feat(ui): 重做启动器界面并修复 DPI 发糊
PR 审核 / 后端编译 (pull_request) Canceled after 0s
PR 审核 / 后端自检 (pull_request) Canceled after 0s
PR 审核 / 前端检查(Flutter) (pull_request) Canceled after 0s
PR 审核 / 安全扫描 (pull_request) Canceled after 0s
PR 审核 / 审核汇总 (pull_request) Canceled after 0s

- 交叉编译补嵌 runner.exe.manifest:GNUn res 不再丢掉 DPI 声明,缩放屏不再位图拉伸
- main.cpp 建窗前自行声明 Per-Monitor V2 DPI 感知(三级回退)
- win32_window 初始窗口按显示器工作区上限收缩,避免 150% 缩放后超出屏幕
- 重做主题:中性石墨底 + 高对比正文、统一字号/间距/圆角令牌、Segoe UI + 雅黑字体栈
- 首页/下载/设置/关于四页重排,宽屏自适应、小窗不溢出
- 修复下拉框字体丢失、封面遮罩盖住占位、任务状态未翻译等问题
- 截图脚本:注入 CJK/图标字体、runAsync 取像素、补小窗回归用例
This commit is contained in:
lead committed 2026-11-18 22:15:54 +08:00
1 parent 6ee2e8bead
commit e67cc63998
10 files changed
+2518 -1080

No files matched your search

