diff --git a/.gitignore b/.gitignore index c0f027e..dfb5c1c 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,31 @@ dist/ build/ .pytest_cache/ .mypy_cache/ + +# ---- GC-UI(Flutter 前端)---- +# Flutter / Dart 构建产物与本地工具状态 +GC-UI/frontend/.dart_tool/ +GC-UI/frontend/.flutter-plugins +GC-UI/frontend/.flutter-plugins-dependencies +GC-UI/frontend/.packages +GC-UI/frontend/build/ +GC-UI/frontend/**/Flutter/ephemeral/ +GC-UI/frontend/**/GeneratedPluginRegistrant.* +GC-UI/frontend/**/generated_plugin_registrant.* +GC-UI/frontend/**/generated_plugins.cmake +GC-UI/frontend/**/generated_plugins.h +GC-UI/frontend/**/generated_plugin_registrant.h +GC-UI/frontend/**/generated_plugin_registrant.cc +GC-UI/frontend/**/generated_plugin_registrant.swift +GC-UI/frontend/**/flutter_export_environment.sh +GC-UI/frontend/**/xcschemes/xcschememanagement.plist +GC-UI/frontend/**/Pods/ +GC-UI/frontend/**/Podfile.lock +GC-UI/frontend/**/.symlinks/ +GC-UI/frontend/**/Runner.xcworkspace/xcuserdata/ +GC-UI/frontend/**/Runner.xcodeproj/xcuserdata/ +GC-UI/frontend/**/Runner.xcodeproj/project.xcworkspace/xcuserdata/ +GC-UI/frontend/**/DebugProfile.entitlements.bak +GC-UI/frontend/**/*.iml +GC-UI/frontend/test/shots/ + diff --git a/GC-UI/README.md b/GC-UI/README.md new file mode 100644 index 0000000..1c7e675 --- /dev/null +++ b/GC-UI/README.md @@ -0,0 +1,172 @@ +# GC-UI + +GC 启动器的**前后端分离**实现:界面用 Flutter,服务层留在 .NET。 + +``` +GC-UI/ +├── backend/GC.UI.Server/ # .NET 8 后端:本地 HTTP API + 模型窗口宿主 +│ ├── Program.cs # 所有接口(最小 API) +│ ├── ApiModels.cs # 前后端 JSON 契约 +│ └── AvaloniaHost.cs # 模型窗口宿主(Avalonia,惰性启动) +└── frontend/ # Flutter 前端(Windows / macOS 桌面) + ├── lib/ + │ ├── main.dart # 应用入口 + │ ├── shell.dart # 侧边栏 + 内容区 + 更新状态条 + │ ├── pages.dart # 首页 / 下载 / 设置 / 关于 + │ ├── controller.dart # 外壳状态(设置、健康、更新) + │ ├── api_client.dart # 后端 HTTP 客户端 + DTO + │ ├── i18n.dart # zh-CN / en 文案 + │ └── theme.dart # 配色与通用组件 + ├── windows/ # Windows 原生 runner(flutter create 生成) + ├── macos/ # macOS 原生 runner(flutter create 生成) + └── test/ # 单元测试 + 后端契约测试 + 截图脚本 +``` + +## 为什么这样切 + +原来的 GC 是「Avalonia 界面 + 服务层」一体式应用。拆分时唯一不能动的是**模型契约**: +模型 dll 通过 `IModelRuntime.CreateView` 返回的是 Avalonia `Control`,渲染栈是契约的一部分。 +把渲染换成 Flutter 等于让所有已发布模型失效。 + +所以切法是: + +| 层 | 归属 | 说明 | +|---|---|---| +| 首页 / 下载 / 设置 / 关于 | **Flutter 前端** | 纯界面,通过 HTTP 调后端 | +| 模型扫描、下载、更新、设置持久化 | **.NET 后端** | 直接复用 `GC/src`(GC.Core)与 `GC-DOWNLOAD` | +| 模型自己的窗口 | **.NET 后端** | 模型返回 Avalonia 控件,由后端承载 | + +前端只发一条「启动模型」的指令,模型窗口由后端在自己的 UI 线程上打开。 + +## 前端方案:为什么是 Flutter + +Windows 与 macOS 用**同一套 Flutter 代码 + 各自的原生 runner**: + +- **一套代码两个平台**:`flutter create --platforms=windows,macos` 生成 `windows/`(CMake + Win32 窗口)与 `macos/`(Xcode + Cocoa 窗口)两个原生壳,业务代码 100% 共用。 +- **原生桌面窗口**:不是 WebView 套壳,两个平台都是真正的原生窗口,可设置最小尺寸、标题栏、DPI 缩放。 +- **渲染一致**:Skia/Impeller 自绘,两个平台像素级一致,不需要为 WinUI / AppKit 各写一套控件。 +- **热重载**:`flutter run -d windows` / `-d macos` 改界面即时生效,迭代比 XAML 快。 +- **对比过的替代方案**: + - *继续用 Avalonia*:跨平台没问题,但那就不是「前后端分离 + Flutter 前端」了。 + - *WinUI 3 + SwiftUI 各写一套*:两套 UI 代码、两套状态管理,维护成本翻倍。 + - *Electron / Tauri*:WebView 套壳,包体大(Electron ~150MB)或需要 Rust 工具链,且与 .NET 后端通信仍要额外桥接。 + +## 运行 + +### 1. 启动后端 + +```bash +# 仓库根目录 +dotnet run --project GC-UI/backend/GC.UI.Server + +# 指定端口(默认 17890) +dotnet run --project GC-UI/backend/GC.UI.Server -- --port 17890 +# 或 +GC_UI_PORT=17890 dotnet run --project GC-UI/backend/GC.UI.Server +``` + +启动后会在 `~/.GC/ui-backend.json` 写入 `{ port, pid, url, version, platform }`,前端可据此发现端口。 + +### 2. 启动前端 + +```bash +cd GC-UI/frontend +flutter pub get + +# Windows +flutter run -d windows + +# macOS +flutter run -d macos + +# 后端不在默认端口时 +flutter run -d windows --dart-define=GC_UI_BASE_URL=http://127.0.0.1:18000 +``` + +### 3. 打包 + +```bash +cd GC-UI/frontend +flutter build windows --release # build/windows/x64/runner/Release/ +flutter build macos --release # build/macos/Build/Products/Release/ +``` + +或直接用仓库根目录的脚本: + +```bash +./GC-UI/build-ui.sh # macOS / Linux 上构建(macOS 产物) +GC-UI\build-ui.cmd # Windows 上构建(Windows 产物) +``` + +## HTTP 接口 + +后端只监听 `127.0.0.1`,不对外暴露。 + +| 方法 | 路径 | 说明 | +|---|---|---| +| GET | `/api/health` | 健康检查 + 模型窗口宿主是否可用 | +| GET | `/api/models` | 已安装模型 | +| GET | `/api/models/{id}/preview` | 模型封面图(PNG) | +| POST | `/api/models/{id}/launch` | 启动模型(打开模型自己的窗口) | +| DELETE | `/api/models/{id}` | 删除模型 | +| GET | `/api/settings` | 读取设置 | +| POST | `/api/settings` | 修改设置(补丁式,只改传入字段) | +| GET | `/api/sources` | 模型源列表 | +| POST | `/api/sources/select` | 双源测速并切到最快 | +| GET | `/api/remote/models?sourceId=&force=` | 远端可下载模型 | +| POST | `/api/download` | 入队下载 `{ sourceId, modelId }` | +| GET | `/api/download/jobs` | 下载任务列表 | +| POST | `/api/download/{id}/cancel` | 取消 | +| POST | `/api/download/{id}/retry` | 重试 | +| POST | `/api/download/{id}/remove` | 移除任务 | +| POST | `/api/download/clear-finished` | 清除已完成 | +| POST | `/api/update/check` | 检查模型 / 启动器更新 | +| GET | `/api/about` | 版本 + 贡献者 | +| POST | `/api/shell/open-folder` | 打开目录(仅限启动器自己的目录) | +| POST | `/api/shell/open-url` | 打开 http/https 链接 | + +契约定义见 `backend/GC.UI.Server/ApiModels.cs`,前端对应 `frontend/lib/api_client.dart`。 + +## 测试 + +```bash +# 后端编译 +dotnet build GC-UI/backend/GC.UI.Server + +# 前端静态检查 + 单元测试 +cd GC-UI/frontend +flutter analyze +flutter test + +# 前后端联调(需要后端正在运行;后端没起时自动跳过) +flutter test test/backend_contract_test.dart + +# 生成界面截图到 test/shots/(视觉检查用) +flutter test tool/render_shots_test.dart +``` + +截图脚本覆盖四个页面(首页 / 下载 / 设置 / 关于)再加一整套外壳: +`test/shots/home.png`、`download.png`、`settings.png`、`about.png`、`shell.png`。 +需要先在本机 17890 端口跑起后端;脚本用 `runAsync` 给真实 HTTP 留出时间, +否则 `flutter_test` 的假时钟会让页面停在加载态。 + +## 「关于」页展示的技术栈 + +「关于」页的版本卡片里直接写明这套实现的两个关键点: + +| 行 | 值 | 来源 | +|---|---|---| +| 源码语言 | **C#** | 后端 `/api/about` 返回 `sourceLanguage` | +| 前端 | **Flutter** | 后端 `/api/about` 返回 `frontend` | +| 架构 | Flutter 前端 + .NET 后端(本地 HTTP) | 前端 i18n 文案 | + +两个字段由后端下发(而不是前端写死),所以将来换实现时只改后端一处, +前端和「关于」页自动跟着变。契约字段见 `ApiModels.cs` 的 `AboutDto`, +前端解析在 `lib/api_client.dart` 的 `AboutInfo`。 + +## 安全边界 + +- 后端只绑定 `127.0.0.1`,不接受外部连接。 +- `open-folder` 只允许打开模型库 / 数据目录 / 应用目录之内的路径,避免被当成任意路径执行器。 +- `open-url` 只允许 `http` / `https`。 +- CORS 只放行 `localhost` / `127.0.0.1` 来源,方便 `flutter run -d chrome` 调试界面。 diff --git a/GC-UI/backend/GC.UI.Server/ApiModels.cs b/GC-UI/backend/GC.UI.Server/ApiModels.cs new file mode 100644 index 0000000..b4cad8d --- /dev/null +++ b/GC-UI/backend/GC.UI.Server/ApiModels.cs @@ -0,0 +1,140 @@ +using System.Collections.Generic; + +namespace GC.UI.Server; + +// --------------------------------------------------------------------------- +// 前后端之间的数据契约(HTTP + JSON,camelCase)。 +// 前端(Flutter)只认这些字段,不认 .NET 类型;后端换实现不影响前端。 +// --------------------------------------------------------------------------- + +public sealed record HealthDto( + bool Ok, + string Version, + string Platform, + bool UiAvailable, + string? UiError); + +public sealed record ModelDto( + string Id, + string Name, + string Description, + string Version, + string Author, + long SizeBytes, + string SizeText, + IReadOnlyList Tags, + bool HasPreview, + string PreviewUrl, + string Directory, + string DataDirectory); + +public sealed record SourceDto( + string Id, + string Name, + string Url, + bool Enabled, + bool BuiltIn, + string Host); + +public sealed record RemoteModelDto( + string Id, + string Name, + string Description, + string Version, + long SizeBytes, + string SizeText, + string SourceId, + bool Installed, + string? InstalledVersion); + +public sealed record SourceIndexDto( + string SourceId, + string Root, + bool FromCache, + string? Error, + string ResolvedFrom, + IReadOnlyList Models); + +public sealed record JobDto( + string Id, + string ModelId, + string Name, + string Version, + string State, + double Progress, + string StatusText, + string DetailText, + string? Error, + bool IsActive, + bool CanRetry, + bool IsDone); + +public sealed record LanguageDto(string Code, string Label); + +public sealed record SettingsDto( + string Language, + string Theme, + int RenderFps, + int MemoryMb, + bool MemoryAuto, + bool AutoUpdateOnStartup, + bool RequireSignedManifest, + string UpdateRepository, + string? UpdateLocalRoot, + string? ModelRootOverride, + int MemoryBudgetMb, + string MemoryUsageText, + string ModelRoot, + string DataRoot, + string SettingsFile, + string Version, + string Platform, + IReadOnlyList Sources, + IReadOnlyList Languages); + +/// 设置补丁:只改传进来的字段,null 表示不动。 +public sealed record SettingsPatch( + string? Language, + string? Theme, + int? RenderFps, + int? MemoryMb, + bool? MemoryAuto, + bool? AutoUpdateOnStartup, + bool? RequireSignedManifest, + string? UpdateRepository, + string? UpdateLocalRoot, + string? ModelRootOverride); + +public sealed record LatencyDto(string Id, string Name, long Milliseconds); + +public sealed record UpdateCheckDto( + string Outcome, + string Message, + int UpdatedModels, + IReadOnlyList ModelNames, + string? LauncherMessage, + string? Error, + string? LauncherLatest, + string SourceName, + IReadOnlyList Latency); + +public sealed record ContributorDto(string Name, int Contributions, string? AvatarUrl); + +public sealed record AboutDto( + string AppName, + string Version, + string Platform, + string Repository, + IReadOnlyList Contributors, + string SourceLanguage, + string Frontend); + +public sealed record LaunchResultDto(bool Ok, string Message); + +public sealed record DownloadRequest(string SourceId, string ModelId); + +public sealed record PathRequest(string Path); + +public sealed record UrlRequest(string Url); + +public sealed record ForceRequest(bool Force); diff --git a/GC-UI/backend/GC.UI.Server/AvaloniaHost.cs b/GC-UI/backend/GC.UI.Server/AvaloniaHost.cs new file mode 100644 index 0000000..e6c346f --- /dev/null +++ b/GC-UI/backend/GC.UI.Server/AvaloniaHost.cs @@ -0,0 +1,148 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Threading; +using GC.Models; +using GC.Services; +using GC.Views; + +namespace GC.UI.Server; + +/// +/// 模型窗口宿主。 +/// +/// 为什么渲染这一层留在 .NET:模型 dll 通过 IModelRuntime.CreateView 返回的是 +/// Avalonia ,这是模型契约的一部分。把渲染栈换成 Flutter 等于换掉契约, +/// 所有已发布模型都会失效。所以前后端分离的切法是: +/// · 界面(首页 / 下载 / 设置 / 关于)→ Flutter 前端 +/// · 模型窗口(模型自带界面)→ 仍由 .NET 承载,前端只发一条「启动模型」的指令 +/// +/// 这里惰性启动一个没有主窗口的 Avalonia 桌面生命周期,之后所有模型窗口都在它的 UI 线程上创建。 +/// 无桌面会话(CI / 无头环境)时启动会失败,此时只有「启动模型」不可用,其余接口照常工作。 +/// +public sealed class AvaloniaHost +{ + private readonly AppServices _services; + private readonly object _gate = new(); + private readonly List _windows = new(); + private Task? _startTask; + + public AvaloniaHost(AppServices services) => _services = services; + + public bool IsAvailable { get; private set; } + + public string? LastError { get; private set; } + + public Task EnsureStartedAsync() + { + lock (_gate) + { + _startTask ??= Task.Run(StartCore); + return _startTask; + } + } + + private bool StartCore() + { + var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var thread = new Thread(() => + { + try + { + AppBuilder.Configure() + .UsePlatformDetect() + .AfterSetup(_ => ready.TrySetResult(true)) + .StartWithClassicDesktopLifetime(Array.Empty()); + } + catch (Exception ex) + { + LastError = ex.Message; + ready.TrySetResult(false); + } + }) + { + IsBackground = true, + Name = "gc-ui-avalonia" + }; + + // Windows 上 Avalonia 需要 STA 线程;macOS / Linux 不支持也不必要。 + if (OperatingSystem.IsWindows()) + { + try { thread.SetApartmentState(ApartmentState.STA); } + catch { /* 忽略:部分运行时不允许设置 */ } + } + + thread.Start(); + + if (!ready.Task.Wait(TimeSpan.FromSeconds(30))) + { + LastError = "图形环境初始化超时"; + return false; + } + + IsAvailable = ready.Task.Result; + return IsAvailable; + } + + /// 在 Avalonia UI 线程上加载模型并打开它自己的窗口。 + public async Task LaunchAsync(ModelPackage package) + { + if (!await EnsureStartedAsync().ConfigureAwait(false)) + throw new InvalidOperationException( + LastError ?? "无法初始化图形环境(当前会话没有桌面?)"); + + return await Dispatcher.UIThread.InvokeAsync(async () => + { + PlayerWindow? window = null; + LoadedModel? loaded = null; + try + { + Action requestClose = () => Dispatcher.UIThread.Post(() => + { + try { window?.Close(); } catch { /* 已关闭 */ } + }); + + loaded = await _services.ModelHost.LoadAsync(package, requestClose, null); + + window = new PlayerWindow(package, loaded); + var captured = loaded; + window.Closed += (_, _) => + { + try { captured.Dispose(); } catch { /* 释放失败不影响退出 */ } + lock (_gate) _windows.Remove(window!); + }; + + lock (_gate) _windows.Add(window); + window.Show(); + return $"已启动模型 {package.Id}"; + } + catch + { + try { loaded?.Dispose(); } catch { /* 忽略 */ } + throw; + } + }); + } +} + +/// 后端自己的 Avalonia 应用:没有主窗口,只用来承载模型窗口。 +internal sealed class HostApp : Application +{ + public override void Initialize() { } + + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown; + desktop.MainWindow = null; + } + + base.OnFrameworkInitializationCompleted(); + } +} diff --git a/GC-UI/backend/GC.UI.Server/GC.UI.Server.csproj b/GC-UI/backend/GC.UI.Server/GC.UI.Server.csproj new file mode 100644 index 0000000..195fb6b --- /dev/null +++ b/GC-UI/backend/GC.UI.Server/GC.UI.Server.csproj @@ -0,0 +1,33 @@ + + + + + Exe + enable + true + GC.UI.Server + GC.UI.Server + false + false + + false + + + + + + + + + + + + + diff --git a/GC-UI/backend/GC.UI.Server/Program.cs b/GC-UI/backend/GC.UI.Server/Program.cs new file mode 100644 index 0000000..67746b5 --- /dev/null +++ b/GC-UI/backend/GC.UI.Server/Program.cs @@ -0,0 +1,503 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using GC.Download; +using GC.Models; +using GC.Services; +using GC.UI.Server; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +// --------------------------------------------------------------------------- +// GC-UI 后端:本地 HTTP 服务(只监听 127.0.0.1)。 +// +// 它把原来 GC 启动器里的服务层原样复用(GC.Core / GC-DOWNLOAD), +// 只是把「界面」从 Avalonia 换成 Flutter —— 前端通过下面这些接口驱动后端。 +// +// GET /api/health 健康检查 + 图形环境是否可用 +// GET /api/models 已安装模型 +// GET /api/models/{id}/preview 模型封面图 +// POST /api/models/{id}/launch 启动模型(打开模型自己的窗口) +// DELETE /api/models/{id} 删除模型 +// GET /api/settings 读取设置 +// POST /api/settings 修改设置(补丁式) +// GET /api/sources 模型源列表 +// POST /api/sources/select 双源测速并切到最快 +// GET /api/remote/models 远端可下载模型 +// POST /api/download 入队下载 +// GET /api/download/jobs 下载任务 +// POST /api/download/{id}/cancel|retry|remove +// POST /api/download/clear-finished 清除已完成 +// POST /api/update/check 检查模型 / 启动器更新 +// GET /api/about 版本 + 贡献者 +// POST /api/shell/open-folder|open-url 打开目录 / 链接 +// --------------------------------------------------------------------------- + +var port = ResolvePort(args); + +// 下载模块(GC-DOWNLOAD)通过宿主钩子注入,和 GC-BOOT 的做法一致。 +DownloadModuleHost.Factory = new DownloadModuleFactory(); + +var services = AppServices.Create(); +var uiHost = new AvaloniaHost(services); + +var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args }); +builder.Logging.ClearProviders(); +builder.WebHost.UseUrls($"http://127.0.0.1:{port}"); + +// 桌面端(Windows/macOS)走原生 HTTP,不需要 CORS; +// 这里放开本机回环来源,方便用 `flutter run -d chrome` 调试界面。 +builder.Services.AddCors(options => options.AddDefaultPolicy(policy => policy + .SetIsOriginAllowed(origin => + Uri.TryCreate(origin, UriKind.Absolute, out var uri) && + (uri.Host == "127.0.0.1" || uri.Host == "localhost")) + .AllowAnyHeader() + .AllowAnyMethod())); + +var app = builder.Build(); +app.UseCors(); + +// ---- 健康检查 ------------------------------------------------------------- + +app.MapGet("/api/health", () => Results.Ok(new HealthDto( + true, + LauncherRuntimeInfo.CurrentLauncherVersion, + LauncherRuntimeInfo.CurrentRid, + uiHost.IsAvailable, + uiHost.LastError))); + +// ---- 已安装模型 ----------------------------------------------------------- + +app.MapGet("/api/models", () => + Results.Ok(services.Models.Scan().Select(ToModelDto).ToList())); + +app.MapGet("/api/models/{id}/preview", (string id) => +{ + var package = services.Models.Find(id); + if (package == null || !File.Exists(package.PreviewPath)) return Results.NotFound(); + return Results.File(package.PreviewPath, "image/png"); +}); + +app.MapPost("/api/models/{id}/launch", async (string id) => +{ + var package = services.Models.Find(id); + if (package == null) return Results.NotFound(new LaunchResultDto(false, $"没有找到模型 {id}")); + + try + { + services.Memory.Refresh(); + var message = await uiHost.LaunchAsync(package); + return Results.Ok(new LaunchResultDto(true, message)); + } + catch (Exception ex) + { + return Results.Json(new LaunchResultDto(false, ex.Message), statusCode: 503); + } +}); + +app.MapDelete("/api/models/{id}", (string id) => +{ + var ok = services.Models.Delete(id); + if (ok) services.Models.NotifyChanged(); + return ok + ? Results.Ok(new LaunchResultDto(true, $"已删除模型 {id}")) + : Results.NotFound(new LaunchResultDto(false, $"没有找到模型 {id}")); +}); + +// ---- 设置 ----------------------------------------------------------------- + +app.MapGet("/api/settings", () => Results.Ok(ToSettingsDto())); + +app.MapPost("/api/settings", (SettingsPatch? patch) => +{ + if (patch == null) return Results.BadRequest(new LaunchResultDto(false, "缺少设置内容")); + + services.Settings.Apply(s => + { + if (patch.Language != null) s.Language = patch.Language; + if (patch.Theme != null) s.Theme = patch.Theme; + if (patch.RenderFps.HasValue) s.RenderFps = Math.Clamp(patch.RenderFps.Value, 12, 120); + if (patch.MemoryMb.HasValue) s.MemoryMb = Math.Clamp(patch.MemoryMb.Value, 256, 16384); + if (patch.MemoryAuto.HasValue) s.MemoryAuto = patch.MemoryAuto.Value; + if (patch.AutoUpdateOnStartup.HasValue) s.AutoUpdateOnStartup = patch.AutoUpdateOnStartup.Value; + if (patch.RequireSignedManifest.HasValue) s.RequireSignedManifest = patch.RequireSignedManifest.Value; + if (patch.UpdateRepository != null) s.UpdateRepository = patch.UpdateRepository; + if (patch.UpdateLocalRoot != null) s.UpdateLocalRoot = patch.UpdateLocalRoot; + if (patch.ModelRootOverride != null) s.ModelRootOverride = patch.ModelRootOverride; + }); + + if (patch.Language != null) L.I.SetLanguage(patch.Language); + if (patch.MemoryMb.HasValue || patch.MemoryAuto.HasValue) + services.Memory.ApplyAuto(services.Settings.Current.MemoryAuto, services.Settings.Current.MemoryMb); + + return Results.Ok(ToSettingsDto()); +}); + +// ---- 模型源 --------------------------------------------------------------- + +app.MapGet("/api/sources", () => + Results.Ok(services.Settings.Current.Sources.Select(ToSourceDto).ToList())); + +app.MapPost("/api/sources/select", async (ForceRequest? request) => +{ + var force = request?.Force ?? false; + try + { + var fastest = await services.Selector.PickFastestAsync(force, CancellationToken.None); + services.Updates.UseRemote(services.DownloadModule.CreateRemote(fastest)); + return Results.Ok(new LatencyDto( + fastest.Id, fastest.Name, + services.Selector.LastLatency.TryGetValue(fastest.Id, out var ms) ? ms : 0)); + } + catch (Exception ex) + { + return Results.Json(new LaunchResultDto(false, ex.Message), statusCode: 503); + } +}); + +app.MapGet("/api/remote/models", async (string? sourceId, bool force) => +{ + var source = ResolveSource(sourceId); + if (source == null) return Results.NotFound(new LaunchResultDto(false, "没有可用的模型源")); + + var index = await services.Sources.FetchAsync(source, force, null, CancellationToken.None); + var installed = services.Models.Scan() + .ToDictionary(p => p.Id, p => p.Manifest.Version, StringComparer.OrdinalIgnoreCase); + + return Results.Ok(new SourceIndexDto( + index.SourceId, + index.Root, + index.FromCache, + index.Error, + index.ResolvedFrom, + index.Models.Select(m => new RemoteModelDto( + m.Id, + m.LocalizedName, + m.LocalizedDescription, + m.Manifest.Version, + m.SizeBytes, + ModelScanner.HumanSize(m.SizeBytes), + m.SourceId, + installed.ContainsKey(m.Id), + installed.TryGetValue(m.Id, out var v) ? v : null)).ToList())); +}); + +// ---- 下载 ----------------------------------------------------------------- + +app.MapPost("/api/download", async (DownloadRequest? request) => +{ + if (request == null || string.IsNullOrWhiteSpace(request.ModelId)) + return Results.BadRequest(new LaunchResultDto(false, "缺少 modelId")); + + var source = ResolveSource(request.SourceId); + if (source == null) return Results.NotFound(new LaunchResultDto(false, "没有可用的模型源")); + + var index = await services.Sources.FetchAsync(source, false, null, CancellationToken.None); + var model = index.Models.FirstOrDefault(m => + m.Id.Equals(request.ModelId, StringComparison.OrdinalIgnoreCase)); + if (model == null) + return Results.NotFound(new LaunchResultDto(false, $"源里没有模型 {request.ModelId}")); + + var job = services.Downloads.Enqueue(model); + return Results.Ok(ToJobDto(job)); +}); + +app.MapGet("/api/download/jobs", () => + Results.Ok(services.Downloads.Jobs.Select(ToJobDto).ToList())); + +app.MapPost("/api/download/{id}/cancel", (string id) => + ActOnJob(id, job => services.Downloads.Cancel(job))); + +app.MapPost("/api/download/{id}/retry", (string id) => + ActOnJob(id, job => services.Downloads.Retry(job))); + +app.MapPost("/api/download/{id}/remove", (string id) => + ActOnJob(id, job => services.Downloads.Remove(job))); + +app.MapPost("/api/download/clear-finished", () => +{ + services.Downloads.ClearFinished(); + return Results.Ok(new LaunchResultDto(true, "已清除完成的任务")); +}); + +// ---- 更新 ----------------------------------------------------------------- + +app.MapPost("/api/update/check", async (ForceRequest? request) => +{ + var force = request?.Force ?? true; + var messages = new List(); + + try + { + var fastest = await services.Selector.PickFastestAsync(force, CancellationToken.None); + services.Updates.UseRemote(services.DownloadModule.CreateRemote(fastest)); + } + catch (Exception ex) + { + Console.Error.WriteLine($"[update] 测速失败,沿用当前源: {ex.Message}"); + } + + string? launcherLatest = null; + try + { + launcherLatest = await services.LauncherUpdates.CheckAsync( + services.Updates.Remote, CancellationToken.None); + } + catch (Exception ex) + { + Console.Error.WriteLine($"[update] 启动器版本检查失败: {ex.Message}"); + } + + var progress = new Progress(p => + { + if (!string.IsNullOrWhiteSpace(p.Message)) messages.Add(p.Message); + }); + + var result = await services.Updates.RunAsync(force, progress, CancellationToken.None); + + return Results.Ok(new UpdateCheckDto( + result.Outcome.ToString(), + result.Message, + result.UpdatedModels, + result.ModelNames, + result.LauncherMessage, + result.Error, + launcherLatest, + services.Updates.Remote.DisplayName, + services.Selector.LastLatency + .Select(kv => new LatencyDto( + kv.Key, + SourcePreset.Find(kv.Key)?.Name ?? kv.Key, + kv.Value)) + .ToList())); +}); + +// ---- 关于 ----------------------------------------------------------------- + +app.MapGet("/api/about", async () => +{ + var repository = services.Settings.Current.UpdateRepository; + var contributors = new List(); + try + { + foreach (var c in await ContributorsService.FetchAsync(repository, CancellationToken.None)) + contributors.Add(new ContributorDto(c.DisplayName, c.Contributions, c.AvatarUrl)); + } + catch (Exception ex) + { + Console.Error.WriteLine($"[about] 读取贡献者失败: {ex.Message}"); + } + + return Results.Ok(new AboutDto( + "Morris GC", + LauncherRuntimeInfo.CurrentLauncherVersion, + LauncherRuntimeInfo.CurrentRid, + repository, + contributors, + // 「关于」页展示的技术栈信息:源码语言与前端框架。 + SourceLanguage: "C#", + Frontend: "Flutter")); +}); + +// ---- 系统集成 ------------------------------------------------------------- + +app.MapPost("/api/shell/open-folder", (PathRequest? request) => +{ + var path = request?.Path; + if (string.IsNullOrWhiteSpace(path)) + return Results.BadRequest(new LaunchResultDto(false, "缺少 path")); + + // 只允许打开启动器自己的目录,避免前端被当成任意路径执行器 + if (!IsInsideKnownRoot(path!)) + return Results.BadRequest(new LaunchResultDto(false, "只允许打开启动器自己的目录")); + + Shell.OpenFolder(path!); + return Results.Ok(new LaunchResultDto(true, "已打开目录")); +}); + +app.MapPost("/api/shell/open-url", (UrlRequest? request) => +{ + var url = request?.Url; + if (string.IsNullOrWhiteSpace(url) || !Uri.TryCreate(url, UriKind.Absolute, out var uri)) + return Results.BadRequest(new LaunchResultDto(false, "URL 无效")); + + if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) + return Results.BadRequest(new LaunchResultDto(false, "只允许 http/https 链接")); + + Shell.OpenUrl(url!); + return Results.Ok(new LaunchResultDto(true, "已打开链接")); +}); + +// ---- 启动 ----------------------------------------------------------------- + +WriteEndpointFile(services, port); +Console.WriteLine($"[GC-UI] 后端已启动: http://127.0.0.1:{port}"); +Console.WriteLine($"[GC-UI] 模型库: {services.Paths.ModelRoot}"); + +app.Run(); + +// --------------------------------------------------------------------------- +// 局部辅助 +// --------------------------------------------------------------------------- + +static int ResolvePort(string[] args) +{ + var env = Environment.GetEnvironmentVariable("GC_UI_PORT"); + if (int.TryParse(env, out var fromEnv) && fromEnv > 0 && fromEnv < 65536) return fromEnv; + + for (var i = 0; i < args.Length; i++) + { + if (args[i] == "--port" && i + 1 < args.Length && + int.TryParse(args[i + 1], out var next) && next > 0 && next < 65536) + return next; + + const string prefix = "--port="; + if (args[i].StartsWith(prefix, StringComparison.Ordinal) && + int.TryParse(args[i][prefix.Length..], out var inline) && inline > 0 && inline < 65536) + return inline; + } + + return 17890; +} + +static void WriteEndpointFile(AppServices services, int port) +{ + try + { + var file = Path.Combine(services.Paths.HomeRoot, "ui-backend.json"); + var payload = JsonSerializer.Serialize(new + { + port, + pid = Environment.ProcessId, + url = $"http://127.0.0.1:{port}", + version = LauncherRuntimeInfo.CurrentLauncherVersion, + platform = LauncherRuntimeInfo.CurrentRid, + startedAt = DateTimeOffset.UtcNow.ToString("o") + }, new JsonSerializerOptions { WriteIndented = true }); + + File.WriteAllText(file, payload); + } + catch (Exception ex) + { + Console.Error.WriteLine($"[GC-UI] 写入端点文件失败: {ex.Message}"); + } +} + +ModelDto ToModelDto(ModelPackage package) => new( + package.Id, + package.LocalizedName, + package.LocalizedDescription, + package.Manifest.Version, + package.Manifest.Author, + package.SizeBytes, + ModelScanner.HumanSize(package.SizeBytes), + package.Manifest.Tags ?? new List(), + File.Exists(package.PreviewPath), + $"/api/models/{package.Id}/preview", + package.Directory, + package.DataDirectory); + +SourceDto ToSourceDto(ModelSource source) => new( + source.Id, + string.IsNullOrWhiteSpace(source.Name) ? source.Id : source.Name, + source.Url, + source.Enabled, + source.BuiltIn, + source.DisplayHost); + +SettingsDto ToSettingsDto() => new( + services.Settings.Current.Language, + services.Settings.Current.Theme, + services.Settings.Current.RenderFps, + services.Settings.Current.MemoryMb, + services.Settings.Current.MemoryAuto, + services.Settings.Current.AutoUpdateOnStartup, + services.Settings.Current.RequireSignedManifest, + services.Settings.Current.UpdateRepository, + services.Settings.Current.UpdateLocalRoot, + services.Settings.Current.ModelRootOverride, + services.Memory.BudgetMb, + services.Memory.UsageText, + services.Paths.ModelRoot, + services.Paths.DataRoot, + services.Paths.SettingsFile, + LauncherRuntimeInfo.CurrentLauncherVersion, + LauncherRuntimeInfo.CurrentRid, + services.Settings.Current.Sources.Select(ToSourceDto).ToList(), + L.Supported.Select(s => new LanguageDto(s.Code, s.Label)).ToList()); + +JobDto ToJobDto(IDownloadJob job) => new( + job.Id, + job.Model.Id, + job.Name, + job.Version, + job.State.ToString(), + job.Progress, + job.StatusText, + job.DetailText, + job.Error, + job.IsActive, + job.CanRetry, + job.IsDone); + +ModelSource? ResolveSource(string? sourceId) +{ + var sources = services.Settings.Current.Sources; + if (!string.IsNullOrWhiteSpace(sourceId)) + { + var exact = sources.FirstOrDefault(s => + s.Id.Equals(sourceId, StringComparison.OrdinalIgnoreCase)); + if (exact != null) return exact; + } + + return sources.FirstOrDefault(s => s.Enabled && !string.IsNullOrWhiteSpace(s.Url)) + ?? sources.FirstOrDefault(); +} + +IResult ActOnJob(string id, Action action) +{ + var job = services.Downloads.Jobs.FirstOrDefault(j => + j.Id.Equals(id, StringComparison.OrdinalIgnoreCase)); + if (job == null) return Results.NotFound(new LaunchResultDto(false, $"没有找到任务 {id}")); + + action(job); + return Results.Ok(ToJobDto(job)); +} + +bool IsInsideKnownRoot(string path) +{ + try + { + var full = Path.GetFullPath(path); + var roots = new[] + { + services.Paths.ModelRoot, + services.Paths.DataRoot, + services.Paths.HomeRoot, + services.Paths.AppRoot + }; + + foreach (var root in roots) + { + if (string.IsNullOrWhiteSpace(root)) continue; + var rootFull = Path.GetFullPath(root); + if (full.Equals(rootFull, StringComparison.OrdinalIgnoreCase)) return true; + if (full.StartsWith(rootFull + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + return true; + } + } + catch + { + return false; + } + + return false; +} diff --git a/GC-UI/build-ui.cmd b/GC-UI/build-ui.cmd new file mode 100644 index 0000000..b7b09cf --- /dev/null +++ b/GC-UI/build-ui.cmd @@ -0,0 +1,29 @@ +@echo off +REM 构建 GC-UI 前端(Windows 上运行;macOS 请用 build-ui.sh)。 +REM +REM GC-UI\build-ui.cmd + +setlocal +set ROOT=%~dp0.. +set FRONTEND=%ROOT%\GC-UI\frontend + +where flutter >nul 2>nul +if errorlevel 1 ( + echo 找不到 flutter,请先安装 Flutter SDK 并加入 PATH。 + exit /b 1 +) + +echo ==^> 构建后端(GC.UI.Server) +dotnet build "%ROOT%\GC-UI\backend\GC.UI.Server\GC.UI.Server.csproj" -c Release +if errorlevel 1 exit /b 1 + +echo ==^> 构建前端(windows) +cd /d "%FRONTEND%" +call flutter pub get +if errorlevel 1 exit /b 1 +call flutter build windows --release +if errorlevel 1 exit /b 1 + +echo ==^> 完成 +echo 产物: %FRONTEND%\build\windows\x64\runner\Release\ +endlocal diff --git a/GC-UI/build-ui.sh b/GC-UI/build-ui.sh new file mode 100755 index 0000000..95b2873 --- /dev/null +++ b/GC-UI/build-ui.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# 构建 GC-UI 前端(macOS / Linux 上运行;Windows 请用 build-ui.cmd)。 +# +# ./GC-UI/build-ui.sh # 构建当前平台 +# ./GC-UI/build-ui.sh macos # 指定目标 +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +FRONTEND="$ROOT/GC-UI/frontend" +TARGET="${1:-}" + +if ! command -v flutter >/dev/null 2>&1; then + echo "找不到 flutter,请先安装 Flutter SDK 并加入 PATH。" >&2 + exit 1 +fi + +if [ -z "$TARGET" ]; then + case "$(uname -s)" in + Darwin) TARGET="macos" ;; + *) TARGET="macos" ;; + esac +fi + +echo "==> 构建后端(GC.UI.Server)" +dotnet build "$ROOT/GC-UI/backend/GC.UI.Server/GC.UI.Server.csproj" -c Release + +echo "==> 构建前端($TARGET)" +cd "$FRONTEND" +flutter pub get +flutter build "$TARGET" --release + +echo "==> 完成" +case "$TARGET" in + macos) echo "产物: $FRONTEND/build/macos/Build/Products/Release/" ;; + windows) echo "产物: $FRONTEND/build/windows/x64/runner/Release/" ;; + *) echo "产物: $FRONTEND/build/$TARGET/" ;; +esac diff --git a/GC-UI/frontend/.gitignore b/GC-UI/frontend/.gitignore new file mode 100644 index 0000000..29a3a50 --- /dev/null +++ b/GC-UI/frontend/.gitignore @@ -0,0 +1,43 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/GC-UI/frontend/.metadata b/GC-UI/frontend/.metadata new file mode 100644 index 0000000..b3d77c5 --- /dev/null +++ b/GC-UI/frontend/.metadata @@ -0,0 +1,33 @@ +# 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: macos + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: windows + 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' diff --git a/GC-UI/frontend/README.md b/GC-UI/frontend/README.md new file mode 100644 index 0000000..bff9a70 --- /dev/null +++ b/GC-UI/frontend/README.md @@ -0,0 +1,16 @@ +# gc_ui + +GC launcher UI (Flutter frontend) + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/GC-UI/frontend/analysis_options.yaml b/GC-UI/frontend/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/GC-UI/frontend/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/GC-UI/frontend/lib/api_client.dart b/GC-UI/frontend/lib/api_client.dart new file mode 100644 index 0000000..b5291b5 --- /dev/null +++ b/GC-UI/frontend/lib/api_client.dart @@ -0,0 +1,466 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; + +/// 后端返回的错误(HTTP 非 2xx,或后端明确返回 ok=false)。 +class ApiException implements Exception { + ApiException(this.message, {this.statusCode}); + + final String message; + final int? statusCode; + + @override + String toString() => message; +} + +/// 已安装模型。 +class ModelInfo { + ModelInfo.fromJson(Map json) + : id = json['id'] as String? ?? '', + name = json['name'] as String? ?? '', + description = json['description'] as String? ?? '', + version = json['version'] as String? ?? '', + author = json['author'] as String? ?? '', + sizeBytes = (json['sizeBytes'] as num?)?.toInt() ?? 0, + sizeText = json['sizeText'] as String? ?? '', + tags = _stringList(json['tags']), + hasPreview = json['hasPreview'] as bool? ?? false, + previewUrl = json['previewUrl'] as String? ?? '', + directory = json['directory'] as String? ?? '', + dataDirectory = json['dataDirectory'] as String? ?? ''; + + final String id; + final String name; + final String description; + final String version; + final String author; + final int sizeBytes; + final String sizeText; + final List tags; + final bool hasPreview; + final String previewUrl; + final String directory; + final String dataDirectory; + + String get metaText => 'v$version · $sizeText'; +} + +/// 模型源。 +class SourceInfo { + SourceInfo.fromJson(Map json) + : id = json['id'] as String? ?? '', + name = json['name'] as String? ?? '', + url = json['url'] as String? ?? '', + enabled = json['enabled'] as bool? ?? false, + builtIn = json['builtIn'] as bool? ?? false, + host = json['host'] as String? ?? ''; + + final String id; + final String name; + final String url; + final bool enabled; + final bool builtIn; + final String host; +} + +/// 远端可下载模型。 +class RemoteModelInfo { + RemoteModelInfo.fromJson(Map json) + : id = json['id'] as String? ?? '', + name = json['name'] as String? ?? '', + description = json['description'] as String? ?? '', + version = json['version'] as String? ?? '', + sizeBytes = (json['sizeBytes'] as num?)?.toInt() ?? 0, + sizeText = json['sizeText'] as String? ?? '', + sourceId = json['sourceId'] as String? ?? '', + installed = json['installed'] as bool? ?? false, + installedVersion = json['installedVersion'] as String?; + + final String id; + final String name; + final String description; + final String version; + final int sizeBytes; + final String sizeText; + final String sourceId; + final bool installed; + final String? installedVersion; +} + +/// 一次远端源索引结果。 +class SourceIndexInfo { + SourceIndexInfo.fromJson(Map json) + : sourceId = json['sourceId'] as String? ?? '', + root = json['root'] as String? ?? '', + fromCache = json['fromCache'] as bool? ?? false, + error = json['error'] as String?, + resolvedFrom = json['resolvedFrom'] as String? ?? '', + models = (json['models'] as List? ?? const []) + .map((e) => RemoteModelInfo.fromJson(e as Map)) + .toList(); + + final String sourceId; + final String root; + final bool fromCache; + final String? error; + final String resolvedFrom; + final List models; +} + +/// 下载任务。 +class JobInfo { + JobInfo.fromJson(Map json) + : id = json['id'] as String? ?? '', + modelId = json['modelId'] as String? ?? '', + name = json['name'] as String? ?? '', + version = json['version'] as String? ?? '', + state = json['state'] as String? ?? 'Queued', + progress = (json['progress'] as num?)?.toDouble() ?? 0, + statusText = json['statusText'] as String? ?? '', + detailText = json['detailText'] as String? ?? '', + error = json['error'] as String?, + isActive = json['isActive'] as bool? ?? false, + canRetry = json['canRetry'] as bool? ?? false, + isDone = json['isDone'] as bool? ?? false; + + final String id; + final String modelId; + final String name; + final String version; + final String state; + final double progress; + final String statusText; + final String detailText; + final String? error; + final bool isActive; + final bool canRetry; + final bool isDone; +} + +/// 界面语言选项。 +class LanguageInfo { + LanguageInfo.fromJson(Map json) + : code = json['code'] as String? ?? '', + label = json['label'] as String? ?? ''; + + final String code; + final String label; +} + +/// 设置。 +class SettingsInfo { + SettingsInfo.fromJson(Map json) + : language = json['language'] as String? ?? 'auto', + theme = json['theme'] as String? ?? 'light', + renderFps = (json['renderFps'] as num?)?.toInt() ?? 120, + memoryMb = (json['memoryMb'] as num?)?.toInt() ?? 2048, + memoryAuto = json['memoryAuto'] as bool? ?? true, + autoUpdateOnStartup = json['autoUpdateOnStartup'] as bool? ?? true, + requireSignedManifest = json['requireSignedManifest'] as bool? ?? true, + updateRepository = json['updateRepository'] as String? ?? '', + updateLocalRoot = json['updateLocalRoot'] as String?, + modelRootOverride = json['modelRootOverride'] as String?, + memoryBudgetMb = (json['memoryBudgetMb'] as num?)?.toInt() ?? 0, + memoryUsageText = json['memoryUsageText'] as String? ?? '', + modelRoot = json['modelRoot'] as String? ?? '', + dataRoot = json['dataRoot'] as String? ?? '', + settingsFile = json['settingsFile'] as String? ?? '', + version = json['version'] as String? ?? '', + platform = json['platform'] as String? ?? '', + sources = (json['sources'] as List? ?? const []) + .map((e) => SourceInfo.fromJson(e as Map)) + .toList(), + languages = (json['languages'] as List? ?? const []) + .map((e) => LanguageInfo.fromJson(e as Map)) + .toList(); + + final String language; + final String theme; + final int renderFps; + final int memoryMb; + final bool memoryAuto; + final bool autoUpdateOnStartup; + final bool requireSignedManifest; + final String updateRepository; + final String? updateLocalRoot; + final String? modelRootOverride; + final int memoryBudgetMb; + final String memoryUsageText; + final String modelRoot; + final String dataRoot; + final String settingsFile; + final String version; + final String platform; + final List sources; + final List languages; +} + +/// 设置补丁:只提交要改的字段。 +class SettingsPatch { + const SettingsPatch({ + this.language, + this.theme, + this.renderFps, + this.memoryMb, + this.memoryAuto, + this.autoUpdateOnStartup, + this.requireSignedManifest, + this.updateRepository, + this.updateLocalRoot, + this.modelRootOverride, + }); + + final String? language; + final String? theme; + final int? renderFps; + final int? memoryMb; + final bool? memoryAuto; + final bool? autoUpdateOnStartup; + final bool? requireSignedManifest; + final String? updateRepository; + final String? updateLocalRoot; + final String? modelRootOverride; + + Map toJson() { + final map = {}; + if (language != null) map['language'] = language; + if (theme != null) map['theme'] = theme; + if (renderFps != null) map['renderFps'] = renderFps; + if (memoryMb != null) map['memoryMb'] = memoryMb; + if (memoryAuto != null) map['memoryAuto'] = memoryAuto; + if (autoUpdateOnStartup != null) map['autoUpdateOnStartup'] = autoUpdateOnStartup; + if (requireSignedManifest != null) map['requireSignedManifest'] = requireSignedManifest; + if (updateRepository != null) map['updateRepository'] = updateRepository; + if (updateLocalRoot != null) map['updateLocalRoot'] = updateLocalRoot; + if (modelRootOverride != null) map['modelRootOverride'] = modelRootOverride; + return map; + } +} + +/// 健康检查。 +class HealthInfo { + HealthInfo.fromJson(Map json) + : ok = json['ok'] as bool? ?? false, + version = json['version'] as String? ?? '', + platform = json['platform'] as String? ?? '', + uiAvailable = json['uiAvailable'] as bool? ?? false, + uiError = json['uiError'] as String?; + + final bool ok; + final String version; + final String platform; + final bool uiAvailable; + final String? uiError; +} + +/// 一次更新检查的结果。 +class UpdateCheckInfo { + UpdateCheckInfo.fromJson(Map json) + : outcome = json['outcome'] as String? ?? '', + message = json['message'] as String? ?? '', + updatedModels = (json['updatedModels'] as num?)?.toInt() ?? 0, + modelNames = _stringList(json['modelNames']), + launcherMessage = json['launcherMessage'] as String?, + error = json['error'] as String?, + launcherLatest = json['launcherLatest'] as String?, + sourceName = json['sourceName'] as String? ?? ''; + + final String outcome; + final String message; + final int updatedModels; + final List modelNames; + final String? launcherMessage; + final String? error; + final String? launcherLatest; + final String sourceName; +} + +/// 贡献者。 +class ContributorInfo { + ContributorInfo.fromJson(Map json) + : name = json['name'] as String? ?? '', + contributions = (json['contributions'] as num?)?.toInt() ?? 0, + avatarUrl = json['avatarUrl'] as String?; + + final String name; + final int contributions; + final String? avatarUrl; +} + +/// 关于页数据。 +class AboutInfo { + AboutInfo.fromJson(Map json) + : appName = json['appName'] as String? ?? '', + version = json['version'] as String? ?? '', + platform = json['platform'] as String? ?? '', + repository = json['repository'] as String? ?? '', + sourceLanguage = json['sourceLanguage'] as String? ?? 'C#', + frontend = json['frontend'] as String? ?? 'Flutter', + contributors = (json['contributors'] as List? ?? const []) + .map((e) => ContributorInfo.fromJson(e as Map)) + .toList(); + + final String appName; + final String version; + final String platform; + final String repository; + + /// 源码语言(后端 / 模型层),由后端 `/api/about` 返回。 + final String sourceLanguage; + + /// 前端框架,由后端 `/api/about` 返回。 + final String frontend; + + final List contributors; +} + +/// 通用操作结果。 +class ActionResult { + ActionResult.fromJson(Map json) + : ok = json['ok'] as bool? ?? false, + message = json['message'] as String? ?? ''; + + final bool ok; + final String message; +} + +List _stringList(dynamic value) => + (value as List? ?? const []).map((e) => e.toString()).toList(); + +/// GC-UI 后端客户端。 +/// +/// 后端是本地伴随进程,默认监听 127.0.0.1:17890;端口可用 +/// `--dart-define=GC_UI_BASE_URL=http://127.0.0.1:12345` 覆盖。 +class GcApi { + GcApi({String? baseUrl}) + : baseUrl = baseUrl ?? defaultBaseUrl; + + static const String defaultBaseUrl = String.fromEnvironment( + 'GC_UI_BASE_URL', + defaultValue: 'http://127.0.0.1:17890', + ); + + final String baseUrl; + + Uri _uri(String path, [Map? query]) => + Uri.parse('$baseUrl$path').replace(queryParameters: query); + + Future _send(String method, String path, + {Map? query, Object? body}) async { + final uri = _uri(path, query); + late http.Response response; + try { + switch (method) { + case 'GET': + response = await http.get(uri).timeout(const Duration(seconds: 30)); + break; + case 'POST': + response = await http + .post(uri, + headers: const {'Content-Type': 'application/json'}, + body: body == null ? null : jsonEncode(body)) + .timeout(const Duration(seconds: 120)); + break; + case 'DELETE': + response = await http.delete(uri).timeout(const Duration(seconds: 30)); + break; + default: + throw ApiException('不支持的方法 $method'); + } + } on ApiException { + rethrow; + } catch (error) { + throw ApiException('无法连接后端($baseUrl):$error'); + } + + final text = utf8.decode(response.bodyBytes); + dynamic decoded; + if (text.isNotEmpty) { + try { + decoded = jsonDecode(text); + } catch (_) { + decoded = null; + } + } + + if (response.statusCode >= 400) { + final message = decoded is Map + ? (decoded['message'] as String? ?? 'HTTP ${response.statusCode}') + : 'HTTP ${response.statusCode}'; + throw ApiException(message, statusCode: response.statusCode); + } + + return decoded; + } + + List> _asList(dynamic value) => + (value as List? ?? const []) + .map((e) => e as Map) + .toList(); + + Future health() async => + HealthInfo.fromJson(await _send('GET', '/api/health') as Map); + + Future> models() async => + _asList(await _send('GET', '/api/models')).map(ModelInfo.fromJson).toList(); + + Future launchModel(String id) async => ActionResult.fromJson( + await _send('POST', '/api/models/$id/launch') as Map); + + Future deleteModel(String id) async => ActionResult.fromJson( + await _send('DELETE', '/api/models/$id') as Map); + + Future settings() async => + SettingsInfo.fromJson(await _send('GET', '/api/settings') as Map); + + Future saveSettings(SettingsPatch patch) async => + SettingsInfo.fromJson(await _send('POST', '/api/settings', body: patch.toJson()) + as Map); + + Future> sources() async => + _asList(await _send('GET', '/api/sources')).map(SourceInfo.fromJson).toList(); + + Future remoteModels({String? sourceId, bool force = false}) async => + SourceIndexInfo.fromJson(await _send('GET', '/api/remote/models', query: { + if (sourceId != null) 'sourceId': sourceId, + 'force': force.toString(), + }) as Map); + + Future> jobs() async => + _asList(await _send('GET', '/api/download/jobs')).map(JobInfo.fromJson).toList(); + + Future startDownload(String sourceId, String modelId) async => + JobInfo.fromJson(await _send('POST', '/api/download', + body: {'sourceId': sourceId, 'modelId': modelId}) as Map); + + Future cancelJob(String id) async => JobInfo.fromJson( + await _send('POST', '/api/download/$id/cancel') as Map); + + Future retryJob(String id) async => JobInfo.fromJson( + await _send('POST', '/api/download/$id/retry') as Map); + + Future removeJob(String id) async => JobInfo.fromJson( + await _send('POST', '/api/download/$id/remove') as Map); + + Future clearFinished() async => ActionResult.fromJson( + await _send('POST', '/api/download/clear-finished') as Map); + + Future checkUpdate({bool force = true}) async => + UpdateCheckInfo.fromJson( + await _send('POST', '/api/update/check', body: {'force': force}) + as Map); + + Future about() async => + AboutInfo.fromJson(await _send('GET', '/api/about') as Map); + + Future openFolder(String path) async => ActionResult.fromJson( + await _send('POST', '/api/shell/open-folder', body: {'path': path}) + as Map); + + Future openUrl(String url) async => ActionResult.fromJson( + await _send('POST', '/api/shell/open-url', body: {'url': url}) + as Map); + + /// 模型封面图地址(直接给 Image.network 用)。 + String previewUrl(ModelInfo model) => '$baseUrl${model.previewUrl}'; +} diff --git a/GC-UI/frontend/lib/controller.dart b/GC-UI/frontend/lib/controller.dart new file mode 100644 index 0000000..a32820d --- /dev/null +++ b/GC-UI/frontend/lib/controller.dart @@ -0,0 +1,114 @@ +import 'package:flutter/foundation.dart'; + +import 'api_client.dart'; +import 'i18n.dart'; + +/// 外壳状态:后端客户端 + 设置 + 健康状态 + 更新状态条。 +/// +/// 各页面只读这里的数据、通过这里的方法改后端,避免每页各持一份状态。 +class ShellController extends ChangeNotifier { + ShellController({GcApi? api}) : api = api ?? GcApi(); + + final GcApi api; + + int index = 0; + SettingsInfo? settings; + HealthInfo? health; + String? loadError; + + bool updateBarVisible = false; + bool updateBusy = false; + double updateProgress = 0; + String updateStatus = ''; + String updateDetail = ''; + String launcherNotice = ''; + + bool get backendReady => settings != null; + + Future bootstrap() async { + try { + health = await api.health(); + settings = await api.settings(); + loadError = null; + I18n.setLanguage(settings!.language); + } catch (error) { + loadError = error.toString(); + } + notifyListeners(); + } + + void goTo(int value) { + if (index == value) return; + index = value; + notifyListeners(); + } + + Future reloadSettings() async { + try { + settings = await api.settings(); + loadError = null; + I18n.setLanguage(settings!.language); + } catch (error) { + loadError = error.toString(); + } + notifyListeners(); + } + + Future saveSettings(SettingsPatch patch) async { + try { + settings = await api.saveSettings(patch); + loadError = null; + I18n.setLanguage(settings!.language); + } catch (error) { + loadError = error.toString(); + } + notifyListeners(); + } + + void setUpdateStatus({ + bool? visible, + bool? busy, + double? progress, + String? status, + String? detail, + String? notice, + }) { + if (visible != null) updateBarVisible = visible; + if (busy != null) updateBusy = busy; + if (progress != null) updateProgress = progress; + if (status != null) updateStatus = status; + if (detail != null) updateDetail = detail; + if (notice != null) launcherNotice = notice; + notifyListeners(); + } + + /// 检查模型 / 启动器更新(设置页与状态条共用)。 + Future checkUpdate({bool force = true}) async { + if (updateBusy) return; + setUpdateStatus( + visible: true, + busy: true, + progress: 0, + status: T('update.checking'), + detail: '', + notice: '', + ); + + try { + final result = await api.checkUpdate(force: force); + setUpdateStatus( + busy: false, + progress: 1, + status: result.message.isEmpty ? T('update.done') : result.message, + detail: result.error ?? '', + notice: result.launcherMessage ?? '', + ); + } catch (error) { + setUpdateStatus( + busy: false, + status: T('update.offline'), + detail: error.toString(), + ); + } + } +} diff --git a/GC-UI/frontend/lib/i18n.dart b/GC-UI/frontend/lib/i18n.dart new file mode 100644 index 0000000..1574e16 --- /dev/null +++ b/GC-UI/frontend/lib/i18n.dart @@ -0,0 +1,274 @@ +import 'package:flutter/widgets.dart'; + +/// 轻量 i18n:键值表 + 运行时切换,和后端 `GC/src/Assets/i18n/*.json` 的键保持一致。 +class I18n { + I18n._(); + + static const List supported = ['zh-CN', 'en']; + + static final ValueNotifier language = ValueNotifier('zh-CN'); + + static const Map> _tables = >{ + 'zh-CN': { + 'app.name': 'Morris GC', + 'app.tagline': '天文教学模型 · 可视化启动器', + 'nav.home': '主页', + 'nav.download': '下载', + 'nav.settings': '设置', + 'nav.about': '关于', + 'home.title': '模型库', + 'home.subtitle': '选择模型,用可交互的三维演示讲清自转、公转与四季成因。', + 'home.launch': '启动模型', + 'home.download': '下载模型', + 'home.settings': '设置', + 'home.installed': '已安装模型', + 'home.count': '{0} 个模型', + 'home.empty': '模型库还是空的', + 'home.emptyHint': '启动时会自动检查并下载模型。若当前断网:可把模型文件夹放进 .GC/model/ 后重新打开,或联网后在「下载」页点重试。', + 'home.emptyAction': '去下载模型', + 'home.open': '打开目录', + 'home.delete': '删除', + 'home.deleteConfirm': '删除模型「{0}」?模型文件会从本地模型库移除。', + 'home.stats.models': '已安装', + 'home.stats.sources': '模型源', + 'home.stats.memory': '内存预算', + 'home.recent': '选择模型后点击「启动模型」', + 'home.launchHint': '模型在自己的窗口里运行,可播放/暂停、切换视角并使用教学要点。', + 'dl.title': '下载模型', + 'dl.subtitle': '从内置模型源读取可下载模型;模型源在「设置」里查看。', + 'dl.sources': '模型源', + 'dl.refresh': '刷新', + 'dl.available': '可用模型', + 'dl.download': '下载', + 'dl.installed': '已安装', + 'dl.reinstall': '重新下载', + 'dl.background': '后台任务', + 'dl.bgEmpty': '暂无后台任务', + 'dl.cancel': '取消', + 'dl.retry': '重试', + 'dl.clearDone': '清除已完成', + 'dl.removeTask': '移除', + 'dl.status.queued': '排队中', + 'dl.status.downloading': '下载中', + 'dl.status.done': '已完成', + 'dl.status.failed': '失败', + 'dl.status.canceled': '已取消', + 'dl.empty': '这个源里没有模型', + 'dl.emptyHint': '仓库需要包含 model/<模型ID>/<模型ID>.json 结构', + 'dl.syncing': '正在读取模型源…', + 'dl.ready': '共 {0} 个模型', + 'dl.fromCache': '本地缓存', + 'dl.pickSource': '选择一个模型源,查看可下载的模型', + 'set.title': '设置', + 'set.subtitle': '模型源、启动时内存分配与本地存储。', + 'set.general': '通用', + 'set.language': '界面语言', + 'set.language.auto': '跟随系统', + 'set.fps': '渲染帧率', + 'set.fps.desc': '越高越顺滑,CPU 占用也越高。', + 'set.memory': '启动时运行内存分配', + 'set.memory.desc': '启动器把这份预算交给模型:模型自己决定用它缓存多少数据(贴图分辨率、缓冲等)。', + 'set.memory.current': '当前占用', + 'set.memory.auto': '自动(根据设备内存分配)', + 'set.memory.hint': '建议 2048 MB 以上,低配设备可选 1024 MB。', + 'set.sources': '模型源', + 'set.sources.desc': '停用的模型源不会出现在下载页。', + 'set.sourceEnabled': '启用', + 'set.storage': '存储', + 'set.modelDir': '模型库目录', + 'set.dataDir': '数据目录', + 'set.openFolder': '打开文件夹', + 'set.clearCache': '清理缓存', + 'set.cacheCleared': '缓存已清理', + 'set.about': '关于', + 'set.version': '版本', + 'set.platform': '平台', + 'set.license': '许可', + 'set.licenseValue': 'MIT', + 'set.checkUpdate': '检查更新', + 'set.checkUpdate.desc': '启动时自动检查模型与启动器是否为最新版。', + 'set.backend': '后端服务', + 'set.backend.desc': '界面(Flutter)与后端(.NET)分离,后端只监听本机回环地址。', + 'set.backend.ui': '模型窗口宿主', + 'set.backend.uiOk': '可用', + 'set.backend.uiBad': '不可用', + 'update.title': '自动更新', + 'update.auto': '启动时自动检查更新', + 'update.checkNow': '检查更新', + 'update.source': '更新源', + 'update.lastCheck': '上次检查', + 'update.never': '尚未检查', + 'update.none': '无', + 'update.checking': '正在检查更新…', + 'update.offline': '暂时无法连接更新服务器,继续使用本地模型', + 'update.noChange': '模型与启动器均为最新版', + 'update.applied': '已更新 {0} 个模型,立即生效', + 'update.done': '更新检查完成', + 'update.pendingReady': '启动器新版 {0} 已就绪,下次启动生效', + 'common.cancel': '取消', + 'common.confirm': '确定', + 'common.delete': '删除', + 'common.close': '关闭', + 'common.open': '打开', + 'common.applied': '已应用', + 'common.confirmTitle': '请确认', + 'common.retry': '重试', + 'common.loading': '加载中…', + 'common.error': '出错了', + 'common.refresh': '刷新', + 'about.developers': '开发者', + 'about.repository': '仓库', + 'about.openRepository': '打开仓库', + 'about.contributions': '{0} 次提交', + 'about.noContributors': '暂无贡献者信息', + 'about.architecture': '架构', + 'about.architectureValue': 'Flutter 前端 + .NET 后端(本地 HTTP)', + 'about.sourceLanguage': '源码语言', + 'about.frontend': '前端', + }, + 'en': { + 'app.name': 'Morris GC', + 'app.tagline': 'Astronomy teaching models · visual launcher', + 'nav.home': 'Home', + 'nav.download': 'Download', + 'nav.settings': 'Settings', + 'nav.about': 'About', + 'home.title': 'Model library', + 'home.subtitle': 'Pick a model and explain rotation, revolution and the seasons with an interactive 3D scene.', + 'home.launch': 'Launch model', + 'home.download': 'Get models', + 'home.settings': 'Settings', + 'home.installed': 'Installed models', + 'home.count': '{0} models', + 'home.empty': 'No models yet', + 'home.emptyHint': 'Models are checked and downloaded on startup. Offline: drop model folders into .GC/model/ and reopen, or retry from the Download page once online.', + 'home.emptyAction': 'Get models', + 'home.open': 'Open folder', + 'home.delete': 'Delete', + 'home.deleteConfirm': 'Delete the model "{0}"? Its files will be removed from the local library.', + 'home.stats.models': 'Installed', + 'home.stats.sources': 'Sources', + 'home.stats.memory': 'Memory budget', + 'home.recent': 'Select a model, then press Launch', + 'home.launchHint': 'Models open in their own window with play/pause, view controls and teaching notes.', + 'dl.title': 'Download', + 'dl.subtitle': 'Read downloadable models from the built-in sources; manage sources in Settings.', + 'dl.sources': 'Sources', + 'dl.refresh': 'Refresh', + 'dl.available': 'Available models', + 'dl.download': 'Download', + 'dl.installed': 'Installed', + 'dl.reinstall': 'Re-download', + 'dl.background': 'Background tasks', + 'dl.bgEmpty': 'No background tasks', + 'dl.cancel': 'Cancel', + 'dl.retry': 'Retry', + 'dl.clearDone': 'Clear finished', + 'dl.removeTask': 'Remove', + 'dl.status.queued': 'Queued', + 'dl.status.downloading': 'Downloading', + 'dl.status.done': 'Completed', + 'dl.status.failed': 'Failed', + 'dl.status.canceled': 'Canceled', + 'dl.empty': 'No models in this source', + 'dl.emptyHint': 'A source needs model//.json layout', + 'dl.syncing': 'Reading model source…', + 'dl.ready': '{0} models', + 'dl.fromCache': 'cached', + 'dl.pickSource': 'Select a source to see available models', + 'set.title': 'Settings', + 'set.subtitle': 'Model sources, startup memory allocation and local storage.', + 'set.general': 'General', + 'set.language': 'Language', + 'set.language.auto': 'System', + 'set.fps': 'Render frame rate', + 'set.fps.desc': 'Higher is smoother but uses more CPU.', + 'set.memory': 'Startup memory allocation', + 'set.memory.desc': 'The launcher hands this budget to each model; models decide how much data to cache with it.', + 'set.memory.current': 'In use', + 'set.memory.auto': 'Auto (allocate based on device memory)', + 'set.memory.hint': '2048 MB or more is recommended; 1024 MB for low-end devices.', + 'set.sources': 'Model sources', + 'set.sources.desc': 'Disabled sources are hidden from the Download page.', + 'set.sourceEnabled': 'Enabled', + 'set.storage': 'Storage', + 'set.modelDir': 'Model library', + 'set.dataDir': 'Data folder', + 'set.openFolder': 'Open folder', + 'set.clearCache': 'Clear cache', + 'set.cacheCleared': 'Cache cleared', + 'set.about': 'About', + 'set.version': 'Version', + 'set.platform': 'Platform', + 'set.license': 'License', + 'set.licenseValue': 'MIT', + 'set.checkUpdate': 'Check for updates', + 'set.checkUpdate.desc': 'Check on startup whether models and the launcher are up to date.', + 'set.backend': 'Backend service', + 'set.backend.desc': 'The UI (Flutter) and the backend (.NET) are separate; the backend only listens on loopback.', + 'set.backend.ui': 'Model window host', + 'set.backend.uiOk': 'available', + 'set.backend.uiBad': 'unavailable', + 'update.title': 'Auto update', + 'update.auto': 'Check for updates on startup', + 'update.checkNow': 'Check now', + 'update.source': 'Update source', + 'update.lastCheck': 'Last check', + 'update.never': 'Never', + 'update.none': 'None', + 'update.checking': 'Checking for updates…', + 'update.offline': 'Update server unavailable — continuing with local models', + 'update.noChange': 'Models and launcher are up to date', + 'update.applied': 'Updated {0} models, applied now', + 'update.done': 'Update check complete', + 'update.pendingReady': 'Launcher {0} is ready, applies on next start', + 'common.cancel': 'Cancel', + 'common.confirm': 'Confirm', + 'common.delete': 'Delete', + 'common.close': 'Close', + 'common.open': 'Open', + 'common.applied': 'Applied', + 'common.confirmTitle': 'Please confirm', + 'common.retry': 'Retry', + 'common.loading': 'Loading…', + 'common.error': 'Something went wrong', + 'common.refresh': 'Refresh', + 'about.developers': 'Developers', + 'about.repository': 'Repository', + 'about.openRepository': 'Open repository', + 'about.contributions': '{0} commits', + 'about.noContributors': 'No contributor information', + 'about.architecture': 'Architecture', + 'about.architectureValue': 'Flutter frontend + .NET backend (local HTTP)', + 'about.sourceLanguage': 'Source language', + 'about.frontend': 'Frontend', + }, + }; + + /// 取一条文案;`{0}` 这类占位符用 [args] 填充。 + static String t(String key, [List args = const []]) { + final table = _tables[language.value] ?? _tables['zh-CN']!; + var text = table[key] ?? _tables['zh-CN']![key] ?? key; + for (var i = 0; i < args.length; i++) { + text = text.replaceAll('{$i}', '${args[i]}'); + } + return text; + } + + /// 把后端语言设置(auto / zh-CN / en)解析成实际语言。 + static String resolve(String? preference) { + if (preference != null && preference.isNotEmpty && preference != 'auto') { + return preference.startsWith('en') ? 'en' : 'zh-CN'; + } + final locale = WidgetsBinding.instance.platformDispatcher.locale; + return locale.languageCode == 'zh' ? 'zh-CN' : 'en'; + } + + static void setLanguage(String code) { + final resolved = resolve(code); + if (language.value != resolved) language.value = resolved; + } +} + +/// 便捷取词:`T('nav.home')`。 +String T(String key, [List args = const []]) => I18n.t(key, args); diff --git a/GC-UI/frontend/lib/main.dart b/GC-UI/frontend/lib/main.dart new file mode 100644 index 0000000..51e0519 --- /dev/null +++ b/GC-UI/frontend/lib/main.dart @@ -0,0 +1,40 @@ +import 'package:flutter/material.dart'; + +import 'controller.dart'; +import 'i18n.dart'; +import 'shell.dart'; +import 'theme.dart'; + +void main() { + runApp(const GcUiApp()); +} + +/// GC-UI 前端:Flutter 桌面应用(Windows / macOS)。 +/// +/// 界面全部在这里;模型扫描、下载、更新、设置、模型窗口宿主都在后端 +/// (GC-UI/backend/GC.UI.Server,本地 HTTP 服务)。 +class GcUiApp extends StatefulWidget { + const GcUiApp({super.key}); + + @override + State createState() => _GcUiAppState(); +} + +class _GcUiAppState extends State { + final ShellController _controller = ShellController(); + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder( + valueListenable: I18n.language, + builder: (context, language, _) { + return MaterialApp( + title: 'Morris GC', + debugShowCheckedModeBanner: false, + theme: buildGcTheme(), + home: ShellPage(controller: _controller), + ); + }, + ); + } +} diff --git a/GC-UI/frontend/lib/pages.dart b/GC-UI/frontend/lib/pages.dart new file mode 100644 index 0000000..6b20466 --- /dev/null +++ b/GC-UI/frontend/lib/pages.dart @@ -0,0 +1,1562 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import 'api_client.dart'; +import 'controller.dart'; +import 'i18n.dart'; +import 'theme.dart'; + +// --------------------------------------------------------------------------- +// 首页:模型库 +// --------------------------------------------------------------------------- + +class HomePageView extends StatefulWidget { + const HomePageView({super.key, required this.controller, this.initialModels}); + + final ShellController controller; + + /// 预置模型列表(仅用于测试 / 截图,正常运行时为 null,由后端提供)。 + final List? initialModels; + + @override + State createState() => _HomePageViewState(); +} + +class _HomePageViewState extends State { + List _models = const []; + bool _loading = true; + String? _error; + String? _notice; + + @override + void initState() { + super.initState(); + final preset = widget.initialModels; + if (preset != null) { + _models = preset; + _loading = false; + } else { + _load(); + } + } + + Future _load() async { + setState(() { + _loading = true; + _error = null; + }); + try { + final models = await widget.controller.api.models(); + if (!mounted) return; + setState(() { + _models = models; + _loading = false; + }); + } catch (error) { + if (!mounted) return; + setState(() { + _error = error.toString(); + _loading = false; + }); + } + } + + Future _launch(ModelInfo model) async { + setState(() => _notice = null); + try { + final result = await widget.controller.api.launchModel(model.id); + if (!mounted) return; + setState(() => _notice = result.message); + } catch (error) { + if (!mounted) return; + setState(() => _notice = error.toString()); + } + } + + Future _delete(ModelInfo model) async { + final confirmed = await showDialog( + context: context, + builder: (context) => AlertDialog( + backgroundColor: GcColors.surface, + title: Text(T('common.confirmTitle')), + content: Text(T('home.deleteConfirm', [model.name])), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: Text(T('common.cancel')), + ), + FilledButton( + onPressed: () => Navigator.of(context).pop(true), + child: Text(T('common.delete')), + ), + ], + ), + ); + if (confirmed != true) return; + + try { + await widget.controller.api.deleteModel(model.id); + await _load(); + } catch (error) { + if (!mounted) return; + setState(() => _notice = error.toString()); + } + } + + Future _openFolder(String path) async { + try { + await widget.controller.api.openFolder(path); + } catch (error) { + if (!mounted) return; + setState(() => _notice = error.toString()); + } + } + + @override + Widget build(BuildContext context) { + final settings = widget.controller.settings; + return RefreshIndicator( + onRefresh: _load, + child: ListView( + padding: const EdgeInsets.fromLTRB(26, 24, 26, 28), + children: [ + _hero(settings), + const SizedBox(height: 18), + Row( + children: [ + Expanded( + child: Text( + T('home.installed'), + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w600, + color: GcColors.ink, + ), + ), + ), + GcHint(T('home.count', [_models.length])), + const SizedBox(width: 10), + IconButton( + tooltip: T('common.refresh'), + onPressed: _load, + icon: const Icon(Icons.refresh_rounded, size: 18), + color: GcColors.faint, + ), + ], + ), + if (_notice != null) ...[ + const SizedBox(height: 8), + GcCard( + padding: const EdgeInsets.all(12), + child: Text( + _notice!, + style: const TextStyle(fontSize: 12, color: GcColors.warn), + ), + ), + ], + const SizedBox(height: 12), + if (_loading) + const Padding( + padding: EdgeInsets.symmetric(vertical: 40), + child: Center(child: CircularProgressIndicator(strokeWidth: 2.4)), + ) + else if (_error != null) + GcCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(T('common.error'), + style: const TextStyle(color: GcColors.danger)), + const SizedBox(height: 8), + GcHint(_error!), + ], + ), + ) + else if (_models.isEmpty) + _emptyState() + else + Wrap( + spacing: 16, + runSpacing: 16, + children: [ + for (final model in _models) + _ModelCard( + model: model, + previewUrl: widget.controller.api.previewUrl(model), + onLaunch: () => _launch(model), + onOpenFolder: () => _openFolder(model.directory), + onDelete: () => _delete(model), + ), + ], + ), + ], + ), + ); + } + + Widget _hero(SettingsInfo? settings) { + return Container( + padding: const EdgeInsets.all(26), + decoration: BoxDecoration( + gradient: const LinearGradient( + colors: [Color(0xFF16233C), Color(0xFF0E1A31)], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + borderRadius: BorderRadius.circular(16), + border: Border.all(color: GcColors.line), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + T('home.title'), + style: const TextStyle( + fontSize: 24, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + const SizedBox(height: 9), + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 500), + child: Text( + T('home.subtitle'), + style: const TextStyle( + fontSize: 12.5, + color: Color(0xFFA9BEDF), + height: 1.5, + ), + ), + ), + const SizedBox(height: 16), + Wrap( + spacing: 10, + runSpacing: 8, + children: [ + FilledButton( + onPressed: _models.isEmpty ? null : () => _launch(_models.first), + child: Text(T('home.launch')), + ), + OutlinedButton( + onPressed: () => widget.controller.goTo(1), + child: Text(T('home.download')), + ), + OutlinedButton( + onPressed: () => widget.controller.goTo(2), + child: Text(T('home.settings')), + ), + ], + ), + const SizedBox(height: 10), + Text( + T('home.launchHint'), + style: const TextStyle(fontSize: 11, color: Color(0xFF7E93B8)), + ), + ], + ), + ), + const SizedBox(width: 16), + Row( + children: [ + _stat('${_models.length}', T('home.stats.models'), 96), + const SizedBox(width: 10), + _stat('${settings?.sources.where((s) => s.enabled).length ?? 0}', + T('home.stats.sources'), 96), + const SizedBox(width: 10), + _stat('${settings?.memoryBudgetMb ?? 0} MB', + T('home.stats.memory'), 112), + ], + ), + ], + ), + ); + } + + Widget _stat(String value, String label, double width) { + return Container( + width: width, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + decoration: BoxDecoration( + color: GcColors.surfaceAlt, + borderRadius: BorderRadius.circular(14), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + value, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w600, + color: Colors.white, + ), + ), + const SizedBox(height: 2), + Text( + label, + style: const TextStyle(fontSize: 10.5, color: Color(0xFF7E93B8)), + ), + ], + ), + ); + } + + Widget _emptyState() { + return GcCard( + padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 34), + child: Column( + children: [ + Text( + T('home.empty'), + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w600, + color: GcColors.ink, + ), + ), + const SizedBox(height: 10), + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Text( + T('home.emptyHint'), + textAlign: TextAlign.center, + style: const TextStyle( + fontSize: 12, + color: GcColors.faint, + height: 1.5, + ), + ), + ), + const SizedBox(height: 16), + FilledButton( + onPressed: () => widget.controller.goTo(1), + child: Text(T('home.emptyAction')), + ), + ], + ), + ); + } +} + +class _ModelCard extends StatelessWidget { + const _ModelCard({ + required this.model, + required this.previewUrl, + required this.onLaunch, + required this.onOpenFolder, + required this.onDelete, + }); + + final ModelInfo model; + final String previewUrl; + final VoidCallback onLaunch; + final VoidCallback onOpenFolder; + final VoidCallback onDelete; + + @override + Widget build(BuildContext context) { + return SizedBox( + width: 336, + child: GcCard( + padding: EdgeInsets.zero, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ClipRRect( + borderRadius: const BorderRadius.vertical(top: Radius.circular(13)), + child: SizedBox( + height: 138, + width: double.infinity, + child: Container( + color: const Color(0xFF0B1226), + child: model.hasPreview + ? Image.network( + previewUrl, + fit: BoxFit.cover, + errorBuilder: (context, error, stack) => + const _PreviewFallback(), + ) + : const _PreviewFallback(), + ), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 13, 16, 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + model.name, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: GcColors.ink, + ), + ), + ), + const SizedBox(width: 8), + Text( + model.metaText, + style: const TextStyle( + fontSize: 10.5, + color: GcColors.faint, + ), + ), + ], + ), + const SizedBox(height: 7), + SizedBox( + height: 34, + child: Text( + model.description, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 12, + color: GcColors.muted, + height: 1.4, + ), + ), + ), + if (model.tags.isNotEmpty) ...[ + const SizedBox(height: 6), + Text( + model.tags.join(' · '), + style: const TextStyle( + fontSize: 10.5, + color: GcColors.faint, + ), + ), + ], + const SizedBox(height: 12), + Row( + children: [ + FilledButton( + onPressed: onLaunch, + child: Text(T('home.launch')), + ), + const Spacer(), + TextButton( + onPressed: onOpenFolder, + child: Text(T('home.open')), + ), + TextButton( + onPressed: onDelete, + style: TextButton.styleFrom( + foregroundColor: GcColors.danger, + ), + child: Text(T('home.delete')), + ), + ], + ), + ], + ), + ), + ], + ), + ), + ); + } +} + +class _PreviewFallback extends StatelessWidget { + const _PreviewFallback(); + + @override + Widget build(BuildContext context) => const Center( + child: Text( + '◎', + style: TextStyle(fontSize: 34, color: Color(0xFF1B2A47)), + ), + ); +} + +// --------------------------------------------------------------------------- +// 下载页 +// --------------------------------------------------------------------------- + +class DownloadPageView extends StatefulWidget { + const DownloadPageView({ + super.key, + required this.controller, + this.initialSources, + this.initialIndex, + this.initialJobs, + }); + + final ShellController controller; + + /// 预置数据(仅用于测试 / 截图,正常运行时为 null,由后端提供)。 + final List? initialSources; + final SourceIndexInfo? initialIndex; + final List? initialJobs; + + @override + State createState() => _DownloadPageViewState(); +} + +class _DownloadPageViewState extends State { + List _sources = const []; + SourceIndexInfo? _index; + List _jobs = const []; + String? _selectedSourceId; + bool _loading = true; + String? _error; + Timer? _poll; + + @override + void initState() { + super.initState(); + final presetSources = widget.initialSources; + if (presetSources != null) { + _sources = presetSources; + _index = widget.initialIndex; + _jobs = widget.initialJobs ?? const []; + _selectedSourceId = presetSources.isEmpty ? null : presetSources.first.id; + _loading = false; + return; + } + _load(); + _poll = Timer.periodic(const Duration(seconds: 1), (_) => _refreshJobs()); + } + + @override + void dispose() { + _poll?.cancel(); + super.dispose(); + } + + Future _load() async { + setState(() { + _loading = true; + _error = null; + }); + try { + final sources = await widget.controller.api.sources(); + final preferred = sources.where((s) => s.enabled).toList(); + final selected = _selectedSourceId ?? + (preferred.isNotEmpty + ? preferred.first.id + : (sources.isNotEmpty ? sources.first.id : '')); + + final index = selected.isEmpty + ? null + : await widget.controller.api.remoteModels(sourceId: selected); + + if (!mounted) return; + setState(() { + _sources = sources; + _selectedSourceId = selected; + _index = index; + _loading = false; + }); + await _refreshJobs(); + } catch (error) { + if (!mounted) return; + setState(() { + _error = error.toString(); + _loading = false; + }); + } + } + + Future _refreshJobs() async { + try { + final jobs = await widget.controller.api.jobs(); + if (!mounted) return; + setState(() => _jobs = jobs); + } catch (_) { + // 轮询失败不打扰用户,下一次再试 + } + } + + Future _selectSource(String id) async { + setState(() { + _selectedSourceId = id; + _loading = true; + _error = null; + }); + try { + final index = await widget.controller.api.remoteModels(sourceId: id); + if (!mounted) return; + setState(() { + _index = index; + _loading = false; + }); + } catch (error) { + if (!mounted) return; + setState(() { + _error = error.toString(); + _loading = false; + }); + } + } + + Future _download(RemoteModelInfo model) async { + final sourceId = _selectedSourceId; + if (sourceId == null) return; + try { + await widget.controller.api.startDownload(sourceId, model.id); + await _refreshJobs(); + } catch (error) { + if (!mounted) return; + setState(() => _error = error.toString()); + } + } + + Future _jobAction(Future Function(String id) action, String id) async { + try { + await action(id); + await _refreshJobs(); + } catch (error) { + if (!mounted) return; + setState(() => _error = error.toString()); + } + } + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.fromLTRB(24, 22, 24, 24), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(width: 300, child: _sourcePanel()), + const SizedBox(width: 16), + Expanded(child: _modelPanel()), + ], + ), + ); + } + + Widget _sourcePanel() { + return GcCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GcSectionTitle(T('dl.sources')), + const SizedBox(height: 12), + for (final source in _sources) + Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Material( + color: source.id == _selectedSourceId + ? GcColors.surfaceAlt + : Colors.transparent, + borderRadius: BorderRadius.circular(9), + child: InkWell( + borderRadius: BorderRadius.circular(9), + onTap: () => _selectSource(source.id), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 10), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + source.name, + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: GcColors.ink, + ), + ), + ), + if (!source.enabled) + const Text( + 'off', + style: TextStyle( + fontSize: 10, color: GcColors.faint), + ), + ], + ), + const SizedBox(height: 2), + Text( + source.host, + style: const TextStyle( + fontSize: 10.5, color: GcColors.faint), + ), + ], + ), + ), + ), + ), + ), + const SizedBox(height: 10), + GcHint(T('dl.subtitle')), + const SizedBox(height: 12), + OutlinedButton.icon( + onPressed: _load, + icon: const Icon(Icons.refresh_rounded, size: 16), + label: Text(T('dl.refresh')), + ), + ], + ), + ); + } + + Widget _modelPanel() { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + T('dl.available'), + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w600, + color: GcColors.ink, + ), + ), + ), + if (_index != null) + GcHint(_index!.fromCache + ? '${T('dl.ready', [_index!.models.length])} · ${T('dl.fromCache')}' + : T('dl.ready', [_index!.models.length])), + ], + ), + const SizedBox(height: 12), + Expanded( + child: ListView( + children: [ + if (_loading) + const Padding( + padding: EdgeInsets.symmetric(vertical: 40), + child: Center( + child: CircularProgressIndicator(strokeWidth: 2.4)), + ) + else if (_error != null) + GcCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(T('common.error'), + style: const TextStyle(color: GcColors.danger)), + const SizedBox(height: 8), + GcHint(_error!), + ], + ), + ) + else if (_index == null || _index!.models.isEmpty) + GcCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(T('dl.empty'), + style: const TextStyle(color: GcColors.ink)), + const SizedBox(height: 8), + GcHint(T('dl.emptyHint')), + ], + ), + ) + else + for (final model in _index!.models) + Padding( + padding: const EdgeInsets.only(bottom: 10), + child: GcCard( + padding: const EdgeInsets.all(14), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + model.name, + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: GcColors.ink, + ), + ), + const SizedBox(width: 8), + Text( + 'v${model.version} · ${model.sizeText}', + style: const TextStyle( + fontSize: 10.5, + color: GcColors.faint), + ), + if (model.installed) ...[ + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: GcColors.ok + .withOpacity(0.16), + borderRadius: + BorderRadius.circular(5), + ), + child: Text( + T('dl.installed'), + style: const TextStyle( + fontSize: 10, + color: GcColors.ok), + ), + ), + ], + ], + ), + const SizedBox(height: 4), + Text( + model.description, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 11.5, + color: GcColors.muted, + height: 1.4, + ), + ), + ], + ), + ), + const SizedBox(width: 12), + FilledButton( + onPressed: () => _download(model), + child: Text(model.installed + ? T('dl.reinstall') + : T('dl.download')), + ), + ], + ), + ), + ), + const SizedBox(height: 8), + _jobsPanel(), + ], + ), + ), + ], + ); + } + + Widget _jobsPanel() { + return GcCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GcSectionTitle( + T('dl.background'), + trailing: TextButton( + onPressed: () async { + try { + await widget.controller.api.clearFinished(); + await _refreshJobs(); + } catch (_) { + // 忽略 + } + }, + child: Text(T('dl.clearDone')), + ), + ), + const SizedBox(height: 8), + if (_jobs.isEmpty) + GcHint(T('dl.bgEmpty')) + else + for (final job in _jobs) + Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + '${job.name} v${job.version}', + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: GcColors.ink, + ), + ), + ), + Text( + _stateLabel(job.state), + style: TextStyle( + fontSize: 11, + color: job.state == 'Failed' + ? GcColors.danger + : job.state == 'Completed' + ? GcColors.ok + : GcColors.faint, + ), + ), + const SizedBox(width: 8), + if (job.isActive) + TextButton( + onPressed: () => _jobAction( + widget.controller.api.cancelJob, job.id), + child: Text(T('dl.cancel')), + ) + else if (job.canRetry) + TextButton( + onPressed: () => _jobAction( + widget.controller.api.retryJob, job.id), + child: Text(T('dl.retry')), + ) + else + TextButton( + onPressed: () => _jobAction( + widget.controller.api.removeJob, job.id), + child: Text(T('dl.removeTask')), + ), + ], + ), + const SizedBox(height: 6), + LinearProgressIndicator( + value: job.progress.clamp(0, 1).toDouble(), + minHeight: 4, + ), + const SizedBox(height: 4), + Text( + job.error ?? job.detailText, + style: const TextStyle( + fontSize: 10.5, color: GcColors.faint), + ), + ], + ), + ), + ], + ), + ); + } + + String _stateLabel(String state) { + switch (state) { + case 'Queued': + return T('dl.status.queued'); + case 'Running': + return T('dl.status.downloading'); + case 'Completed': + return T('dl.status.done'); + case 'Failed': + return T('dl.status.failed'); + case 'Canceled': + return T('dl.status.canceled'); + default: + return state; + } + } +} + +// --------------------------------------------------------------------------- +// 设置页 +// --------------------------------------------------------------------------- + +class SettingsPageView extends StatefulWidget { + const SettingsPageView({super.key, required this.controller}); + + final ShellController controller; + + @override + State createState() => _SettingsPageViewState(); +} + +class _SettingsPageViewState extends State { + double _memory = 2048; + bool _memoryAuto = true; + int _fps = 120; + bool _autoUpdate = true; + String _language = 'auto'; + bool _synced = false; + String? _status; + + @override + void initState() { + super.initState(); + widget.controller.reloadSettings(); + } + + void _syncFrom(SettingsInfo settings) { + if (_synced) return; + _memory = settings.memoryMb.toDouble(); + _memoryAuto = settings.memoryAuto; + _fps = settings.renderFps; + _autoUpdate = settings.autoUpdateOnStartup; + _language = settings.language; + _synced = true; + } + + @override + Widget build(BuildContext context) { + final settings = widget.controller.settings; + if (settings == null) { + return const Center(child: CircularProgressIndicator(strokeWidth: 2.4)); + } + _syncFrom(settings); + + return ListView( + padding: const EdgeInsets.fromLTRB(26, 24, 26, 28), + children: [ + Text( + T('set.title'), + style: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.w700, + color: GcColors.ink, + ), + ), + const SizedBox(height: 6), + GcHint(T('set.subtitle')), + const SizedBox(height: 18), + _generalCard(settings), + const SizedBox(height: 16), + _memoryCard(settings), + const SizedBox(height: 16), + _sourcesCard(settings), + const SizedBox(height: 16), + _storageCard(settings), + const SizedBox(height: 16), + _updateCard(settings), + const SizedBox(height: 16), + _backendCard(settings), + if (_status != null) ...[ + const SizedBox(height: 14), + GcHint(_status!), + ], + ], + ); + } + + Widget _generalCard(SettingsInfo settings) { + return GcCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GcSectionTitle(T('set.general')), + const SizedBox(height: 14), + Row( + children: [ + SizedBox(width: 160, child: Text(T('set.language'), + style: const TextStyle(fontSize: 12.5, color: GcColors.muted))), + DropdownButton( + value: _language, + dropdownColor: GcColors.surfaceAlt, + underline: const SizedBox.shrink(), + items: >[ + DropdownMenuItem( + value: 'auto', + child: Text(T('set.language.auto')), + ), + for (final language in settings.languages) + DropdownMenuItem( + value: language.code, + child: Text(language.label), + ), + ], + onChanged: (value) async { + if (value == null) return; + setState(() => _language = value); + await widget.controller.saveSettings( + SettingsPatch(language: value)); + }, + ), + ], + ), + const SizedBox(height: 10), + Row( + children: [ + SizedBox(width: 160, child: Text(T('set.fps'), + style: const TextStyle(fontSize: 12.5, color: GcColors.muted))), + Expanded( + child: Slider( + value: _fps.toDouble(), + min: 24, + max: 120, + divisions: 4, + label: '$_fps', + onChanged: (value) => setState(() => _fps = value.round()), + onChangeEnd: (value) async { + await widget.controller + .saveSettings(SettingsPatch(renderFps: value.round())); + if (mounted) setState(() => _status = T('common.applied')); + }, + ), + ), + SizedBox( + width: 46, + child: Text('$_fps', + style: const TextStyle( + fontSize: 12.5, color: GcColors.ink)), + ), + ], + ), + GcHint(T('set.fps.desc')), + ], + ), + ); + } + + Widget _memoryCard(SettingsInfo settings) { + return GcCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GcSectionTitle(T('set.memory')), + const SizedBox(height: 8), + GcHint(T('set.memory.desc')), + const SizedBox(height: 14), + Row( + children: [ + Switch( + value: _memoryAuto, + onChanged: (value) async { + setState(() => _memoryAuto = value); + await widget.controller + .saveSettings(SettingsPatch(memoryAuto: value)); + }, + ), + const SizedBox(width: 10), + Expanded( + child: Text( + T('set.memory.auto'), + style: const TextStyle(fontSize: 12.5, color: GcColors.muted), + ), + ), + ], + ), + const SizedBox(height: 6), + Row( + children: [ + Expanded( + child: Slider( + value: _memory, + min: 512, + max: 16384, + divisions: 62, + label: '${_memory.round()} MB', + onChanged: _memoryAuto + ? null + : (value) => setState(() => _memory = value), + onChangeEnd: (value) async { + await widget.controller.saveSettings( + SettingsPatch(memoryMb: value.round())); + if (mounted) setState(() => _status = T('common.applied')); + }, + ), + ), + SizedBox( + width: 96, + child: Text( + '${_memory.round()} MB', + style: const TextStyle(fontSize: 12.5, color: GcColors.ink), + ), + ), + ], + ), + const SizedBox(height: 6), + Row( + children: [ + Text( + '${T('set.memory.current')}: ${settings.memoryUsageText}', + style: const TextStyle(fontSize: 11.5, color: GcColors.faint), + ), + ], + ), + const SizedBox(height: 6), + GcHint(T('set.memory.hint')), + ], + ), + ); + } + + Widget _sourcesCard(SettingsInfo settings) { + return GcCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GcSectionTitle(T('set.sources')), + const SizedBox(height: 8), + GcHint(T('set.sources.desc')), + const SizedBox(height: 12), + for (final source in settings.sources) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + source.name, + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: GcColors.ink, + ), + ), + const SizedBox(height: 2), + Text( + source.url, + style: const TextStyle( + fontSize: 10.5, color: GcColors.faint), + ), + ], + ), + ), + Text( + source.enabled ? T('set.sourceEnabled') : '—', + style: const TextStyle(fontSize: 11, color: GcColors.faint), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _storageCard(SettingsInfo settings) { + return GcCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GcSectionTitle(T('set.storage')), + const SizedBox(height: 12), + _pathRow(T('set.modelDir'), settings.modelRoot), + const SizedBox(height: 8), + _pathRow(T('set.dataDir'), settings.dataRoot), + const SizedBox(height: 12), + Wrap( + spacing: 10, + children: [ + OutlinedButton( + onPressed: () async { + try { + await widget.controller.api.openFolder(settings.modelRoot); + } catch (error) { + if (mounted) setState(() => _status = error.toString()); + } + }, + child: Text(T('set.openFolder')), + ), + OutlinedButton( + onPressed: () async { + await widget.controller.checkUpdate(force: true); + if (mounted) setState(() => _status = T('set.cacheCleared')); + }, + child: Text(T('set.clearCache')), + ), + ], + ), + ], + ), + ); + } + + Widget _pathRow(String label, String value) { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 160, + child: Text(label, + style: const TextStyle(fontSize: 12.5, color: GcColors.muted)), + ), + Expanded( + child: SelectableText( + value, + style: const TextStyle(fontSize: 11.5, color: GcColors.faint), + ), + ), + ], + ); + } + + Widget _updateCard(SettingsInfo settings) { + return GcCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GcSectionTitle(T('update.title')), + const SizedBox(height: 8), + GcHint(T('set.checkUpdate.desc')), + const SizedBox(height: 12), + Row( + children: [ + Switch( + value: _autoUpdate, + onChanged: (value) async { + setState(() => _autoUpdate = value); + await widget.controller + .saveSettings(SettingsPatch(autoUpdateOnStartup: value)); + }, + ), + const SizedBox(width: 10), + Expanded( + child: Text( + T('update.auto'), + style: const TextStyle(fontSize: 12.5, color: GcColors.muted), + ), + ), + ], + ), + const SizedBox(height: 8), + _pathRow(T('update.source'), settings.updateRepository), + const SizedBox(height: 12), + FilledButton( + onPressed: () => widget.controller.checkUpdate(force: true), + child: Text(T('update.checkNow')), + ), + ], + ), + ); + } + + Widget _backendCard(SettingsInfo settings) { + final health = widget.controller.health; + return GcCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GcSectionTitle(T('set.backend')), + const SizedBox(height: 8), + GcHint(T('set.backend.desc')), + const SizedBox(height: 12), + _pathRow('API', widget.controller.api.baseUrl), + const SizedBox(height: 8), + _pathRow(T('set.version'), settings.version), + const SizedBox(height: 8), + _pathRow(T('set.platform'), settings.platform), + const SizedBox(height: 8), + _pathRow( + T('set.backend.ui'), + health == null + ? '—' + : health.uiAvailable + ? T('set.backend.uiOk') + : '${T('set.backend.uiBad')}${health.uiError == null ? '' : ' · ${health.uiError}'}', + ), + ], + ), + ); + } +} + +// --------------------------------------------------------------------------- +// 关于页 +// --------------------------------------------------------------------------- + +class AboutPageView extends StatefulWidget { + const AboutPageView({super.key, required this.controller, this.initialAbout}); + + final ShellController controller; + + /// 预置数据(仅用于测试 / 截图,正常运行时为 null,由后端提供)。 + final AboutInfo? initialAbout; + + @override + State createState() => _AboutPageViewState(); +} + +class _AboutPageViewState extends State { + AboutInfo? _about; + bool _loading = true; + String? _error; + + @override + void initState() { + super.initState(); + final preset = widget.initialAbout; + if (preset != null) { + _about = preset; + _loading = false; + return; + } + _load(); + } + + Future _load() async { + setState(() { + _loading = true; + _error = null; + }); + try { + final about = await widget.controller.api.about(); + if (!mounted) return; + setState(() { + _about = about; + _loading = false; + }); + } catch (error) { + if (!mounted) return; + setState(() { + _error = error.toString(); + _loading = false; + }); + } + } + + @override + Widget build(BuildContext context) { + return ListView( + padding: const EdgeInsets.fromLTRB(26, 24, 26, 28), + children: [ + Text( + T('nav.about'), + style: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.w700, + color: GcColors.ink, + ), + ), + const SizedBox(height: 18), + if (_loading) + const Padding( + padding: EdgeInsets.symmetric(vertical: 40), + child: Center(child: CircularProgressIndicator(strokeWidth: 2.4)), + ) + else if (_error != null) + GcCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(T('common.error'), + style: const TextStyle(color: GcColors.danger)), + const SizedBox(height: 8), + GcHint(_error!), + const SizedBox(height: 12), + OutlinedButton( + onPressed: _load, + child: Text(T('common.retry')), + ), + ], + ), + ) + else ...[ + GcCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _about?.appName ?? 'Morris GC', + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w700, + color: GcColors.ink, + ), + ), + const SizedBox(height: 6), + GcHint(T('app.tagline')), + const SizedBox(height: 14), + _row(T('set.version'), 'v${_about?.version ?? '—'}'), + const SizedBox(height: 8), + _row(T('set.platform'), _about?.platform ?? '—'), + const SizedBox(height: 8), + _row(T('about.architecture'), T('about.architectureValue')), + const SizedBox(height: 8), + _row(T('about.sourceLanguage'), _about?.sourceLanguage ?? 'C#'), + const SizedBox(height: 8), + _row(T('about.frontend'), _about?.frontend ?? 'Flutter'), + const SizedBox(height: 8), + _row(T('set.license'), T('set.licenseValue')), + const SizedBox(height: 14), + OutlinedButton( + onPressed: () async { + final url = _about?.repository; + if (url == null || url.isEmpty) return; + try { + await widget.controller.api.openUrl(url); + } catch (_) { + // 忽略 + } + }, + child: Text(T('about.openRepository')), + ), + ], + ), + ), + const SizedBox(height: 16), + GcCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GcSectionTitle(T('about.developers')), + const SizedBox(height: 12), + if ((_about?.contributors ?? const []).isEmpty) + GcHint(T('about.noContributors')) + else + for (final contributor in _about!.contributors) + Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Row( + children: [ + CircleAvatar( + radius: 16, + backgroundColor: GcColors.surfaceAlt, + backgroundImage: contributor.avatarUrl == null + ? null + : NetworkImage(contributor.avatarUrl!), + child: contributor.avatarUrl == null + ? const Text('◎', + style: TextStyle( + fontSize: 12, color: GcColors.accent)) + : null, + ), + const SizedBox(width: 12), + Expanded( + child: Text( + contributor.name, + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: GcColors.ink, + ), + ), + ), + Text( + T('about.contributions', + [contributor.contributions]), + style: const TextStyle( + fontSize: 11, color: GcColors.faint), + ), + ], + ), + ), + ], + ), + ), + ], + ], + ); + } + + Widget _row(String label, String value) { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 160, + child: Text(label, + style: const TextStyle(fontSize: 12.5, color: GcColors.muted)), + ), + Expanded( + child: SelectableText( + value, + style: const TextStyle(fontSize: 12, color: GcColors.ink), + ), + ), + ], + ); + } +} diff --git a/GC-UI/frontend/lib/shell.dart b/GC-UI/frontend/lib/shell.dart new file mode 100644 index 0000000..b7ca261 --- /dev/null +++ b/GC-UI/frontend/lib/shell.dart @@ -0,0 +1,330 @@ +import 'package:flutter/material.dart'; + +import 'controller.dart'; +import 'i18n.dart'; +import 'pages.dart'; +import 'theme.dart'; + +/// 侧边栏导航项。 +class _NavItem { + const _NavItem(this.icon, this.labelKey); + + final IconData icon; + final String labelKey; +} + +const List<_NavItem> _navItems = <_NavItem>[ + _NavItem(Icons.grid_view_rounded, 'nav.home'), + _NavItem(Icons.download_rounded, 'nav.download'), + _NavItem(Icons.tune_rounded, 'nav.settings'), + _NavItem(Icons.info_outline_rounded, 'nav.about'), +]; + +/// 应用外壳:左侧导航 + 右侧内容 + 底部更新状态条。 +class ShellPage extends StatefulWidget { + const ShellPage({super.key, required this.controller}); + + final ShellController controller; + + @override + State createState() => _ShellPageState(); +} + +class _ShellPageState extends State { + @override + void initState() { + super.initState(); + widget.controller.bootstrap(); + } + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: widget.controller, + builder: (context, _) { + final controller = widget.controller; + return Scaffold( + backgroundColor: GcColors.appBg, + body: Row( + children: [ + _Sidebar(controller: controller), + Expanded( + child: Column( + children: [ + Expanded(child: _content(controller)), + if (controller.updateBarVisible) + _UpdateBar(controller: controller), + ], + ), + ), + ], + ), + ); + }, + ); + } + + Widget _content(ShellController controller) { + if (!controller.backendReady) { + if (controller.loadError != null) { + return _BackendDown(controller: controller); + } + return const Center( + child: SizedBox( + width: 26, + height: 26, + child: CircularProgressIndicator(strokeWidth: 2.4), + ), + ); + } + + switch (controller.index) { + case 1: + return DownloadPageView(controller: controller); + case 2: + return SettingsPageView(controller: controller); + case 3: + return AboutPageView(controller: controller); + default: + return HomePageView(controller: controller); + } + } +} + +class _Sidebar extends StatelessWidget { + const _Sidebar({required this.controller}); + + final ShellController controller; + + @override + Widget build(BuildContext context) { + final settings = controller.settings; + return Container( + width: 236, + color: GcColors.sideBg, + padding: const EdgeInsets.fromLTRB(16, 20, 16, 18), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 26, + height: 26, + decoration: BoxDecoration( + color: GcColors.surfaceAlt, + borderRadius: BorderRadius.circular(8), + ), + alignment: Alignment.center, + child: const Text( + '◎', + style: TextStyle(fontSize: 14, color: GcColors.accent), + ), + ), + const SizedBox(width: 10), + const Expanded( + child: Text( + 'Morris GC', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: GcColors.ink, + ), + ), + ), + ], + ), + const SizedBox(height: 6), + GcHint(T('app.tagline')), + const SizedBox(height: 26), + const Padding( + padding: EdgeInsets.only(left: 14, bottom: 6), + child: Text( + 'MENU', + style: TextStyle( + fontSize: 9.5, + letterSpacing: 1.2, + fontWeight: FontWeight.w600, + color: Color(0xFF4C5F80), + ), + ), + ), + for (var i = 0; i < _navItems.length; i++) + _NavButton( + item: _navItems[i], + active: controller.index == i, + onTap: () => controller.goTo(i), + ), + const Spacer(), + Container(height: 1, color: GcColors.line), + const SizedBox(height: 10), + Padding( + padding: const EdgeInsets.only(left: 14), + child: Text( + 'v${settings?.version ?? '—'}', + style: const TextStyle(fontSize: 10.5, color: GcColors.faint), + ), + ), + Padding( + padding: const EdgeInsets.only(left: 14, top: 2), + child: Text( + settings?.platform ?? '—', + style: const TextStyle(fontSize: 10, color: Color(0xFF4F6080)), + ), + ), + ], + ), + ); + } +} + +class _NavButton extends StatelessWidget { + const _NavButton({ + required this.item, + required this.active, + required this.onTap, + }); + + final _NavItem item; + final bool active; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Material( + color: active ? GcColors.surfaceAlt : Colors.transparent, + borderRadius: BorderRadius.circular(9), + child: InkWell( + borderRadius: BorderRadius.circular(9), + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + child: Row( + children: [ + Icon( + item.icon, + size: 16, + color: active ? GcColors.accent : GcColors.faint, + ), + const SizedBox(width: 10), + Text( + T(item.labelKey), + style: TextStyle( + fontSize: 12.5, + fontWeight: active ? FontWeight.w600 : FontWeight.w400, + color: active ? GcColors.ink : GcColors.muted, + ), + ), + ], + ), + ), + ), + ), + ); + } +} + +class _UpdateBar extends StatelessWidget { + const _UpdateBar({required this.controller}); + + final ShellController controller; + + @override + Widget build(BuildContext context) { + return Container( + decoration: const BoxDecoration( + color: GcColors.surface, + border: Border(top: BorderSide(color: GcColors.line)), + ), + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 9), + child: Row( + children: [ + const Text('⟳', style: TextStyle(fontSize: 16, color: GcColors.accent)), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + controller.updateStatus, + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: GcColors.ink, + ), + overflow: TextOverflow.ellipsis, + ), + if (controller.updateDetail.isNotEmpty) + Text( + controller.updateDetail, + style: const TextStyle(fontSize: 11, color: GcColors.faint), + overflow: TextOverflow.ellipsis, + ), + if (controller.launcherNotice.isNotEmpty) + Text( + controller.launcherNotice, + style: const TextStyle(fontSize: 11, color: GcColors.warn), + ), + ], + ), + ), + if (controller.updateBusy) + const SizedBox( + width: 130, + child: LinearProgressIndicator(minHeight: 4), + ), + const SizedBox(width: 14), + TextButton( + onPressed: controller.updateBusy + ? null + : () => controller.checkUpdate(force: true), + child: Text(T('update.checkNow')), + ), + ], + ), + ); + } +} + +class _BackendDown extends StatelessWidget { + const _BackendDown({required this.controller}); + + final ShellController controller; + + @override + Widget build(BuildContext context) { + return Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 520), + child: GcCard( + padding: const EdgeInsets.all(28), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + T('common.error'), + style: const TextStyle( + fontSize: 17, + fontWeight: FontWeight.w600, + color: GcColors.ink, + ), + ), + const SizedBox(height: 10), + GcHint(controller.loadError ?? ''), + const SizedBox(height: 6), + GcHint('后端地址:${controller.api.baseUrl}'), + const SizedBox(height: 16), + FilledButton( + onPressed: controller.bootstrap, + child: Text(T('common.retry')), + ), + ], + ), + ), + ), + ); + } +} diff --git a/GC-UI/frontend/lib/theme.dart b/GC-UI/frontend/lib/theme.dart new file mode 100644 index 0000000..300cf03 --- /dev/null +++ b/GC-UI/frontend/lib/theme.dart @@ -0,0 +1,134 @@ +import 'package:flutter/material.dart'; + +/// 与 Avalonia 启动器一致的深色配色。 +class GcColors { + GcColors._(); + + static const Color appBg = Color(0xFF0A1226); + static const Color sideBg = Color(0xFF0C1529); + static const Color surface = Color(0xFF111C33); + static const Color surfaceAlt = Color(0xFF16233C); + static const Color line = Color(0xFF1B2740); + static const Color accent = Color(0xFF8FB6FF); + static const Color accentStrong = Color(0xFF4C7DFF); + static const Color ink = Color(0xFFF2F6FF); + static const Color muted = Color(0xFFA9B8D4); + static const Color faint = Color(0xFF7C90B4); + static const Color warn = Color(0xFFFFC46B); + static const Color danger = Color(0xFFFF7A7A); + static const Color ok = Color(0xFF6BE3A2); +} + +ThemeData buildGcTheme() { + final base = ThemeData.dark(useMaterial3: true); + return base.copyWith( + scaffoldBackgroundColor: GcColors.appBg, + colorScheme: base.colorScheme.copyWith( + primary: GcColors.accentStrong, + secondary: GcColors.accent, + surface: GcColors.surface, + error: GcColors.danger, + ), + textTheme: base.textTheme.apply( + bodyColor: GcColors.ink, + displayColor: GcColors.ink, + ), + dividerColor: GcColors.line, + cardTheme: const CardTheme( + color: GcColors.surface, + elevation: 0, + margin: EdgeInsets.zero, + ), + sliderTheme: base.sliderTheme.copyWith( + activeTrackColor: GcColors.accentStrong, + thumbColor: GcColors.accent, + inactiveTrackColor: GcColors.line, + ), + switchTheme: SwitchThemeData( + thumbColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.selected) + ? GcColors.accent + : GcColors.faint, + ), + trackColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.selected) + ? GcColors.accentStrong.withOpacity(0.45) + : GcColors.line, + ), + ), + progressIndicatorTheme: const ProgressIndicatorThemeData( + color: GcColors.accent, + linearTrackColor: GcColors.line, + ), + tooltipTheme: const TooltipThemeData( + decoration: BoxDecoration( + color: GcColors.surfaceAlt, + borderRadius: BorderRadius.all(Radius.circular(6)), + ), + textStyle: TextStyle(color: GcColors.ink, fontSize: 12), + ), + ); +} + +/// 通用卡片容器。 +class GcCard extends StatelessWidget { + const GcCard({super.key, required this.child, this.padding, this.width}); + + final Widget child; + final EdgeInsetsGeometry? padding; + final double? width; + + @override + Widget build(BuildContext context) { + return Container( + width: width, + padding: padding ?? const EdgeInsets.all(18), + decoration: BoxDecoration( + color: GcColors.surface, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: GcColors.line), + ), + child: child, + ); + } +} + +/// 小标题。 +class GcSectionTitle extends StatelessWidget { + const GcSectionTitle(this.text, {super.key, this.trailing}); + + final String text; + final Widget? trailing; + + @override + Widget build(BuildContext context) { + return Row( + children: [ + Expanded( + child: Text( + text, + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w600, + color: GcColors.ink, + ), + ), + ), + if (trailing != null) trailing!, + ], + ); + } +} + +/// 说明文字。 +class GcHint extends StatelessWidget { + const GcHint(this.text, {super.key}); + + final String text; + + @override + Widget build(BuildContext context) => Text( + text, + style: const TextStyle(fontSize: 12, color: GcColors.faint, height: 1.5), + ); +} diff --git a/GC-UI/frontend/macos/.gitignore b/GC-UI/frontend/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/GC-UI/frontend/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/GC-UI/frontend/macos/Flutter/Flutter-Debug.xcconfig b/GC-UI/frontend/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/GC-UI/frontend/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/GC-UI/frontend/macos/Flutter/Flutter-Release.xcconfig b/GC-UI/frontend/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/GC-UI/frontend/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/GC-UI/frontend/macos/Runner.xcodeproj/project.pbxproj b/GC-UI/frontend/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..137edda --- /dev/null +++ b/GC-UI/frontend/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,705 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* gc_ui.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "gc_ui.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* gc_ui.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* gc_ui.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.morris.gc.gcUi.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/gc_ui.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/gc_ui"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.morris.gc.gcUi.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/gc_ui.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/gc_ui"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.morris.gc.gcUi.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/gc_ui.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/gc_ui"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/GC-UI/frontend/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/GC-UI/frontend/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/GC-UI/frontend/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/GC-UI/frontend/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/GC-UI/frontend/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..44440af --- /dev/null +++ b/GC-UI/frontend/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/GC-UI/frontend/macos/Runner.xcworkspace/contents.xcworkspacedata b/GC-UI/frontend/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/GC-UI/frontend/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/GC-UI/frontend/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/GC-UI/frontend/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/GC-UI/frontend/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/GC-UI/frontend/macos/Runner/AppDelegate.swift b/GC-UI/frontend/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..8e02df2 --- /dev/null +++ b/GC-UI/frontend/macos/Runner/AppDelegate.swift @@ -0,0 +1,9 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } +} diff --git a/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/GC-UI/frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/GC-UI/frontend/macos/Runner/Base.lproj/MainMenu.xib b/GC-UI/frontend/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/GC-UI/frontend/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/GC-UI/frontend/macos/Runner/Configs/AppInfo.xcconfig b/GC-UI/frontend/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..8ee93c2 --- /dev/null +++ b/GC-UI/frontend/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = gc_ui + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.morris.gc.gcUi + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.morris.gc. All rights reserved. diff --git a/GC-UI/frontend/macos/Runner/Configs/Debug.xcconfig b/GC-UI/frontend/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/GC-UI/frontend/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/GC-UI/frontend/macos/Runner/Configs/Release.xcconfig b/GC-UI/frontend/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/GC-UI/frontend/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/GC-UI/frontend/macos/Runner/Configs/Warnings.xcconfig b/GC-UI/frontend/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/GC-UI/frontend/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/GC-UI/frontend/macos/Runner/DebugProfile.entitlements b/GC-UI/frontend/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/GC-UI/frontend/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/GC-UI/frontend/macos/Runner/Info.plist b/GC-UI/frontend/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/GC-UI/frontend/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/GC-UI/frontend/macos/Runner/MainFlutterWindow.swift b/GC-UI/frontend/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/GC-UI/frontend/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/GC-UI/frontend/macos/Runner/Release.entitlements b/GC-UI/frontend/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/GC-UI/frontend/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/GC-UI/frontend/macos/RunnerTests/RunnerTests.swift b/GC-UI/frontend/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/GC-UI/frontend/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/GC-UI/frontend/pubspec.lock b/GC-UI/frontend/pubspec.lock new file mode 100644 index 0000000..e02ce0c --- /dev/null +++ b/GC-UI/frontend/pubspec.lock @@ -0,0 +1,245 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + characters: + dependency: transitive + description: + name: characters + sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" + url: "https://pub.dev" + source: hosted + version: "1.3.0" + clock: + dependency: transitive + description: + name: clock + sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf + url: "https://pub.dev" + source: hosted + version: "1.1.1" + collection: + dependency: transitive + description: + name: collection + sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a + url: "https://pub.dev" + source: hosted + version: "1.18.0" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" + url: "https://pub.dev" + source: hosted + version: "1.3.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3f41d009ba7172d5ff9be5f6e6e6abb4300e263aab8866d2a0842ed2a70f8f0c" + url: "https://pub.dev" + source: hosted + version: "4.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + http: + dependency: "direct main" + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" + url: "https://pub.dev" + source: hosted + version: "4.0.2" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "3f87a60e8c63aecc975dda1ceedbc8f24de75f09e4856ea27daf8958f2f0ce05" + url: "https://pub.dev" + source: hosted + version: "10.0.5" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "932549fb305594d82d7183ecd9fa93463e9914e1b67cacc34bc40906594a1806" + url: "https://pub.dev" + source: hosted + version: "3.0.5" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" + url: "https://pub.dev" + source: hosted + version: "3.0.1" + lints: + dependency: transitive + description: + name: lints + sha256: "976c774dd944a42e83e2467f4cc670daef7eed6295b10b36ae8c85bcbf828235" + url: "https://pub.dev" + source: hosted + version: "4.0.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb + url: "https://pub.dev" + source: hosted + version: "0.12.16+1" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7 + url: "https://pub.dev" + source: hosted + version: "1.15.0" + path: + dependency: transitive + description: + name: path + sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af" + url: "https://pub.dev" + source: hosted + version: "1.9.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.99" + source_span: + dependency: transitive + description: + name: source_span + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" + url: "https://pub.dev" + source: hosted + version: "1.11.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 + url: "https://pub.dev" + source: hosted + version: "2.1.2" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + test_api: + dependency: transitive + description: + name: test_api + sha256: "5b8a98dafc4d5c4c9c72d8b31ab2b23fc13422348d2997120294d3bac86b4ddb" + url: "https://pub.dev" + source: hosted + version: "0.7.2" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "5c5f338a667b4c644744b661f309fb8080bb94b18a7e91ef1dbd343bed00ed6d" + url: "https://pub.dev" + source: hosted + version: "14.2.5" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" +sdks: + dart: ">=3.5.4 <4.0.0" + flutter: ">=3.18.0-18.0.pre.54" diff --git a/GC-UI/frontend/pubspec.yaml b/GC-UI/frontend/pubspec.yaml new file mode 100644 index 0000000..027782e --- /dev/null +++ b/GC-UI/frontend/pubspec.yaml @@ -0,0 +1,92 @@ +name: gc_ui +description: "GC launcher UI (Flutter frontend)" +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.5.4 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + # 与 GC-UI 后端(本地 HTTP 服务)通信 + http: ^1.2.2 + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^4.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/GC-UI/frontend/test/backend_contract_test.dart b/GC-UI/frontend/test/backend_contract_test.dart new file mode 100644 index 0000000..697dd41 --- /dev/null +++ b/GC-UI/frontend/test/backend_contract_test.dart @@ -0,0 +1,95 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:gc_ui/api_client.dart'; + +/// 前后端契约联调测试。 +/// +/// 需要 GC-UI 后端正在运行(`dotnet run --project GC-UI/backend/GC.UI.Server`)。 +/// 后端没起时整组跳过,不会让 CI 变红。 +/// +/// 注意:flutter_test 默认把所有 HTTP 请求拦成 400,这里显式放开真实网络。 +void main() { + setUpAll(() { + HttpOverrides.global = null; + }); + + final api = GcApi( + baseUrl: const String.fromEnvironment( + 'GC_UI_BASE_URL', + defaultValue: 'http://127.0.0.1:17890', + ), + ); + + Future backendUp() async { + try { + await api.health(); + return true; + } catch (_) { + return false; + } + } + + test('health / settings / models / sources / jobs 都能解析', () async { + if (!await backendUp()) { + markTestSkipped('后端未运行,跳过联调测试'); + return; + } + + final health = await api.health(); + expect(health.ok, isTrue); + expect(health.version, isNotEmpty); + expect(health.platform, isNotEmpty); + + final settings = await api.settings(); + expect(settings.modelRoot, isNotEmpty); + expect(settings.dataRoot, isNotEmpty); + expect(settings.renderFps, greaterThan(0)); + expect(settings.memoryMb, greaterThan(0)); + expect(settings.languages, isNotEmpty); + expect(settings.sources, isNotEmpty); + + final models = await api.models(); + for (final model in models) { + expect(model.id, isNotEmpty); + expect(model.name, isNotEmpty); + } + + final sources = await api.sources(); + expect(sources, isNotEmpty); + expect(sources.first.id, isNotEmpty); + + final jobs = await api.jobs(); + expect(jobs, isA>()); + }); + + test('设置补丁能写回并读出一致', () async { + if (!await backendUp()) { + markTestSkipped('后端未运行,跳过联调测试'); + return; + } + + final before = await api.settings(); + final updated = await api.saveSettings( + SettingsPatch(renderFps: before.renderFps == 60 ? 90 : 60), + ); + expect(updated.renderFps, before.renderFps == 60 ? 90 : 60); + + final restored = await api.saveSettings( + SettingsPatch(renderFps: before.renderFps), + ); + expect(restored.renderFps, before.renderFps); + }); + + test('越界路径被后端拒绝', () async { + if (!await backendUp()) { + markTestSkipped('后端未运行,跳过联调测试'); + return; + } + + await expectLater( + api.openFolder('/etc'), + throwsA(isA()), + ); + }); +} diff --git a/GC-UI/frontend/test/widget_test.dart b/GC-UI/frontend/test/widget_test.dart new file mode 100644 index 0000000..85d30a0 --- /dev/null +++ b/GC-UI/frontend/test/widget_test.dart @@ -0,0 +1,85 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:gc_ui/api_client.dart'; +import 'package:gc_ui/i18n.dart'; +import 'package:gc_ui/theme.dart'; + +void main() { + group('I18n', () { + test('resolves auto to a supported language', () { + expect(I18n.supported.contains(I18n.resolve('auto')), isTrue); + expect(I18n.resolve('en-US'), 'en'); + expect(I18n.resolve('zh-CN'), 'zh-CN'); + }); + + test('translates keys and fills placeholders', () { + I18n.language.value = 'zh-CN'; + expect(T('nav.home'), '主页'); + expect(T('home.count', [3]), '3 个模型'); + + I18n.language.value = 'en'; + expect(T('nav.home'), 'Home'); + expect(T('home.count', [3]), '3 models'); + }); + + test('falls back to the key for unknown entries', () { + expect(T('does.not.exist'), 'does.not.exist'); + }); + }); + + group('SettingsPatch', () { + test('only serialises the fields that were set', () { + const patch = SettingsPatch(renderFps: 60, memoryAuto: false); + expect(patch.toJson(), { + 'renderFps': 60, + 'memoryAuto': false, + }); + }); + + test('empty patch serialises to an empty map', () { + expect(const SettingsPatch().toJson(), isEmpty); + }); + }); + + group('GcApi', () { + test('builds model preview urls from the base url', () { + final api = GcApi(baseUrl: 'http://127.0.0.1:17890'); + final model = ModelInfo.fromJson({ + 'id': 'solar-system', + 'name': '太阳系', + 'previewUrl': '/api/models/solar-system/preview', + }); + expect(api.previewUrl(model), + 'http://127.0.0.1:17890/api/models/solar-system/preview'); + }); + + test('parses a model payload', () { + final model = ModelInfo.fromJson({ + 'id': 'earth', + 'name': '地球', + 'version': '1.2.0', + 'sizeBytes': 1048576, + 'sizeText': '1.0 MB', + 'tags': ['天文', '地球'], + 'hasPreview': true, + }); + expect(model.id, 'earth'); + expect(model.tags, ['天文', '地球']); + expect(model.metaText, 'v1.2.0 · 1.0 MB'); + }); + }); + + group('theme', () { + testWidgets('renders a card with its child', (tester) async { + await tester.pumpWidget( + MaterialApp( + theme: buildGcTheme(), + home: const Scaffold( + body: GcCard(child: Text('hello')), + ), + ), + ); + expect(find.text('hello'), findsOneWidget); + }); + }); +} diff --git a/GC-UI/frontend/tool/render_shots_test.dart b/GC-UI/frontend/tool/render_shots_test.dart new file mode 100644 index 0000000..16d708a --- /dev/null +++ b/GC-UI/frontend/tool/render_shots_test.dart @@ -0,0 +1,293 @@ +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:gc_ui/api_client.dart'; +import 'package:gc_ui/controller.dart'; +import 'package:gc_ui/i18n.dart'; +import 'package:gc_ui/pages.dart'; +import 'package:gc_ui/shell.dart'; +import 'package:gc_ui/theme.dart'; + +/// 视觉检查:把真实页面渲染成 PNG 写到 test/shots/。 +/// +/// 用 RepaintBoundary 直接取像素,不走 golden 比较器(避免网络图片阻塞)。 +/// 测试环境默认用 Ahem 占位字体,这里显式加载系统中文字体,否则中文全是方块。 +/// +/// 运行(需要后端已在 127.0.0.1:17890 上跑起来): +/// flutter test tool/render_shots_test.dart +void main() { + setUpAll(() async { + HttpOverrides.global = null; + + const candidates = [ + '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc', + '/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc', + ]; + for (final path in candidates) { + final file = File(path); + if (!file.existsSync()) continue; + final bytes = file.readAsBytesSync(); + final loader = FontLoader('Noto Sans CJK SC') + ..addFont(Future.value(ByteData.view(bytes.buffer))); + await loader.load(); + break; + } + }); + + SettingsInfo sampleSettings() => SettingsInfo.fromJson({ + 'language': 'zh-CN', + 'theme': 'dark', + 'renderFps': 120, + 'memoryMb': 2048, + 'memoryAuto': true, + 'autoUpdateOnStartup': true, + 'requireSignedManifest': true, + 'updateRepository': 'https://git.xhmcl.com/Morris/GC', + 'memoryBudgetMb': 2048, + 'memoryUsageText': '512 MB / 2048 MB', + 'modelRoot': '/Users/morris/.GC/model', + 'dataRoot': '/Users/morris/.GC/data', + 'settingsFile': '/Users/morris/.GC/settings.json', + 'version': '1.0.7', + 'platform': 'osx-arm64', + 'sources': [ + { + 'id': 'github', + 'name': 'GitHub', + 'url': 'https://github.com/Morris-GC/GC', + 'enabled': true, + 'builtIn': true, + 'host': 'github.com', + }, + { + 'id': 'gitee', + 'name': 'Gitee', + 'url': 'https://gitee.com/morris/gc', + 'enabled': true, + 'builtIn': true, + 'host': 'gitee.com', + }, + ], + 'languages': [ + {'code': 'zh-CN', 'label': '简体中文'}, + {'code': 'en', 'label': 'English'}, + ], + }); + + List sampleModels() => [ + ModelInfo.fromJson({ + 'id': 'contour-map', + 'name': '等高线地图', + 'description': '把三维地形与等高线对应起来,识别山峰、山脊、山谷、鞍部与陡崖。', + 'version': '1.0', + 'author': 'Morris GC', + 'sizeBytes': 147351, + 'sizeText': '143.9 KB', + 'tags': ['地理', '地图', '等高线', '地形'], + 'hasPreview': false, + }), + ModelInfo.fromJson({ + 'id': 'solar-system', + 'name': '太阳系', + 'description': '观察八大行星的公转轨道与相对大小,理解日地月系统的尺度关系。', + 'version': '1.2', + 'author': 'Morris GC', + 'sizeBytes': 2411724, + 'sizeText': '2.3 MB', + 'tags': ['天文', '太阳系', '公转'], + 'hasPreview': false, + }), + ModelInfo.fromJson({ + 'id': 'earth-rotation', + 'name': '地球自转', + 'description': '用可交互的三维地球演示自转方向、昼夜交替与地方时差。', + 'version': '1.1', + 'author': 'Morris GC', + 'sizeBytes': 1887436, + 'sizeText': '1.8 MB', + 'tags': ['天文', '地球', '自转'], + 'hasPreview': false, + }), + ]; + + ShellController sampleController() => ShellController(api: GcApi()) + ..settings = sampleSettings() + ..health = HealthInfo.fromJson({ + 'ok': true, + 'version': '1.0.7', + 'platform': 'osx-arm64', + 'uiAvailable': true, + }); + + Future shoot(WidgetTester tester, String name, Widget page) async { + tester.view.physicalSize = const Size(1280, 820); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final key = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + debugShowCheckedModeBanner: false, + theme: buildGcTheme().copyWith( + textTheme: buildGcTheme().textTheme.apply( + fontFamily: 'Noto Sans CJK SC', + ), + ), + home: RepaintBoundary( + key: key, + child: Scaffold(backgroundColor: GcColors.appBg, body: page), + ), + ), + ); + await tester.pump(const Duration(milliseconds: 200)); + // 页面里的数据来自真实后端(/api/about、/api/sources 等)。 + // flutter_test 默认用假时钟,真实 HTTP 永远不会完成,所以这里用 runAsync + // 让出真实时间,等请求回来后再 pump 出最终画面。 + await tester.runAsync(() async { + await Future.delayed(const Duration(milliseconds: 1200)); + }); + await tester.pump(const Duration(milliseconds: 300)); + await tester.runAsync(() async { + await Future.delayed(const Duration(milliseconds: 600)); + }); + await tester.pump(const Duration(milliseconds: 300)); + + final boundary = + key.currentContext!.findRenderObject()! as RenderRepaintBoundary; + final image = await boundary.toImage(pixelRatio: 1.0); + final bytes = await image.toByteData(format: ui.ImageByteFormat.png); + + final dir = Directory('test/shots')..createSync(recursive: true); + File('${dir.path}/$name.png').writeAsBytesSync(bytes!.buffer.asUint8List()); + } + + testWidgets('home', (tester) async { + I18n.language.value = 'zh-CN'; + await shoot( + tester, + 'home', + HomePageView(controller: sampleController(), initialModels: sampleModels()), + ); + }); + + testWidgets('download', (tester) async { + I18n.language.value = 'zh-CN'; + await shoot( + tester, + 'download', + DownloadPageView( + controller: sampleController(), + initialSources: [ + SourceInfo.fromJson({ + 'id': 'github', + 'name': 'GitHub', + 'url': 'https://github.com/Morris-GC/GC', + 'enabled': true, + 'builtIn': true, + 'host': 'github.com', + }), + SourceInfo.fromJson({ + 'id': 'gitee', + 'name': 'Gitee', + 'url': 'https://gitee.com/morris/gc', + 'enabled': true, + 'builtIn': true, + 'host': 'gitee.com', + }), + ], + initialIndex: SourceIndexInfo.fromJson({ + 'sourceId': 'github', + 'root': 'https://github.com/Morris-GC/GC', + 'fromCache': false, + 'resolvedFrom': 'version.json', + 'models': [ + { + 'id': 'solar-system', + 'name': '太阳系', + 'description': '观察八大行星的公转轨道与相对大小。', + 'version': '1.2', + 'sizeBytes': 2411724, + 'sizeText': '2.3 MB', + 'sourceId': 'github', + 'installed': true, + 'installedVersion': '1.2', + }, + { + 'id': 'earth-revolution', + 'name': '地球公转', + 'description': '演示公转轨道、四季成因与太阳直射点移动。', + 'version': '1.0', + 'sizeBytes': 2097152, + 'sizeText': '2.0 MB', + 'sourceId': 'github', + 'installed': false, + }, + { + 'id': 'earth-geography', + 'name': '地球地理', + 'description': '经纬网、海陆分布与大洲大洋的交互式讲解。', + 'version': '1.1', + 'sizeBytes': 3145728, + 'sizeText': '3.0 MB', + 'sourceId': 'github', + 'installed': false, + }, + ], + }), + initialJobs: [ + JobInfo.fromJson({ + 'id': 'job-1', + 'modelId': 'earth-revolution', + 'name': '地球公转', + 'version': '1.0', + 'state': 'Downloading', + 'progress': 0.42, + 'statusText': '正在下载 42%', + 'detailText': '860 KB / 2.0 MB', + 'isActive': true, + }), + ], + ), + ); + }); + + testWidgets('settings', (tester) async { + I18n.language.value = 'zh-CN'; + await shoot(tester, 'settings', SettingsPageView(controller: sampleController())); + }); + + testWidgets('about', (tester) async { + I18n.language.value = 'zh-CN'; + await shoot( + tester, + 'about', + AboutPageView( + controller: sampleController(), + initialAbout: AboutInfo.fromJson({ + 'appName': 'Morris GC', + 'version': '1.0.7', + 'platform': 'osx-arm64', + 'repository': 'https://git.xhmcl.com/Morris/GC', + 'sourceLanguage': 'C#', + 'frontend': 'Flutter', + 'contributors': [ + { + 'name': 'Morris', + 'contributions': 25, + 'avatarUrl': null, + }, + ], + }), + ), + ); + }); + + testWidgets('shell', (tester) async { + I18n.language.value = 'zh-CN'; + await shoot(tester, 'shell', ShellPage(controller: sampleController())); + }); +} diff --git a/GC-UI/frontend/windows/.gitignore b/GC-UI/frontend/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/GC-UI/frontend/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/GC-UI/frontend/windows/CMakeLists.txt b/GC-UI/frontend/windows/CMakeLists.txt new file mode 100644 index 0000000..1b2f617 --- /dev/null +++ b/GC-UI/frontend/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(gc_ui LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "gc_ui") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/GC-UI/frontend/windows/flutter/CMakeLists.txt b/GC-UI/frontend/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/GC-UI/frontend/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/GC-UI/frontend/windows/runner/CMakeLists.txt b/GC-UI/frontend/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/GC-UI/frontend/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/GC-UI/frontend/windows/runner/Runner.rc b/GC-UI/frontend/windows/runner/Runner.rc new file mode 100644 index 0000000..3be81a0 --- /dev/null +++ b/GC-UI/frontend/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.morris.gc" "\0" + VALUE "FileDescription", "gc_ui" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "gc_ui" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.morris.gc. All rights reserved." "\0" + VALUE "OriginalFilename", "gc_ui.exe" "\0" + VALUE "ProductName", "gc_ui" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/GC-UI/frontend/windows/runner/flutter_window.cpp b/GC-UI/frontend/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/GC-UI/frontend/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/GC-UI/frontend/windows/runner/flutter_window.h b/GC-UI/frontend/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/GC-UI/frontend/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/GC-UI/frontend/windows/runner/main.cpp b/GC-UI/frontend/windows/runner/main.cpp new file mode 100644 index 0000000..f34302f --- /dev/null +++ b/GC-UI/frontend/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"gc_ui", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/GC-UI/frontend/windows/runner/resource.h b/GC-UI/frontend/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/GC-UI/frontend/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/GC-UI/frontend/windows/runner/resources/app_icon.ico b/GC-UI/frontend/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/GC-UI/frontend/windows/runner/resources/app_icon.ico differ diff --git a/GC-UI/frontend/windows/runner/runner.exe.manifest b/GC-UI/frontend/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/GC-UI/frontend/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/GC-UI/frontend/windows/runner/utils.cpp b/GC-UI/frontend/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/GC-UI/frontend/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/GC-UI/frontend/windows/runner/utils.h b/GC-UI/frontend/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/GC-UI/frontend/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/GC-UI/frontend/windows/runner/win32_window.cpp b/GC-UI/frontend/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/GC-UI/frontend/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/GC-UI/frontend/windows/runner/win32_window.h b/GC-UI/frontend/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/GC-UI/frontend/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/GC.sln b/GC.sln index b954738..eaff933 100644 --- a/GC.sln +++ b/GC.sln @@ -41,6 +41,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-DOWNLOAD", "GC-DOWNLOAD\ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-SAVEDOG", "GC-SAVEDOG\GC-SAVEDOG.csproj", "{B169F2BF-9E60-40BF-824E-0486573DA65E}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC-UI", "GC-UI", "{560E034A-28FD-4D82-ABD0-FBD0C1B0F553}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "backend", "backend", "{59BED32E-68DD-4FA2-9A8E-89C71966F30E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.UI.Server", "GC-UI\backend\GC.UI.Server\GC.UI.Server.csproj", "{33EA353C-FD81-4288-872E-D9404D9E50AF}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -147,6 +153,18 @@ Global {B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x64.Build.0 = Release|Any CPU {B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x86.ActiveCfg = Release|Any CPU {B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x86.Build.0 = Release|Any CPU + {33EA353C-FD81-4288-872E-D9404D9E50AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {33EA353C-FD81-4288-872E-D9404D9E50AF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {33EA353C-FD81-4288-872E-D9404D9E50AF}.Debug|x64.ActiveCfg = Debug|Any CPU + {33EA353C-FD81-4288-872E-D9404D9E50AF}.Debug|x64.Build.0 = Debug|Any CPU + {33EA353C-FD81-4288-872E-D9404D9E50AF}.Debug|x86.ActiveCfg = Debug|Any CPU + {33EA353C-FD81-4288-872E-D9404D9E50AF}.Debug|x86.Build.0 = Debug|Any CPU + {33EA353C-FD81-4288-872E-D9404D9E50AF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {33EA353C-FD81-4288-872E-D9404D9E50AF}.Release|Any CPU.Build.0 = Release|Any CPU + {33EA353C-FD81-4288-872E-D9404D9E50AF}.Release|x64.ActiveCfg = Release|Any CPU + {33EA353C-FD81-4288-872E-D9404D9E50AF}.Release|x64.Build.0 = Release|Any CPU + {33EA353C-FD81-4288-872E-D9404D9E50AF}.Release|x86.ActiveCfg = Release|Any CPU + {33EA353C-FD81-4288-872E-D9404D9E50AF}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -165,5 +183,7 @@ Global {AB63C416-5783-4FB9-A162-5BBA32E8BFCC} = {09578AA7-0862-3E52-D2AA-D8F7E863B74B} {6C38EF76-7D14-0C76-0B88-84F29EAA96CD} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE} {98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3} = {BCA2AA3E-F98F-43A1-9D31-239103C303F7} + {59BED32E-68DD-4FA2-9A8E-89C71966F30E} = {560E034A-28FD-4D82-ABD0-FBD0C1B0F553} + {33EA353C-FD81-4288-872E-D9404D9E50AF} = {59BED32E-68DD-4FA2-9A8E-89C71966F30E} EndGlobalSection EndGlobal diff --git a/README.md b/README.md index ed4882f..ce6f570 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,35 @@ - 目标平台:**macOS arm64 / Windows x64 / Windows arm64**(Linux 可自行编译,未列入发布矩阵) - 更新仓库:,模型目录 +## GC-UI:前后端分离版(Flutter 前端) + +`GC-UI/` 是同一套服务层的**前后端分离**实现,界面改用 Flutter,Windows 与 macOS 共用一套代码: + +``` +GC-UI/ +├── backend/GC.UI.Server/ .NET 8 本地 HTTP 服务(复用 GC/src + GC-DOWNLOAD)+ 模型窗口宿主 +└── frontend/ Flutter 桌面应用(windows/ 与 macos/ 原生 runner) +``` + +- **前端**:Flutter(`flutter create --platforms=windows,macos` 生成两个原生壳),负责首页 / 下载 / 设置 / 关于 +- **后端**:.NET 8 最小 API,只监听 `127.0.0.1`,负责模型扫描、下载、更新、设置持久化 +- **模型窗口**:仍由 .NET 承载 —— 模型 dll 返回的是 Avalonia `Control`,渲染栈属于模型契约,不能换 + +`GC-UI/` 的详情、平台选型理由与接口列表见 [`GC-UI/README.md`](GC-UI/README.md)。 +「关于」页会直接展示 **源码语言:C#、前端:Flutter**(由后端 `/api/about` 下发)。 + +```bash +# 后端 +dotnet run --project GC-UI/backend/GC.UI.Server + +# 前端(另开终端) +cd GC-UI/frontend && flutter pub get +flutter run -d windows # 或 -d macos +``` + +详见 [GC-UI/README.md](GC-UI/README.md)(含完整接口表、构建脚本与测试说明)。 + + ## 快速开始 ```bash