+19
View File
@@ -137,6 +137,25 @@ GC-UI.exe flutter_windows.dll data/{icudtl.dat, app.so, flutter_assets/}
- `Runner.rc` 在 windres 下有两处不兼容:图标用反斜杠相对路径、`VERSION_AS_STRING`
依赖命令行传 `-D` 的转义字符串。脚本生成一份路径与宏都已规整的 rc 副本再编译。
### 交叉编译必须自己嵌 DPI 清单
`windows/runner/CMakeLists.txt` 把 `runner.exe.manifest` 当**源文件**列进 target,
Visual Studio 生成器会把它交给链接器(`/MANIFESTINPUT`)自动嵌入 exe;
但 `buildsh/cross/CMakeLists.txt` 只用 windres 编 `Runner.rc`,CMake 不会做这一步。
结果就是交叉编出来的 `GC-UI.exe` **完全没有清单**:Windows 认为它「DPI 不感知」,
在 125% / 150% 缩放的屏幕上把整块窗口当位图拉伸 —— 界面整体发虚,中文小字最明显。
现在两处都已加固,改这块代码时不要拆掉任何一处:
| 位置 | 做法 |
|---|---|
| `buildsh/cross/CMakeLists.txt` | 往 `Runner.cross.rc` 追加 `1 24 "<abs>/runner.exe.manifest"`(id 1 = CREATEPROCESS_MANIFEST_RESOURCE_ID,type 24 = RT_MANIFEST) |
| `windows/runner/main.cpp` | 建窗之前调 `SetProcessDpiAwarenessContext(PER_MONITOR_AWARE_V2)`,失败依次退到 `SetProcessDpiAwareness` / `SetProcessDPIAware` |
`main.cpp` 那层是兜底:即使清单因为工具链原因没嵌进去,程序自己也会声明 DPI 感知。
验证办法(Windows):`GC-UI.exe` 属性 →「兼容性」里不该出现「替代高 DPI 缩放行为」,
或在 125% 缩放下截图,文字边缘应是锐利的 1.25 倍像素,而不是模糊的插值。
`.gitea/workflows` 里的 `windows` 任务仍然跑在 `windows-latest` 上;若手头只有 macOS/Linux
构建机,可以把该任务的 `runs-on` 换成对应标签,直接复用这套交叉编译脚本,
不再需要 VS Build Tools。
+26 -5
View File
@@ -149,14 +149,35 @@ flutter test
# 前后端联调(需要后端正在运行;后端没起时自动跳过)
flutter test test/backend_contract_test.dart
# 生成界面截图到 test/shots/(视觉检查用)
# 生成界面截图到 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` 的假时钟会让页面停在加载态。
截图脚本覆盖四个页面(首页 / 下载 / 设置 / 关于),再加一整套外壳与 1024×680 小窗回归:
`test/shots/home.png`、`download.png`、`settings.png`、`about.png`、`shell.png`、
`home-small.png`、`download-small.png`、`settings-small.png`,以及浅色主题的
`home-light.png`、`settings-light.png`。小窗用例会顺带抓布局溢出(RenderFlex overflow)。
四个页面都用预置数据(`initialModels` / `initialSources` / `initialAbout` 等)渲染,
所以**不需要先起后端**。测试环境的字体是 Ahem(所有字都是方块),脚本会显式加载
系统里的 Noto Sans SC / 微软雅黑 / 苹方,并顺带加载 Material 图标字体,中文和图标才正常。
截图必须放在 `runAsync` 里取像素(`toImage` / `toByteData` 走真实引擎管线),
否则 fake async 时钟不推进,每个用例会卡满 10 分钟才超时。
## 界面清晰度(DPI)
`GC-UI.exe` 必须在启动时就声明 DPI 感知,否则 Windows 在 125% / 150% 缩放下会把
整块窗口当位图拉伸,界面看起来「糊」—— 中文小字最先糊。两处保证:
- `windows/runner/runner.exe.manifest`:PerMonitorV2(原生 MSVC 构建由 CMake 自动嵌入)
- `windows/runner/main.cpp`:建窗前再声明一次,依次尝试
`SetProcessDpiAwarenessContext` → `SetProcessDpiAwareness` → `SetProcessDPIAware`
- `buildsh/cross/CMakeLists.txt`:交叉编译时把清单写进 `.rc`(windres 不会自动嵌入)
另外主题里做了两件跟「清晰」有关的事:字体族走
`Segoe UI + Microsoft YaHei UI`(macOS 走苹方)而不是让引擎随意回退;
正文最小 12px、行高固定,中文不再挤成一片。详见
[CI.md 的「交叉编译必须自己嵌 DPI 清单」](CI.md#交叉编译必须自己嵌-dpi-清单)。
## 「关于」页展示的技术栈
+2
View File
@@ -42,6 +42,8 @@ class _GcUiAppState extends State<GcUiApp> {
return MaterialApp(
title: 'Morris GC',
debugShowCheckedModeBanner: false,
// 桌面端不要移动端那套拉伸回弹和边缘光晕。
scrollBehavior: const GcScrollBehavior(),
theme: buildGcTheme(Brightness.light),
darkTheme: buildGcTheme(Brightness.dark),
themeMode: mode,
File diff suppressed because it is too large. Load diff
+184 -86
View File
@@ -14,12 +14,31 @@ class _NavItem {
}
const List<_NavItem> _navItems = <_NavItem>[
_NavItem(Icons.grid_view_rounded, 'nav.home'),
_NavItem(Icons.dashboard_rounded, 'nav.home'),
_NavItem(Icons.download_rounded, 'nav.download'),
_NavItem(Icons.tune_rounded, 'nav.settings'),
_NavItem(Icons.info_outline_rounded, 'nav.about'),
];
/// 桌面端滚动行为:去掉移动端的拉伸回弹和边缘光晕,滚轮更跟手。
class GcScrollBehavior extends MaterialScrollBehavior {
const GcScrollBehavior();
@override
Widget buildOverscrollIndicator(
BuildContext context,
Widget child,
ScrollableDetails details,
) {
return child;
}
@override
ScrollPhysics getScrollPhysics(BuildContext context) {
return const ClampingScrollPhysics(parent: AlwaysScrollableScrollPhysics());
}
}
/// 应用外壳:左侧导航 + 右侧内容 + 底部更新状态条。
class ShellPage extends StatefulWidget {
const ShellPage({super.key, required this.controller});
@@ -52,6 +71,7 @@ class _ShellPageState extends State<ShellPage> {
body: Row(
children: <Widget>[
_Sidebar(controller: controller),
Container(width: 1, color: GcColors.line),
Expanded(
child: Column(
children: <Widget>[
@@ -75,9 +95,9 @@ class _ShellPageState extends State<ShellPage> {
}
return const Center(
child: SizedBox(
width: 26,
height: 26,
child: CircularProgressIndicator(strokeWidth: 2.4),
width: 22,
height: 22,
child: CircularProgressIndicator(strokeWidth: 2),
),
);
}
@@ -124,52 +144,25 @@ class _Sidebar extends StatelessWidget {
Widget build(BuildContext context) {
final settings = controller.settings;
return Container(
width: 236,
width: GcSize.sidebar,
color: GcColors.sideBg,
padding: const EdgeInsets.fromLTRB(16, 20, 16, 18),
padding: const EdgeInsets.fromLTRB(
GcSpace.xl, GcSpace.xxl, GcSpace.lg, GcSpace.lg),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Container(
width: 26,
height: 26,
decoration: BoxDecoration(
color: GcColors.surfaceAlt,
borderRadius: BorderRadius.circular(8),
),
alignment: Alignment.center,
child: Text(
'◎',
style: TextStyle(fontSize: 14, color: GcColors.accent),
),
),
const SizedBox(width: 10),
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),
_brand(),
const SizedBox(height: GcSpace.xxxl),
const Padding(
padding: EdgeInsets.only(left: 14, bottom: 6),
padding: EdgeInsets.only(left: 10, bottom: GcSpace.sm),
child: Text(
'MENU',
style: TextStyle(
fontSize: 9.5,
letterSpacing: 1.2,
fontSize: 11,
height: 1.2,
letterSpacing: 1.4,
fontWeight: FontWeight.w600,
color: Color(0xFF4C5F80),
color: Color(0xFF5C6A80),
),
),
),
@@ -181,25 +174,91 @@ class _Sidebar extends StatelessWidget {
),
const Spacer(),
Container(height: 1, color: GcColors.line),
const SizedBox(height: 10),
const SizedBox(height: GcSpace.md),
Padding(
padding: const EdgeInsets.only(left: 14),
child: Text(
'v${settings?.version ?? '—'}',
style: 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)),
padding: const EdgeInsets.only(left: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'v${settings?.version ?? '—'}',
style: TextStyle(
fontSize: 12,
height: 1.4,
fontWeight: FontWeight.w600,
color: GcColors.muted,
),
),
const SizedBox(height: 2),
Text(
settings?.platform ?? '—',
style: TextStyle(
fontSize: 11.5,
height: 1.4,
color: GcColors.ghost,
),
),
],
),
),
],
),
);
}
/// 品牌区:一个渐变圆角标 + 名称 + 一句定位。
Widget _brand() {
return Row(
children: <Widget>[
Container(
width: 32,
height: 32,
alignment: Alignment.center,
decoration: BoxDecoration(
color: GcColors.accentSoft,
borderRadius: BorderRadius.circular(9),
border: Border.all(
color: Color.alphaBlend(
GcColors.accent.withOpacity(0.35), GcColors.sideBg),
),
),
child: Text(
'◎',
style: TextStyle(fontSize: 16, height: 1.1, color: GcColors.accent),
),
),
const SizedBox(width: GcSpace.md),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
'Morris GC',
style: TextStyle(
fontSize: 14,
height: 1.3,
fontWeight: FontWeight.w600,
color: GcColors.ink,
),
),
const SizedBox(height: 1),
Text(
'SCIENCE · CLASSROOM',
style: TextStyle(
fontSize: 10,
height: 1.3,
letterSpacing: 0.9,
fontWeight: FontWeight.w600,
color: GcColors.ghost,
),
),
],
),
),
],
);
}
}
class _NavButton extends StatelessWidget {
@@ -216,29 +275,34 @@ class _NavButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 4),
padding: const EdgeInsets.only(bottom: GcSpace.xs),
child: Material(
color: active ? GcColors.surfaceAlt : Colors.transparent,
borderRadius: BorderRadius.circular(9),
color: active ? GcColors.accentSoft : Colors.transparent,
borderRadius: BorderRadius.circular(GcRadius.control),
child: InkWell(
borderRadius: BorderRadius.circular(9),
borderRadius: BorderRadius.circular(GcRadius.control),
onTap: onTap,
hoverColor: GcColors.surfaceHover,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
padding: const EdgeInsets.symmetric(
horizontal: GcSpace.md,
vertical: 11,
),
child: Row(
children: <Widget>[
Icon(
item.icon,
size: 16,
size: 17,
color: active ? GcColors.accent : GcColors.faint,
),
const SizedBox(width: 10),
const SizedBox(width: GcSpace.md),
Text(
T(item.labelKey),
style: TextStyle(
fontSize: 12.5,
fontSize: 13.5,
height: 1.2,
fontWeight: active ? FontWeight.w600 : FontWeight.w400,
color: active ? GcColors.ink : GcColors.muted,
color: active ? GcColors.accent : GcColors.muted,
),
),
],
@@ -262,20 +326,28 @@ class _UpdateBar extends StatelessWidget {
color: GcColors.surface,
border: Border(top: BorderSide(color: GcColors.line)),
),
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 9),
padding: const EdgeInsets.symmetric(
horizontal: GcSpace.xxl,
vertical: GcSpace.md,
),
child: Row(
children: <Widget>[
Text('⟳',
style: TextStyle(fontSize: 16, color: GcColors.accent)),
const SizedBox(width: 12),
Icon(
Icons.sync_rounded,
size: 18,
color: GcColors.accent,
),
const SizedBox(width: GcSpace.md),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
controller.updateStatus,
style: TextStyle(
fontSize: 12.5,
fontSize: 13,
height: 1.35,
fontWeight: FontWeight.w600,
color: GcColors.ink,
),
@@ -284,23 +356,41 @@ class _UpdateBar extends StatelessWidget {
if (controller.updateDetail.isNotEmpty)
Text(
controller.updateDetail,
style: TextStyle(fontSize: 11, color: GcColors.faint),
style: TextStyle(
fontSize: 12,
height: 1.4,
color: GcColors.faint,
),
overflow: TextOverflow.ellipsis,
),
if (controller.launcherNotice.isNotEmpty)
Text(
controller.launcherNotice,
style: TextStyle(fontSize: 11, color: GcColors.warn),
style: TextStyle(
fontSize: 12,
height: 1.4,
color: GcColors.warn,
),
),
],
),
),
if (controller.updateBusy)
const SizedBox(
width: 130,
child: LinearProgressIndicator(minHeight: 4),
if (controller.updateBusy) ...<Widget>[
const SizedBox(width: GcSpace.lg),
SizedBox(
width: 140,
child: ClipRRect(
borderRadius: BorderRadius.circular(3),
child: LinearProgressIndicator(
value: controller.updateProgress > 0
? controller.updateProgress.clamp(0, 1).toDouble()
: null,
minHeight: 4,
),
),
),
const SizedBox(width: 14),
],
const SizedBox(width: GcSpace.lg),
TextButton(
onPressed: controller.updateBusy
? null
@@ -324,24 +414,32 @@ class _BackendDown extends StatelessWidget {
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 520),
child: GcCard(
padding: const EdgeInsets.all(28),
padding: const EdgeInsets.all(GcSpace.xxl),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
T('common.error'),
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.w600,
color: GcColors.ink,
),
Row(
children: <Widget>[
Icon(Icons.error_outline_rounded,
size: 20, color: GcColors.danger),
const SizedBox(width: GcSpace.sm),
Text(
T('common.error'),
style: TextStyle(
fontSize: 16,
height: 1.35,
fontWeight: FontWeight.w600,
color: GcColors.ink,
),
),
],
),
const SizedBox(height: 10),
const SizedBox(height: GcSpace.md),
GcHint(controller.loadError ?? ''),
const SizedBox(height: 6),
GcHint('后端地址:${controller.api.baseUrl}'),
const SizedBox(height: 16),
const SizedBox(height: GcSpace.xs),
GcHint('${T('set.backend')}: ${controller.api.baseUrl}'),
const SizedBox(height: GcSpace.lg),
FilledButton(
onPressed: controller.bootstrap,
child: Text(T('common.retry')),
File diff suppressed because it is too large. Load diff
+150 -24
View File
@@ -21,9 +21,18 @@ import 'package:gc_ui/theme.dart';
/// flutter test tool/render_shots_test.dart
void main() {
setUpAll(() async {
HttpOverrides.global = null;
// 不要设置 HttpOverrides.global = null:那会打开真实网络,
// flutter_test 的假时钟下 HTTP 定时器永远悬着,用例结束时
// 会撞上「!timersPending」断言。保持 flutter_test 默认的 FakeHttpClient
// (所有请求立即返回 400),页面本身都用预置数据渲染,不需要后端。
// 测试环境默认用 Ahem 占位字体(所有字都是方块),必须显式加载一套真字体:
// Linux CI 用 Noto CJK,Windows 本机用 Noto Sans SC / 微软雅黑,macOS 用苹方。
const candidates = <String>[
r'C:\Windows\Fonts\Deng.ttf',
r'C:\Windows\Fonts\NotoSansSC-VF.ttf',
r'C:\Windows\Fonts\msyh.ttc',
r'C:\Windows\Fonts\simhei.ttf',
'/System/Library/Fonts/PingFang.ttc',
'/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc',
'/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc',
];
@@ -36,6 +45,22 @@ void main() {
await loader.load();
break;
}
// Material 图标字体:flutter_test 不会自动加载,不加载的话所有 Icon
// 都是方框,截图就没法检查图标。SDK 缓存里那份由 flutter test 通过
// FLUTTER_ROOT 指过来。
final flutterRoot = Platform.environment['FLUTTER_ROOT'];
if (flutterRoot != null) {
final icons = File(
'$flutterRoot/bin/cache/artifacts/material_fonts/materialicons-regular.otf',
);
if (icons.existsSync()) {
final bytes = icons.readAsBytesSync();
final loader = FontLoader('MaterialIcons')
..addFont(Future<ByteData>.value(ByteData.view(bytes.buffer)));
await loader.load();
}
}
});
SettingsInfo sampleSettings() => SettingsInfo.fromJson(<String, dynamic>{
@@ -123,9 +148,26 @@ void main() {
'uiAvailable': true,
});
/// 外壳用的 controller:bootstrap 直接返回,不去连后端。
///
/// 真 ShellPage 会在 initState 里 bootstrap,后端不在时会挂重试定时器,
/// 用例结束时报「!timersPending」。这里只把 bootstrap 换成空实现,
/// 页面里的数据请求仍会走 flutter_test 的假 HTTP(立即 400)。
ShellController shellController() => _StubShellController()
..settings = sampleSettings()
..health = HealthInfo.fromJson(<String, dynamic>{
'ok': true,
'version': '1.0.7',
'platform': 'osx-arm64',
'uiAvailable': true,
});
Future<void> shoot(WidgetTester tester, String name, Widget page,
{Brightness brightness = Brightness.dark}) async {
tester.view.physicalSize = const Size(1280, 820);
{Brightness brightness = Brightness.dark,
Size size = const Size(1280, 860)}) async {
// 1280×860:与发布包窗口默认尺寸(1280×720)接近,再多留一点高度看得到
// 底部状态条。像素比 1.0,方便逐像素检查描边和文字。
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
@@ -136,10 +178,13 @@ void main() {
await tester.pumpWidget(
MaterialApp(
debugShowCheckedModeBanner: false,
theme: buildGcTheme(brightness).copyWith(
textTheme: buildGcTheme(brightness).textTheme.apply(
fontFamily: 'Noto Sans CJK SC',
),
// 四个页面都用预置数据渲染,不需要后端;字体统一换成测试里加载的
// 那一套,并且清空 fallback —— 否则主题里的按钮 / 输入框样式会去
// 找系统字体(测试环境没有),缺字处就画成方块。
theme: buildGcTheme(
brightness,
fontFamily: 'Noto Sans CJK SC',
fontFamilyFallback: const <String>[],
),
home: RepaintBoundary(
key: key,
@@ -148,25 +193,27 @@ void main() {
),
);
await tester.pump(const Duration(milliseconds: 200));
// 页面里的数据来自真实后端(/api/about、/api/sources 等)。
// flutter_test 默认用假时钟,真实 HTTP 永远不会完成,所以这里用 runAsync
// 让出真实时间,等请求回来后再 pump 出最终画面。
await tester.runAsync(() async {
await Future<void>.delayed(const Duration(milliseconds: 1200));
});
await tester.pump(const Duration(milliseconds: 300));
await tester.runAsync(() async {
await Future<void>.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);
// toImage / toByteData 要走真实引擎的异步管线,必须放在 runAsync 里,
// 否则 fake async 时钟不会推进,Future 一直不完成(表现为每个用例卡
// 满 10 分钟超时才返回)。
final stopwatch = Stopwatch()..start();
final image = await tester.runAsync(
() => boundary.toImage(pixelRatio: 1.0),
);
final bytes = await tester.runAsync(
() => image!.toByteData(format: ui.ImageByteFormat.png),
);
final dir = Directory('test/shots')..createSync(recursive: true);
File('${dir.path}/$name.png').writeAsBytesSync(bytes!.buffer.asUint8List());
stopwatch.stop();
// ignore: avoid_print
print(
'[shots] $name (${brightness.name}) 耗时 ${stopwatch.elapsedMilliseconds} ms');
}
testWidgets('home', (tester) async {
@@ -174,7 +221,8 @@ void main() {
await shoot(
tester,
'home',
HomePageView(controller: sampleController(), initialModels: sampleModels()),
HomePageView(
controller: sampleController(), initialModels: sampleModels()),
);
});
@@ -261,7 +309,8 @@ void main() {
testWidgets('settings', (tester) async {
I18n.language.value = 'zh-CN';
await shoot(tester, 'settings', SettingsPageView(controller: sampleController()));
await shoot(
tester, 'settings', SettingsPageView(controller: sampleController()));
});
testWidgets('about', (tester) async {
@@ -292,7 +341,77 @@ void main() {
testWidgets('shell', (tester) async {
I18n.language.value = 'zh-CN';
await shoot(tester, 'shell', ShellPage(controller: sampleController()));
final controller = shellController()
..setUpdateStatus(
visible: true,
busy: false,
progress: 1,
status: '已更新 2 个模型,立即生效',
detail: '模型与启动器均为最新版',
notice: '',
);
await shoot(tester, 'shell', ShellPage(controller: controller));
});
/// 小窗口回归:1024×680 下不应出现溢出条纹或卡片挤压。
testWidgets('home-small', (tester) async {
I18n.language.value = 'zh-CN';
await shoot(
tester,
'home-small',
HomePageView(
controller: sampleController(), initialModels: sampleModels()),
size: const Size(1024, 680),
);
});
testWidgets('download-small', (tester) async {
I18n.language.value = 'zh-CN';
await shoot(
tester,
'download-small',
DownloadPageView(
controller: sampleController(),
initialSources: <SourceInfo>[
SourceInfo.fromJson(<String, dynamic>{
'id': 'github',
'name': 'GitHub',
'url': 'https://github.com/Morris-GC/GC',
'enabled': true,
'builtIn': true,
'host': 'github.com',
}),
],
initialIndex: SourceIndexInfo.fromJson(<String, dynamic>{
'sourceId': 'github',
'root': 'https://github.com/Morris-GC/GC',
'fromCache': false,
'resolvedFrom': 'version.json',
'models': <dynamic>[
<String, dynamic>{
'id': 'sun',
'name': '太阳系',
'description': '观察八大行星的公转轨道与相对大小。',
'version': '1.2',
'sizeText': '2.3 MB',
'installed': true,
},
],
}),
initialJobs: const <JobInfo>[],
),
size: const Size(1024, 680),
);
});
testWidgets('settings-small', (tester) async {
I18n.language.value = 'zh-CN';
await shoot(
tester,
'settings-small',
SettingsPageView(controller: sampleController()),
size: const Size(1024, 680),
);
});
testWidgets('home-light', (tester) async {
@@ -300,7 +419,8 @@ void main() {
await shoot(
tester,
'home-light',
HomePageView(controller: sampleController(), initialModels: sampleModels()),
HomePageView(
controller: sampleController(), initialModels: sampleModels()),
brightness: Brightness.light,
);
});
@@ -315,3 +435,9 @@ void main() {
);
});
}
/// 只用于截图的 controller:不连后端,避免挂上重试定时器。
class _StubShellController extends ShellController {
@override
Future<void> bootstrap() async {}
}
+73
View File
@@ -5,8 +5,81 @@
#include "flutter_window.h"
#include "utils.h"
namespace {
// Enable DPI awareness (Per-Monitor V2 when available).
//
// The runner.exe.manifest normally declares this, but the mingw/windres cross
// build does not embed the manifest the way the Visual Studio generator does.
// A DPI-unaware process gets bitmap-stretched by Windows on a 125% / 150%
// scaled display, which makes the whole UI (especially small CJK text) look
// blurry. Declaring it again before any window exists costs nothing and does
// not depend on the manifest being present.
//
// Every API is resolved through GetProcAddress: it keeps the binary working on
// older systems and does not require the current SDK / mingw headers to declare
// DPI_AWARENESS_CONTEXT.
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4191) // FARPROC to typed function pointer, on purpose
#endif
BOOL TryPerMonitorV2() {
// DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 == (HANDLE)-4
using Fn = BOOL(WINAPI*)(HANDLE);
HMODULE user32 = ::GetModuleHandleW(L"user32.dll");
if (user32 == nullptr) return FALSE;
auto set_context = reinterpret_cast<Fn>(
::GetProcAddress(user32, "SetProcessDpiAwarenessContext"));
if (set_context == nullptr) return FALSE;
// Cast through INT_PTR: plain -4 to pointer is C4312 at /W4.
return set_context(reinterpret_cast<HANDLE>(static_cast<INT_PTR>(-4)));
}
void TryPerMonitor() {
// Windows 8.1+: PROCESS_PER_MONITOR_DPI_AWARE == 2
using Fn = HRESULT(WINAPI*)(int);
HMODULE shcore = ::LoadLibraryW(L"shcore.dll");
if (shcore == nullptr) return;
auto set_awareness =
reinterpret_cast<Fn>(::GetProcAddress(shcore, "SetProcessDpiAwareness"));
if (set_awareness != nullptr) {
// E_ACCESSDENIED means the manifest already set awareness: still fine.
set_awareness(2);
}
::FreeLibrary(shcore);
}
void TrySystemDpiAware() {
// Windows Vista+: system DPI awareness, better than nothing.
using Fn = BOOL(WINAPI*)();
HMODULE user32 = ::GetModuleHandleW(L"user32.dll");
if (user32 == nullptr) return;
auto set_aware =
reinterpret_cast<Fn>(::GetProcAddress(user32, "SetProcessDPIAware"));
if (set_aware != nullptr) set_aware();
}
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
void EnableDpiAwareness() {
// When the manifest already declared awareness, SetProcessDpiAwarenessContext
// returns FALSE; fall back to the 8.1 and Vista entry points. All three
// failing is harmless: the app still starts, it just scales blurrily.
if (TryPerMonitorV2()) return;
TryPerMonitor();
TrySystemDpiAware();
}
} // namespace
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t *command_line, _In_ int show_command) {
// Must run before the first window is created to take effect.
EnableDpiAwareness();
// 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()) {
+18 -2
View File
@@ -134,11 +134,27 @@ bool Win32Window::Create(const std::wstring& title,
UINT dpi = FlutterDesktopGetDpiForMonitor(monitor);
double scale_factor = dpi / 96.0;
// Cap the initial size to the monitor work area. 1280x720 logical is
// 1920x1080 physical at 150% scaling, which no longer fits on a 1080p
// screen; clamping keeps the window usable instead of hanging off-screen.
int physical_width = Scale(size.width, scale_factor);
int physical_height = Scale(size.height, scale_factor);
MONITORINFO monitor_info{};
monitor_info.cbSize = sizeof(MONITORINFO);
if (::GetMonitorInfoW(monitor, &monitor_info)) {
const int max_width =
(monitor_info.rcWork.right - monitor_info.rcWork.left) * 92 / 100;
const int max_height =
(monitor_info.rcWork.bottom - monitor_info.rcWork.top) * 92 / 100;
if (physical_width > max_width) physical_width = max_width;
if (physical_height > max_height) physical_height = max_height;
}
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);
physical_width, physical_height, nullptr, nullptr,
GetModuleHandle(nullptr), this);
if (!window) {
return false;
+13
View File
@@ -44,6 +44,19 @@ string(REPLACE "#define VERSION_AS_STRING FLUTTER_VERSION"
_rc_text "${_rc_text}")
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/Runner.cross.rc" "${_rc_text}")
# ★ DPI 清单必须自己嵌进去。
#
# windows/runner/CMakeLists.txt 把 runner.exe.manifest 当源文件列进 target,
# Visual Studio 生成器会把它交给链接器(/MANIFESTINPUT)自动嵌入;
# 但这里的交叉编译只用 windres 编 Runner.rc,CMake 不会做这一步,
# 编出来的 GC-UI.exe 就完全没有清单 —— Windows 当它「DPI 不感知」,
# 在 125% / 150% 缩放的屏幕上整体位图拉伸,界面全是糊的。
#
# 因此把清单直接写成资源条目:id 1 = CREATEPROCESS_MANIFEST_RESOURCE_ID,
# type 24 = RT_MANIFEST。windres 不按相对路径解析,这里给绝对路径。
file(APPEND "${CMAKE_CURRENT_BINARY_DIR}/Runner.cross.rc"
"\n1 24 \"${RUN_DIR}/runner.exe.manifest\"\n")
add_executable(${BINARY_NAME} WIN32
"${RUN_DIR}/main.cpp"
"${RUN_DIR}/flutter_window.cpp"