feat: WASM web support

This commit is contained in:
xkeyC
2025-11-13 20:07:47 +08:00
parent 193d2c7496
commit 476c40f4cd
106 changed files with 2276 additions and 4299 deletions

View File

@@ -1,8 +1,12 @@
import 'dart:io';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_tilt/flutter_tilt.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:file_picker/file_picker.dart';
import 'package:starcitizen_doctor/api/analytics.dart';
import 'package:starcitizen_doctor/common/helper/log_helper.dart';
import 'package:starcitizen_doctor/common/helper/system_helper.dart';
@@ -26,20 +30,53 @@ class HomeGameDoctorUI extends HookConsumerWidget {
AnalyticsApi.touch("auto_scan_issues");
SchedulerBinding.instance.addPostFrameCallback((timeStamp) {
dPrint("HomeGameDoctorUI useEffect doCheck timeStamp === $timeStamp");
model.doCheck(context);
if (kIsWeb) {
// Web 平台自动弹出文件选择器
_selectLogFile(context, model);
} else {
model.doCheck(context);
}
});
return null;
}, []);
return makeDefaultPage(context,
title: S.current
.doctor_title_one_click_diagnosis(homeState.scInstalledPath ?? ""),
useBodyContainer: true,
content: Stack(
children: [
Column(
children: [
const SizedBox(height: 12),
return makeDefaultPage(
context,
title: S.current.doctor_title_one_click_diagnosis(homeState.scInstalledPath ?? ""),
useBodyContainer: true,
content: Stack(
children: [
Column(
children: [
const SizedBox(height: 12),
if (kIsWeb)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Row(
children: [
FilledButton(
child: Padding(
padding: const EdgeInsets.all(8),
child: Row(
children: [
const Icon(FluentIcons.folder_open),
const SizedBox(width: 6),
Text(S.current.doctor_action_select_log_file),
],
),
),
onPressed: () => _selectLogFile(context, model),
),
if (state.customLogFilePath != null) ...[
const SizedBox(width: 12),
Expanded(
child: Text(S.current.doctor_info_log_file_selected, style: TextStyle(color: Colors.green)),
),
],
],
),
)
else
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
@@ -50,118 +87,102 @@ class HomeGameDoctorUI extends HookConsumerWidget {
Padding(
padding: const EdgeInsets.only(left: 6, right: 6),
child: Button(
child: Padding(
padding: const EdgeInsets.all(4),
child: Row(
children: [
const Icon(FluentIcons.folder_open),
const SizedBox(width: 6),
Text(item.value),
],
),
child: Padding(
padding: const EdgeInsets.all(4),
child: Row(
children: [
const Icon(FluentIcons.folder_open),
const SizedBox(width: 6),
Text(item.value),
],
),
onPressed: () =>
_onTapButton(context, item.key, homeState)),
),
onPressed: () => _onTapButton(context, item.key, homeState),
),
),
],
),
if (state.isChecking)
Expanded(
child: Center(
if (state.isChecking)
Expanded(
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const ProgressRing(),
const SizedBox(height: 12),
Text(state.lastScreenInfo)
],
children: [const ProgressRing(), const SizedBox(height: 12), Text(state.lastScreenInfo)],
),
))
else if (state.checkResult == null ||
state.checkResult!.isEmpty) ...[
Expanded(
child: Center(
),
)
else if (state.checkResult == null || state.checkResult!.isEmpty) ...[
Expanded(
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 12),
Text(S.current.doctor_info_scan_complete_no_issues,
maxLines: 1),
Text(S.current.doctor_info_scan_complete_no_issues, maxLines: 1),
const SizedBox(height: 64),
],
),
))
] else
...makeResult(context, state, model),
],
),
if (state.isFixing)
Container(
decoration: BoxDecoration(
color: Colors.black.withAlpha(150),
),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const ProgressRing(),
const SizedBox(height: 12),
Text(state.isFixingString.isNotEmpty
? state.isFixingString
: S.current.doctor_info_processing),
],
),
),
] else
...makeResult(context, state, model),
],
),
if (state.isFixing)
Container(
decoration: BoxDecoration(color: Colors.black.withAlpha(150)),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const ProgressRing(),
const SizedBox(height: 12),
Text(state.isFixingString.isNotEmpty ? state.isFixingString : S.current.doctor_info_processing),
],
),
),
Positioned(
bottom: 20,
right: 20,
child: makeRescueBanner(context),
)
],
));
),
Positioned(bottom: 20, right: 20, child: makeRescueBanner(context)),
],
),
);
}
Widget makeRescueBanner(BuildContext context) {
return GestureDetector(
onTap: () async {
await showToast(
context, S.current.doctor_info_game_rescue_service_note);
await showToast(context, S.current.doctor_info_game_rescue_service_note);
launchUrlString(
"https://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=-M4wEme_bCXbUGT4LFKLH0bAYTFt70Ad&authKey=vHVr0TNgRmKu%2BHwywoJV6EiLa7La2VX74Vkyixr05KA0H9TqB6qWlCdY%2B9jLQ4Ha&noverify=0&group_code=536454632");
"https://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=-M4wEme_bCXbUGT4LFKLH0bAYTFt70Ad&authKey=vHVr0TNgRmKu%2BHwywoJV6EiLa7La2VX74Vkyixr05KA0H9TqB6qWlCdY%2B9jLQ4Ha&noverify=0&group_code=536454632",
);
},
child: Tilt(
shadowConfig: const ShadowConfig(maxIntensity: .2),
borderRadius: BorderRadius.circular(12),
child: Container(
decoration: BoxDecoration(
color: FluentTheme.of(context).cardColor,
decoration: BoxDecoration(color: FluentTheme.of(context).cardColor),
child: Padding(
padding: const EdgeInsets.all(12),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Image.asset("assets/rescue.png", width: 24, height: 24),
const SizedBox(width: 12),
Text(S.current.doctor_info_need_help),
],
),
child: Padding(
padding: const EdgeInsets.all(12),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Image.asset("assets/rescue.png", width: 24, height: 24),
const SizedBox(width: 12),
Text(S.current.doctor_info_need_help),
],
),
)),
),
),
),
);
}
List<Widget> makeResult(BuildContext context, HomeGameDoctorState state,
HomeGameDoctorUIModel model) {
List<Widget> makeResult(BuildContext context, HomeGameDoctorState state, HomeGameDoctorUIModel model) {
return [
const SizedBox(height: 24),
Text(state.lastScreenInfo, maxLines: 1),
const SizedBox(height: 12),
Text(
S.current.doctor_info_tool_check_result_note,
style: TextStyle(color: Colors.red, fontSize: 16),
),
Text(S.current.doctor_info_tool_check_result_note, style: TextStyle(color: Colors.red, fontSize: 16)),
const SizedBox(height: 24),
ListView.builder(
itemCount: state.checkResult!.length,
@@ -176,43 +197,54 @@ class HomeGameDoctorUI extends HookConsumerWidget {
];
}
Widget makeResultItem(BuildContext context, MapEntry<String, String> item,
HomeGameDoctorState state, HomeGameDoctorUIModel model) {
Widget makeResultItem(
BuildContext context,
MapEntry<String, String> item,
HomeGameDoctorState state,
HomeGameDoctorUIModel model,
) {
final errorNames = {
"unSupport_system": MapEntry(S.current.doctor_info_result_unsupported_os,
S.current.doctor_info_result_upgrade_system(item.value)),
"no_live_path": MapEntry(S.current.doctor_info_result_missing_live_folder,
S.current.doctor_info_result_create_live_folder(item.value)),
"unSupport_system": MapEntry(
S.current.doctor_info_result_unsupported_os,
S.current.doctor_info_result_upgrade_system(item.value),
),
"no_live_path": MapEntry(
S.current.doctor_info_result_missing_live_folder,
S.current.doctor_info_result_create_live_folder(item.value),
),
"nvme_PhysicalBytes": MapEntry(
S.current.doctor_info_result_incompatible_nvme_device,
S.current.doctor_info_result_add_registry_value(item.value)),
S.current.doctor_info_result_incompatible_nvme_device,
S.current.doctor_info_result_add_registry_value(item.value),
),
"eac_file_miss": MapEntry(
S.current.doctor_info_result_missing_easyanticheat_files,
S.current.doctor_info_result_verify_files_with_rsi_launcher),
S.current.doctor_info_result_missing_easyanticheat_files,
S.current.doctor_info_result_verify_files_with_rsi_launcher,
),
"eac_not_install": MapEntry(
S.current.doctor_info_result_easyanticheat_not_installed,
S.current.doctor_info_result_install_easyanticheat),
"cn_user_name": MapEntry(S.current.doctor_info_result_chinese_username,
S.current.doctor_info_result_chinese_username_error),
S.current.doctor_info_result_easyanticheat_not_installed,
S.current.doctor_info_result_install_easyanticheat,
),
"cn_user_name": MapEntry(
S.current.doctor_info_result_chinese_username,
S.current.doctor_info_result_chinese_username_error,
),
"cn_install_path": MapEntry(
S.current.doctor_info_result_chinese_install_path,
S.current.doctor_info_result_chinese_install_path_error(item.value)),
"low_ram": MapEntry(S.current.doctor_info_result_low_physical_memory,
S.current.doctor_info_result_memory_requirement(item.value)),
S.current.doctor_info_result_chinese_install_path,
S.current.doctor_info_result_chinese_install_path_error(item.value),
),
"low_ram": MapEntry(
S.current.doctor_info_result_low_physical_memory,
S.current.doctor_info_result_memory_requirement(item.value),
),
};
bool isCheckedError = errorNames.containsKey(item.key);
if (isCheckedError) {
return Container(
decoration: BoxDecoration(
color: FluentTheme.of(context).cardColor,
),
decoration: BoxDecoration(color: FluentTheme.of(context).cardColor),
margin: const EdgeInsets.only(bottom: 12),
child: ListTile(
title: Text(
errorNames[item.key]?.key ?? "",
style: const TextStyle(fontSize: 18),
),
title: Text(errorNames[item.key]?.key ?? "", style: const TextStyle(fontSize: 18)),
subtitle: Padding(
padding: const EdgeInsets.only(top: 4, bottom: 4),
child: Column(
@@ -220,10 +252,9 @@ class HomeGameDoctorUI extends HookConsumerWidget {
const SizedBox(height: 4),
Text(
S.current.doctor_info_result_fix_suggestion(
errorNames[item.key]?.value ??
S.current.doctor_info_result_no_solution),
style: TextStyle(
fontSize: 14, color: Colors.white.withValues(alpha: .7)),
errorNames[item.key]?.value ?? S.current.doctor_info_result_no_solution,
),
style: TextStyle(fontSize: 14, color: Colors.white.withValues(alpha: .7)),
),
],
),
@@ -235,8 +266,7 @@ class HomeGameDoctorUI extends HookConsumerWidget {
await model.doFix(context, item);
},
child: Padding(
padding:
const EdgeInsets.only(left: 8, right: 8, top: 4, bottom: 4),
padding: const EdgeInsets.only(left: 8, right: 8, top: 4, bottom: 4),
child: Text(S.current.doctor_info_action_fix),
),
),
@@ -247,26 +277,16 @@ class HomeGameDoctorUI extends HookConsumerWidget {
final isSubTitleUrl = item.value.startsWith("https://");
return Container(
decoration: BoxDecoration(
color: FluentTheme.of(context).cardColor,
),
decoration: BoxDecoration(color: FluentTheme.of(context).cardColor),
margin: const EdgeInsets.only(bottom: 12),
child: ListTile(
title: Text(
item.key,
style: const TextStyle(fontSize: 18),
),
title: Text(item.key, style: const TextStyle(fontSize: 18)),
subtitle: isSubTitleUrl
? null
: Column(
children: [
const SizedBox(height: 4),
Text(
item.value,
style: TextStyle(
fontSize: 14,
color: Colors.white.withValues(alpha: .7)),
),
Text(item.value, style: TextStyle(fontSize: 14, color: Colors.white.withValues(alpha: .7))),
],
),
trailing: isSubTitleUrl
@@ -275,8 +295,7 @@ class HomeGameDoctorUI extends HookConsumerWidget {
launchUrlString(item.value);
},
child: Padding(
padding: const EdgeInsets.only(
left: 8, right: 8, top: 4, bottom: 4),
padding: const EdgeInsets.only(left: 8, right: 8, top: 4, bottom: 4),
child: Text(S.current.doctor_action_view_solution),
),
)
@@ -285,8 +304,7 @@ class HomeGameDoctorUI extends HookConsumerWidget {
);
}
Future<void> _onTapButton(
BuildContext context, String key, HomeUIModelState homeState) async {
Future<void> _onTapButton(BuildContext context, String key, HomeUIModelState homeState) async {
switch (key) {
case "rsi_log":
final path = await SCLoggerHelper.getLogFilePath();
@@ -294,8 +312,7 @@ class HomeGameDoctorUI extends HookConsumerWidget {
SystemHelper.openDir(path);
return;
case "game_log":
if (homeState.scInstalledPath == "not_install" ||
homeState.scInstalledPath == null) {
if (homeState.scInstalledPath == "not_install" || homeState.scInstalledPath == null) {
showToast(context, S.current.doctor_tip_title_select_game_directory);
return;
}
@@ -303,4 +320,37 @@ class HomeGameDoctorUI extends HookConsumerWidget {
return;
}
}
Future<void> _selectLogFile(BuildContext context, HomeGameDoctorUIModel model) async {
try {
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['log'],
dialogTitle: S.current.doctor_action_select_log_file,
);
if (result != null && result.files.isNotEmpty) {
final file = result.files.first;
// 在 web 平台,使用 bytes 读取文件内容
if (kIsWeb && file.bytes != null) {
final content = String.fromCharCodes(file.bytes!);
final lines = content.split('\n');
model.setCustomLogFile(file.name, lines);
if (!context.mounted) return;
// Web 平台选择文件后自动开始诊断
model.doCheck(context);
} else if (!kIsWeb && file.path != null) {
// 桌面平台使用路径读取
if (!kIsWeb) {
final logFile = File(file.path!);
final lines = await logFile.readAsLines();
model.setCustomLogFile(file.path!, lines);
}
}
}
} catch (e) {
dPrint("Error selecting log file: $e");
}
}
}

View File

@@ -2,6 +2,7 @@ import 'dart:convert';
import 'dart:io';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:starcitizen_doctor/common/helper/log_helper.dart';
@@ -23,6 +24,8 @@ abstract class HomeGameDoctorState with _$HomeGameDoctorState {
@Default("") String lastScreenInfo,
@Default("") String isFixingString,
List<MapEntry<String, String>>? checkResult,
String? customLogFilePath,
List<String>? customLogFileContent,
}) = _HomeGameDoctorState;
}
@@ -34,12 +37,16 @@ class HomeGameDoctorUIModel extends _$HomeGameDoctorUIModel {
return state;
}
void setCustomLogFile(String? filePath, List<String>? content) {
state = state.copyWith(customLogFilePath: filePath, customLogFileContent: content);
}
Future<void> doFix(
// ignore: avoid_build_context_in_providers
BuildContext context,
MapEntry<String, String> item) async {
final checkResult =
List<MapEntry<String, String>>.from(state.checkResult ?? []);
// ignore: avoid_build_context_in_providers
BuildContext context,
MapEntry<String, String> item,
) async {
final checkResult = List<MapEntry<String, String>>.from(state.checkResult ?? []);
state = state.copyWith(isFixing: true, isFixingString: "");
switch (item.key) {
case "unSupport_system":
@@ -49,13 +56,11 @@ class HomeGameDoctorUIModel extends _$HomeGameDoctorUIModel {
try {
await Directory(item.value).create(recursive: true);
if (!context.mounted) break;
showToast(
context, S.current.doctor_action_result_create_folder_success);
showToast(context, S.current.doctor_action_result_create_folder_success);
checkResult.remove(item);
state = state.copyWith(checkResult: checkResult);
} catch (e) {
showToast(context,
S.current.doctor_action_result_create_folder_fail(item.value, e));
showToast(context, S.current.doctor_action_result_create_folder_fail(item.value, e));
}
break;
case "nvme_PhysicalBytes":
@@ -71,8 +76,7 @@ class HomeGameDoctorUIModel extends _$HomeGameDoctorUIModel {
}
break;
case "eac_file_miss":
showToast(context,
S.current.doctor_info_result_verify_files_with_rsi_launcher);
showToast(context, S.current.doctor_info_result_verify_files_with_rsi_launcher);
break;
case "eac_not_install":
final eacJsonPath = "${item.value}\\Settings.json";
@@ -80,19 +84,16 @@ class HomeGameDoctorUIModel extends _$HomeGameDoctorUIModel {
final Map eacJson = json.decode(utf8.decode(eacJsonData));
final eacID = eacJson["productid"];
try {
var result = await Process.run(
"${item.value}\\EasyAntiCheat_EOS_Setup.exe", ["install", eacID]);
var result = await Process.run("${item.value}\\EasyAntiCheat_EOS_Setup.exe", ["install", eacID]);
dPrint("${item.value}\\EasyAntiCheat_EOS_Setup.exe install $eacID");
if (result.stderr == "") {
if (!context.mounted) break;
showToast(
context, S.current.doctor_action_result_game_start_success);
showToast(context, S.current.doctor_action_result_game_start_success);
checkResult.remove(item);
state = state.copyWith(checkResult: checkResult);
} else {
if (!context.mounted) break;
showToast(context,
S.current.doctor_action_result_fix_fail(result.stderr));
showToast(context, S.current.doctor_action_result_fix_fail(result.stderr));
}
} catch (e) {
if (!context.mounted) break;
@@ -102,8 +103,7 @@ class HomeGameDoctorUIModel extends _$HomeGameDoctorUIModel {
case "cn_user_name":
showToast(context, S.current.doctor_action_result_redirect_warning);
await Future.delayed(const Duration(milliseconds: 300));
launchUrlString(
"https://jingyan.baidu.com/article/59703552a318a08fc0074021.html");
launchUrlString("https://jingyan.baidu.com/article/59703552a318a08fc0074021.html");
break;
default:
showToast(context, S.current.doctor_action_result_issue_not_supported);
@@ -115,8 +115,7 @@ class HomeGameDoctorUIModel extends _$HomeGameDoctorUIModel {
// ignore: avoid_build_context_in_providers
Future<void> doCheck(BuildContext context) async {
if (state.isChecking) return;
state = state.copyWith(
isChecking: true, lastScreenInfo: S.current.doctor_action_analyzing);
state = state.copyWith(isChecking: true, lastScreenInfo: S.current.doctor_action_analyzing);
dPrint("-------- start docker check -----");
if (!context.mounted) return;
await _statCheck(context);
@@ -134,62 +133,73 @@ class HomeGameDoctorUIModel extends _$HomeGameDoctorUIModel {
// checkResult?.add(MapEntry("nvme_PhysicalBytes", "C"));
// checkResult?.add(MapEntry("no_live_path", ""));
await _checkPreInstall(context, scInstalledPath, checkResult);
if (!context.mounted) return;
await _checkEAC(context, scInstalledPath, checkResult);
if (!context.mounted) return;
// Web 平台仅检查日志文件,跳过系统环境和 EAC 检查
if (!kIsWeb) {
await _checkPreInstall(context, scInstalledPath, checkResult);
if (!context.mounted) return;
await _checkEAC(context, scInstalledPath, checkResult);
if (!context.mounted) return;
}
await _checkGameRunningLog(context, scInstalledPath, checkResult);
if (checkResult.isEmpty) {
final lastScreenInfo = S.current.doctor_action_result_analysis_no_issue;
state = state.copyWith(checkResult: null, lastScreenInfo: lastScreenInfo);
} else {
final lastScreenInfo = S.current
.doctor_action_result_analysis_issues_found(
checkResult.length.toString());
state = state.copyWith(
checkResult: checkResult, lastScreenInfo: lastScreenInfo);
final lastScreenInfo = S.current.doctor_action_result_analysis_issues_found(checkResult.length.toString());
state = state.copyWith(checkResult: checkResult, lastScreenInfo: lastScreenInfo);
}
if (scInstalledPath == "not_install" && (checkResult.isEmpty)) {
// Web 平台不显示 not_install 提示
if (!kIsWeb && scInstalledPath == "not_install" && (checkResult.isEmpty)) {
if (!context.mounted) return;
showToast(context, S.current.doctor_action_result_toast_scan_no_issue);
}
}
// ignore: avoid_build_context_in_providers
Future _checkGameRunningLog(BuildContext context, String scInstalledPath,
List<MapEntry<String, String>> checkResult) async {
if (scInstalledPath == "not_install") return;
Future _checkGameRunningLog(
BuildContext context,
String scInstalledPath,
List<MapEntry<String, String>> checkResult,
) async {
if (scInstalledPath == "not_install" && state.customLogFileContent == null) return;
final lastScreenInfo = S.current.doctor_action_tip_checking_game_log;
state = state.copyWith(lastScreenInfo: lastScreenInfo);
final logs = await SCLoggerHelper.getGameRunningLogs(scInstalledPath);
// 优先使用自定义 log 文件内容(用于 web 平台)
List<String>? logs;
if (state.customLogFileContent != null) {
logs = state.customLogFileContent;
} else {
logs = await SCLoggerHelper.getGameRunningLogs(scInstalledPath);
}
if (logs == null) return;
final info = SCLoggerHelper.getGameRunningLogInfo(logs);
if (info != null) {
if (info.key != "_") {
checkResult.add(MapEntry(
S.current.doctor_action_info_game_abnormal_exit(info.key),
info.value));
checkResult.add(MapEntry(S.current.doctor_action_info_game_abnormal_exit(info.key), info.value));
} else {
checkResult.add(MapEntry(
checkResult.add(
MapEntry(
S.current.doctor_action_info_game_abnormal_exit_unknown,
S.current.doctor_action_info_info_feedback(info.value)));
S.current.doctor_action_info_info_feedback(info.value),
),
);
}
}
}
// ignore: avoid_build_context_in_providers
Future _checkEAC(BuildContext context, String scInstalledPath,
List<MapEntry<String, String>> checkResult) async {
Future _checkEAC(BuildContext context, String scInstalledPath, List<MapEntry<String, String>> checkResult) async {
if (scInstalledPath == "not_install") return;
final lastScreenInfo = S.current.doctor_action_info_checking_eac;
state = state.copyWith(lastScreenInfo: lastScreenInfo);
final eacPath = "$scInstalledPath\\EasyAntiCheat";
final eacJsonPath = "$eacPath\\Settings.json";
if (!await Directory(eacPath).exists() ||
!await File(eacJsonPath).exists()) {
if (!await Directory(eacPath).exists() || !await File(eacJsonPath).exists()) {
checkResult.add(const MapEntry("eac_file_miss", ""));
return;
}
@@ -212,17 +222,18 @@ class HomeGameDoctorUIModel extends _$HomeGameDoctorUIModel {
final _cnExp = RegExp(r"[^\x00-\xff]");
// ignore: avoid_build_context_in_providers
Future _checkPreInstall(BuildContext context, String scInstalledPath,
List<MapEntry<String, String>> checkResult) async {
Future _checkPreInstall(
BuildContext context,
String scInstalledPath,
List<MapEntry<String, String>> checkResult,
) async {
final lastScreenInfo = S.current.doctor_action_info_checking_runtime;
state = state.copyWith(lastScreenInfo: lastScreenInfo);
if (!(Platform.operatingSystemVersion.contains("Windows 10") ||
Platform.operatingSystemVersion.contains("Windows 11"))) {
checkResult
.add(MapEntry("unSupport_system", Platform.operatingSystemVersion));
final lastScreenInfo = S.current.doctor_action_result_info_unsupported_os(
Platform.operatingSystemVersion);
checkResult.add(MapEntry("unSupport_system", Platform.operatingSystemVersion));
final lastScreenInfo = S.current.doctor_action_result_info_unsupported_os(Platform.operatingSystemVersion);
state = state.copyWith(lastScreenInfo: lastScreenInfo);
await showToast(context, lastScreenInfo);
}
@@ -236,12 +247,10 @@ class HomeGameDoctorUIModel extends _$HomeGameDoctorUIModel {
if (ramSize < 16) {
checkResult.add(MapEntry("low_ram", "$ramSize"));
}
state = state.copyWith(
lastScreenInfo: S.current.doctor_action_info_checking_install_info);
state = state.copyWith(lastScreenInfo: S.current.doctor_action_info_checking_install_info);
// 检查安装分区
try {
final listData = await SCLoggerHelper.getGameInstallPath(
await SCLoggerHelper.getLauncherLogList() ?? []);
final listData = await SCLoggerHelper.getGameInstallPath(await SCLoggerHelper.getLauncherLogList() ?? []);
final p = [];
final checkedPath = [];
for (var installPath in listData) {
@@ -265,10 +274,9 @@ class HomeGameDoctorUIModel extends _$HomeGameDoctorUIModel {
// call check
for (var element in p) {
var result = await Process.run('powershell', [
"(fsutil fsinfo sectorinfo $element: | Select-String 'PhysicalBytesPerSectorForPerformance').ToString().Split(':')[1].Trim()"
"(fsutil fsinfo sectorinfo $element: | Select-String 'PhysicalBytesPerSectorForPerformance').ToString().Split(':')[1].Trim()",
]);
dPrint(
"fsutil info sector info: ->>> ${result.stdout.toString().trim()}");
dPrint("fsutil info sector info: ->>> ${result.stdout.toString().trim()}");
if (result.stderr == "") {
final rs = result.stdout.toString().trim();
final physicalBytesPerSectorForPerformance = (int.tryParse(rs) ?? 0);

View File

@@ -14,7 +14,7 @@ T _$identity<T>(T value) => value;
/// @nodoc
mixin _$HomeGameDoctorState {
bool get isChecking; bool get isFixing; String get lastScreenInfo; String get isFixingString; List<MapEntry<String, String>>? get checkResult;
bool get isChecking; bool get isFixing; String get lastScreenInfo; String get isFixingString; List<MapEntry<String, String>>? get checkResult; String? get customLogFilePath; List<String>? get customLogFileContent;
/// Create a copy of HomeGameDoctorState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@@ -25,16 +25,16 @@ $HomeGameDoctorStateCopyWith<HomeGameDoctorState> get copyWith => _$HomeGameDoct
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is HomeGameDoctorState&&(identical(other.isChecking, isChecking) || other.isChecking == isChecking)&&(identical(other.isFixing, isFixing) || other.isFixing == isFixing)&&(identical(other.lastScreenInfo, lastScreenInfo) || other.lastScreenInfo == lastScreenInfo)&&(identical(other.isFixingString, isFixingString) || other.isFixingString == isFixingString)&&const DeepCollectionEquality().equals(other.checkResult, checkResult));
return identical(this, other) || (other.runtimeType == runtimeType&&other is HomeGameDoctorState&&(identical(other.isChecking, isChecking) || other.isChecking == isChecking)&&(identical(other.isFixing, isFixing) || other.isFixing == isFixing)&&(identical(other.lastScreenInfo, lastScreenInfo) || other.lastScreenInfo == lastScreenInfo)&&(identical(other.isFixingString, isFixingString) || other.isFixingString == isFixingString)&&const DeepCollectionEquality().equals(other.checkResult, checkResult)&&(identical(other.customLogFilePath, customLogFilePath) || other.customLogFilePath == customLogFilePath)&&const DeepCollectionEquality().equals(other.customLogFileContent, customLogFileContent));
}
@override
int get hashCode => Object.hash(runtimeType,isChecking,isFixing,lastScreenInfo,isFixingString,const DeepCollectionEquality().hash(checkResult));
int get hashCode => Object.hash(runtimeType,isChecking,isFixing,lastScreenInfo,isFixingString,const DeepCollectionEquality().hash(checkResult),customLogFilePath,const DeepCollectionEquality().hash(customLogFileContent));
@override
String toString() {
return 'HomeGameDoctorState(isChecking: $isChecking, isFixing: $isFixing, lastScreenInfo: $lastScreenInfo, isFixingString: $isFixingString, checkResult: $checkResult)';
return 'HomeGameDoctorState(isChecking: $isChecking, isFixing: $isFixing, lastScreenInfo: $lastScreenInfo, isFixingString: $isFixingString, checkResult: $checkResult, customLogFilePath: $customLogFilePath, customLogFileContent: $customLogFileContent)';
}
@@ -45,7 +45,7 @@ abstract mixin class $HomeGameDoctorStateCopyWith<$Res> {
factory $HomeGameDoctorStateCopyWith(HomeGameDoctorState value, $Res Function(HomeGameDoctorState) _then) = _$HomeGameDoctorStateCopyWithImpl;
@useResult
$Res call({
bool isChecking, bool isFixing, String lastScreenInfo, String isFixingString, List<MapEntry<String, String>>? checkResult
bool isChecking, bool isFixing, String lastScreenInfo, String isFixingString, List<MapEntry<String, String>>? checkResult, String? customLogFilePath, List<String>? customLogFileContent
});
@@ -62,14 +62,16 @@ class _$HomeGameDoctorStateCopyWithImpl<$Res>
/// Create a copy of HomeGameDoctorState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? isChecking = null,Object? isFixing = null,Object? lastScreenInfo = null,Object? isFixingString = null,Object? checkResult = freezed,}) {
@pragma('vm:prefer-inline') @override $Res call({Object? isChecking = null,Object? isFixing = null,Object? lastScreenInfo = null,Object? isFixingString = null,Object? checkResult = freezed,Object? customLogFilePath = freezed,Object? customLogFileContent = freezed,}) {
return _then(_self.copyWith(
isChecking: null == isChecking ? _self.isChecking : isChecking // ignore: cast_nullable_to_non_nullable
as bool,isFixing: null == isFixing ? _self.isFixing : isFixing // ignore: cast_nullable_to_non_nullable
as bool,lastScreenInfo: null == lastScreenInfo ? _self.lastScreenInfo : lastScreenInfo // ignore: cast_nullable_to_non_nullable
as String,isFixingString: null == isFixingString ? _self.isFixingString : isFixingString // ignore: cast_nullable_to_non_nullable
as String,checkResult: freezed == checkResult ? _self.checkResult : checkResult // ignore: cast_nullable_to_non_nullable
as List<MapEntry<String, String>>?,
as List<MapEntry<String, String>>?,customLogFilePath: freezed == customLogFilePath ? _self.customLogFilePath : customLogFilePath // ignore: cast_nullable_to_non_nullable
as String?,customLogFileContent: freezed == customLogFileContent ? _self.customLogFileContent : customLogFileContent // ignore: cast_nullable_to_non_nullable
as List<String>?,
));
}
@@ -154,10 +156,10 @@ return $default(_that);case _:
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( bool isChecking, bool isFixing, String lastScreenInfo, String isFixingString, List<MapEntry<String, String>>? checkResult)? $default,{required TResult orElse(),}) {final _that = this;
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( bool isChecking, bool isFixing, String lastScreenInfo, String isFixingString, List<MapEntry<String, String>>? checkResult, String? customLogFilePath, List<String>? customLogFileContent)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _HomeGameDoctorState() when $default != null:
return $default(_that.isChecking,_that.isFixing,_that.lastScreenInfo,_that.isFixingString,_that.checkResult);case _:
return $default(_that.isChecking,_that.isFixing,_that.lastScreenInfo,_that.isFixingString,_that.checkResult,_that.customLogFilePath,_that.customLogFileContent);case _:
return orElse();
}
@@ -175,10 +177,10 @@ return $default(_that.isChecking,_that.isFixing,_that.lastScreenInfo,_that.isFix
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( bool isChecking, bool isFixing, String lastScreenInfo, String isFixingString, List<MapEntry<String, String>>? checkResult) $default,) {final _that = this;
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( bool isChecking, bool isFixing, String lastScreenInfo, String isFixingString, List<MapEntry<String, String>>? checkResult, String? customLogFilePath, List<String>? customLogFileContent) $default,) {final _that = this;
switch (_that) {
case _HomeGameDoctorState():
return $default(_that.isChecking,_that.isFixing,_that.lastScreenInfo,_that.isFixingString,_that.checkResult);case _:
return $default(_that.isChecking,_that.isFixing,_that.lastScreenInfo,_that.isFixingString,_that.checkResult,_that.customLogFilePath,_that.customLogFileContent);case _:
throw StateError('Unexpected subclass');
}
@@ -195,10 +197,10 @@ return $default(_that.isChecking,_that.isFixing,_that.lastScreenInfo,_that.isFix
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( bool isChecking, bool isFixing, String lastScreenInfo, String isFixingString, List<MapEntry<String, String>>? checkResult)? $default,) {final _that = this;
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( bool isChecking, bool isFixing, String lastScreenInfo, String isFixingString, List<MapEntry<String, String>>? checkResult, String? customLogFilePath, List<String>? customLogFileContent)? $default,) {final _that = this;
switch (_that) {
case _HomeGameDoctorState() when $default != null:
return $default(_that.isChecking,_that.isFixing,_that.lastScreenInfo,_that.isFixingString,_that.checkResult);case _:
return $default(_that.isChecking,_that.isFixing,_that.lastScreenInfo,_that.isFixingString,_that.checkResult,_that.customLogFilePath,_that.customLogFileContent);case _:
return null;
}
@@ -210,7 +212,7 @@ return $default(_that.isChecking,_that.isFixing,_that.lastScreenInfo,_that.isFix
class _HomeGameDoctorState implements HomeGameDoctorState {
_HomeGameDoctorState({this.isChecking = false, this.isFixing = false, this.lastScreenInfo = "", this.isFixingString = "", final List<MapEntry<String, String>>? checkResult}): _checkResult = checkResult;
_HomeGameDoctorState({this.isChecking = false, this.isFixing = false, this.lastScreenInfo = "", this.isFixingString = "", final List<MapEntry<String, String>>? checkResult, this.customLogFilePath, final List<String>? customLogFileContent}): _checkResult = checkResult,_customLogFileContent = customLogFileContent;
@override@JsonKey() final bool isChecking;
@@ -226,6 +228,16 @@ class _HomeGameDoctorState implements HomeGameDoctorState {
return EqualUnmodifiableListView(value);
}
@override final String? customLogFilePath;
final List<String>? _customLogFileContent;
@override List<String>? get customLogFileContent {
final value = _customLogFileContent;
if (value == null) return null;
if (_customLogFileContent is EqualUnmodifiableListView) return _customLogFileContent;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(value);
}
/// Create a copy of HomeGameDoctorState
/// with the given fields replaced by the non-null parameter values.
@@ -237,16 +249,16 @@ _$HomeGameDoctorStateCopyWith<_HomeGameDoctorState> get copyWith => __$HomeGameD
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _HomeGameDoctorState&&(identical(other.isChecking, isChecking) || other.isChecking == isChecking)&&(identical(other.isFixing, isFixing) || other.isFixing == isFixing)&&(identical(other.lastScreenInfo, lastScreenInfo) || other.lastScreenInfo == lastScreenInfo)&&(identical(other.isFixingString, isFixingString) || other.isFixingString == isFixingString)&&const DeepCollectionEquality().equals(other._checkResult, _checkResult));
return identical(this, other) || (other.runtimeType == runtimeType&&other is _HomeGameDoctorState&&(identical(other.isChecking, isChecking) || other.isChecking == isChecking)&&(identical(other.isFixing, isFixing) || other.isFixing == isFixing)&&(identical(other.lastScreenInfo, lastScreenInfo) || other.lastScreenInfo == lastScreenInfo)&&(identical(other.isFixingString, isFixingString) || other.isFixingString == isFixingString)&&const DeepCollectionEquality().equals(other._checkResult, _checkResult)&&(identical(other.customLogFilePath, customLogFilePath) || other.customLogFilePath == customLogFilePath)&&const DeepCollectionEquality().equals(other._customLogFileContent, _customLogFileContent));
}
@override
int get hashCode => Object.hash(runtimeType,isChecking,isFixing,lastScreenInfo,isFixingString,const DeepCollectionEquality().hash(_checkResult));
int get hashCode => Object.hash(runtimeType,isChecking,isFixing,lastScreenInfo,isFixingString,const DeepCollectionEquality().hash(_checkResult),customLogFilePath,const DeepCollectionEquality().hash(_customLogFileContent));
@override
String toString() {
return 'HomeGameDoctorState(isChecking: $isChecking, isFixing: $isFixing, lastScreenInfo: $lastScreenInfo, isFixingString: $isFixingString, checkResult: $checkResult)';
return 'HomeGameDoctorState(isChecking: $isChecking, isFixing: $isFixing, lastScreenInfo: $lastScreenInfo, isFixingString: $isFixingString, checkResult: $checkResult, customLogFilePath: $customLogFilePath, customLogFileContent: $customLogFileContent)';
}
@@ -257,7 +269,7 @@ abstract mixin class _$HomeGameDoctorStateCopyWith<$Res> implements $HomeGameDoc
factory _$HomeGameDoctorStateCopyWith(_HomeGameDoctorState value, $Res Function(_HomeGameDoctorState) _then) = __$HomeGameDoctorStateCopyWithImpl;
@override @useResult
$Res call({
bool isChecking, bool isFixing, String lastScreenInfo, String isFixingString, List<MapEntry<String, String>>? checkResult
bool isChecking, bool isFixing, String lastScreenInfo, String isFixingString, List<MapEntry<String, String>>? checkResult, String? customLogFilePath, List<String>? customLogFileContent
});
@@ -274,14 +286,16 @@ class __$HomeGameDoctorStateCopyWithImpl<$Res>
/// Create a copy of HomeGameDoctorState
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? isChecking = null,Object? isFixing = null,Object? lastScreenInfo = null,Object? isFixingString = null,Object? checkResult = freezed,}) {
@override @pragma('vm:prefer-inline') $Res call({Object? isChecking = null,Object? isFixing = null,Object? lastScreenInfo = null,Object? isFixingString = null,Object? checkResult = freezed,Object? customLogFilePath = freezed,Object? customLogFileContent = freezed,}) {
return _then(_HomeGameDoctorState(
isChecking: null == isChecking ? _self.isChecking : isChecking // ignore: cast_nullable_to_non_nullable
as bool,isFixing: null == isFixing ? _self.isFixing : isFixing // ignore: cast_nullable_to_non_nullable
as bool,lastScreenInfo: null == lastScreenInfo ? _self.lastScreenInfo : lastScreenInfo // ignore: cast_nullable_to_non_nullable
as String,isFixingString: null == isFixingString ? _self.isFixingString : isFixingString // ignore: cast_nullable_to_non_nullable
as String,checkResult: freezed == checkResult ? _self._checkResult : checkResult // ignore: cast_nullable_to_non_nullable
as List<MapEntry<String, String>>?,
as List<MapEntry<String, String>>?,customLogFilePath: freezed == customLogFilePath ? _self.customLogFilePath : customLogFilePath // ignore: cast_nullable_to_non_nullable
as String?,customLogFileContent: freezed == customLogFileContent ? _self._customLogFileContent : customLogFileContent // ignore: cast_nullable_to_non_nullable
as List<String>?,
));
}

View File

@@ -42,7 +42,7 @@ final class HomeGameDoctorUIModelProvider
}
String _$homeGameDoctorUIModelHash() =>
r'7035b501860e9d8c3fdfb91370311760120af115';
r'8b969c4638fb07b8224dd60b3f04fa29742c4ae8';
abstract class _$HomeGameDoctorUIModel extends $Notifier<HomeGameDoctorState> {
HomeGameDoctorState build();

View File

@@ -11,7 +11,6 @@ import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:starcitizen_doctor/api/analytics.dart';
import 'package:starcitizen_doctor/generated/no_l10n_strings.dart';
import 'package:starcitizen_doctor/ui/guide/guide_ui.dart';
import 'package:starcitizen_doctor/ui/tools/tools_ui_model.dart';
import 'package:starcitizen_doctor/widgets/widgets.dart';
import 'package:url_launcher/url_launcher_string.dart';
@@ -32,7 +31,7 @@ class HomeUI extends HookConsumerWidget {
ref.watch(localizationUIModelProvider);
useEffect(() {
_checkGuide(context, model);
// _checkGuide(context, model);
return null;
}, const []);
@@ -118,25 +117,25 @@ class HomeUI extends HookConsumerWidget {
children: [
Text(S.current.home_install_location),
const SizedBox(width: 12),
Button(
onPressed: () async {
await context.push("/guide");
await model.reScanPath();
},
child: const Padding(padding: EdgeInsets.all(6), child: Icon(FluentIcons.settings)),
),
const SizedBox(width: 6),
// Button(
// onPressed: () async {
// await context.push("/guide");
// await model.reScanPath();
// },
// child: const Padding(padding: EdgeInsets.all(6), child: Icon(FluentIcons.settings)),
// ),
// const SizedBox(width: 6),
Expanded(
child: ComboBox<String>(
value: homeState.scInstalledPath,
isExpanded: true,
items: [
ComboBoxItem(value: "not_install", child: Text(S.current.home_not_installed_or_failed)),
for (final path in homeState.scInstallPaths)
ComboBoxItem(
value: path,
child: Row(children: [Text(path)]),
),
ComboBoxItem(value: "not_install", child: Text("您的电脑")),
// for (final path in homeState.scInstallPaths)
// ComboBoxItem(
// value: path,
// child: Row(children: [Text(path)]),
// ),
],
onChanged: model.onChangeInstallPath,
),
@@ -714,13 +713,8 @@ class HomeUI extends HookConsumerWidget {
}
Future<void> _onMenuTap(BuildContext context, String key, HomeUIModelState homeState, WidgetRef ref) async {
String gameInstallReqInfo = S.current.home_action_info_valid_install_location_required;
switch (key) {
case "localization":
if (homeState.scInstalledPath == "not_install") {
ToolsUIModel.rsiEnhance(context, showNotGameInstallMsg: true);
break;
}
final model = ref.watch(homeUIModelProvider.notifier);
model.checkLocalizationUpdate();
await showDialog(
@@ -731,14 +725,10 @@ class HomeUI extends HookConsumerWidget {
model.checkLocalizationUpdate(skipReload: true);
break;
case "performance":
if (homeState.scInstalledPath == "not_install") {
showToast(context, gameInstallReqInfo);
break;
}
context.push("/index/$key");
context.push("/$key");
break;
default:
context.push("/index/$key");
context.push("/$key");
}
}
@@ -771,42 +761,7 @@ class HomeUI extends HookConsumerWidget {
HomeUIModel model,
WidgetRef ref,
) async {
final localizationState = ref.read(localizationUIModelProvider);
if (localizationState.communityInputMethodLanguageData == null) {
showToast(context, S.current.input_method_feature_maintenance);
return;
}
if (localizationState.installedCommunityInputMethodSupportVersion == null) {
final userOK = await showConfirmDialogs(
context,
S.current.input_method_community_input_method_not_installed,
Text(S.current.input_method_install_community_input_method_prompt),
);
if (userOK) {
if (!context.mounted) return;
() async {
await _onMenuTap(context, 'localization', homeState, ref);
final localizationState = ref.read(localizationUIModelProvider);
if (localizationState.installedCommunityInputMethodSupportVersion != null) {
await Future.delayed(Duration(milliseconds: 300));
if (!context.mounted) return;
await _goInputMethod(context, model);
return;
}
}();
await Future.delayed(Duration(milliseconds: 300));
final localizationModel = ref.read(localizationUIModelProvider.notifier);
if (!context.mounted) return;
localizationModel.checkReinstall(context);
}
return;
}
await _goInputMethod(context, model);
}
Future<void> _goInputMethod(BuildContext context, HomeUIModel model) async {
await showDialog(context: context, builder: (context) => const InputMethodDialogUI());
showToast(context, "请使用完整版体验");
}
}

View File

@@ -120,7 +120,12 @@ class HomeUIModel extends _$HomeUIModel {
for (var node in h.body!.nodes) {
if (node is html_dom.Element) {
if (node.localName == "img") {
return node.attributes["src"]?.trim() ?? "";
final image = node.attributes["src"]?.trim() ?? "";
var updatedImage = image.replaceAllMapped(
RegExp(r'http(s)?://i(\d+)\.hdslb\.com/bfs/'),
(match) => 'https://web-proxy.scbox.xkeyc.cn/bfs${match[2]}/bfs/',
);
return updatedImage;
}
}
}

View File

@@ -41,7 +41,7 @@ final class HomeUIModelProvider
}
}
String _$homeUIModelHash() => r'9dc8191f358c2d8e21ed931b3755e08ce394558e';
String _$homeUIModelHash() => r'8ceec2769c0cbc2df62f152224e793a3d10729a8';
abstract class _$HomeUIModel extends $Notifier<HomeUIModelState> {
HomeUIModelState build();

View File

@@ -47,7 +47,7 @@ final class AdvancedLocalizationUIModelProvider
}
String _$advancedLocalizationUIModelHash() =>
r'2f890c854bc56e506c441acabc2014438a163617';
r'c7cca8935ac7df2281e83297b11b6b82d94f7a59';
abstract class _$AdvancedLocalizationUIModel
extends $Notifier<AdvancedLocalizationUIState> {

View File

@@ -30,13 +30,9 @@ class LocalizationDialogUI extends HookConsumerWidget {
return ContentDialog(
title: makeTitle(context, model, state),
constraints: BoxConstraints(
maxWidth: MediaQuery
.of(context)
.size
.width * .7, minHeight: MediaQuery
.of(context)
.size
.height * .9),
maxWidth: MediaQuery.of(context).size.width * .7,
minHeight: MediaQuery.of(context).size.height * .9,
),
content: Padding(
padding: const EdgeInsets.only(left: 12, right: 12, top: 12),
child: SingleChildScrollView(
@@ -44,132 +40,57 @@ class LocalizationDialogUI extends HookConsumerWidget {
children: [
AnimatedSize(
duration: const Duration(milliseconds: 130),
child: state.patchStatus?.key == true &&
state.patchStatus?.value == S.current.home_action_info_game_built_in
child:
state.patchStatus?.key == true &&
state.patchStatus?.value == S.current.home_action_info_game_built_in
? Padding(
padding: const EdgeInsets.only(bottom: 12),
child: InfoBar(
title: Text(S.current.home_action_info_warning),
content: Text(S.current.localization_info_machine_translation_warning),
severity: InfoBarSeverity.info,
style: InfoBarThemeData(decoration: (severity) {
return const BoxDecoration(color: Color.fromRGBO(155, 7, 7, 1.0));
}, iconColor: (severity) {
return Colors.white;
}),
),
)
: SizedBox(
width: MediaQuery
.of(context)
.size
.width,
),
padding: const EdgeInsets.only(bottom: 12),
child: InfoBar(
title: Text(S.current.home_action_info_warning),
content: Text(S.current.localization_info_machine_translation_warning),
severity: InfoBarSeverity.info,
style: InfoBarThemeData(
decoration: (severity) {
return const BoxDecoration(color: Color.fromRGBO(155, 7, 7, 1.0));
},
iconColor: (severity) {
return Colors.white;
},
),
),
)
: SizedBox(width: MediaQuery.of(context).size.width),
),
makeToolsListContainer(context, model, state),
makeListContainer(
S.current.localization_info_translation,
[
if (state.patchStatus == null)
makeLoading(context)
else
...[
const SizedBox(height: 6),
Row(
children: [
Center(
child: Text(S.current.localization_info_enabled(
LocalizationUIModel.languageSupport[state.selectedLanguage] ?? "")),
),
const Spacer(),
ToggleSwitch(
checked: state.patchStatus?.key == true,
onChanged: model.updateLangCfg,
)
],
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: Row(
children: [
Text(S.current.localization_info_installed_version(
"${state.patchStatus?.value ?? ""} ${(state.isInstalledAdvanced ?? false) ? S
.current.home_localization_msg_version_advanced : ""}")),
SizedBox(width: 24),
if (state.installedCommunityInputMethodSupportVersion != null)
Text(
S.current.input_method_community_input_method_support_version(
state.installedCommunityInputMethodSupportVersion ?? "?"),
)
],
),
),
if (state.patchStatus?.value != S.current.home_action_info_game_built_in)
Row(
children: [
Button(
onPressed: model.goFeedback,
child: Padding(
padding: const EdgeInsets.all(4),
child: Row(
children: [
const Icon(FluentIcons.feedback),
const SizedBox(width: 6),
Text(S.current.localization_action_translation_feedback),
],
),
)),
const SizedBox(width: 16),
Button(
onPressed: model.doDelIniFile(),
child: Padding(
padding: const EdgeInsets.all(4),
child: Row(
children: [
const Icon(FluentIcons.delete),
const SizedBox(width: 6),
Text(S.current.localization_action_uninstall_translation),
],
),
)),
],
),
],
),
const SizedBox(height: 12),
Container(
color: Colors.white.withValues(alpha: .1),
height: 1,
),
const SizedBox(height: 12),
if (state.apiLocalizationData == null)
makeLoading(context)
else
if (state.apiLocalizationData!.isEmpty)
Center(
child: Text(
S.current.localization_info_no_translation_available,
style: TextStyle(fontSize: 13, color: Colors.white.withValues(alpha: .8)),
),
)
else
AlignedGridView.count(
crossAxisCount: 2,
crossAxisSpacing: 12,
mainAxisSpacing: 12,
itemBuilder: (BuildContext context, int index) {
final item = state.apiLocalizationData!.entries.elementAt(index);
return makeRemoteList(context, model, item, state, index);
},
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: state.apiLocalizationData?.length ?? 0,
)
],
],
context),
makeListContainer(S.current.localization_info_translation, [
if (state.patchStatus == null)
makeLoading(context)
else ...[
const SizedBox(height: 6),
if (state.apiLocalizationData == null)
makeLoading(context)
else if (state.apiLocalizationData!.isEmpty)
Center(
child: Text(
S.current.localization_info_no_translation_available,
style: TextStyle(fontSize: 13, color: Colors.white.withValues(alpha: .8)),
),
)
else
AlignedGridView.count(
crossAxisCount: 2,
crossAxisSpacing: 12,
mainAxisSpacing: 12,
itemBuilder: (BuildContext context, int index) {
final item = state.apiLocalizationData!.entries.elementAt(index);
return makeRemoteList(context, model, item, state, index);
},
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: state.apiLocalizationData?.length ?? 0,
),
],
], context),
],
),
),
@@ -177,8 +98,13 @@ class LocalizationDialogUI extends HookConsumerWidget {
);
}
Widget makeRemoteList(BuildContext context, LocalizationUIModel model, MapEntry<String, ScLocalizationData> item,
LocalizationUIState state, int index) {
Widget makeRemoteList(
BuildContext context,
LocalizationUIModel model,
MapEntry<String, ScLocalizationData> item,
LocalizationUIState state,
int index,
) {
final isWorking = state.workingVersion.isNotEmpty;
final isMineWorking = state.workingVersion == item.key;
final isInstalled = state.patchStatus?.value == item.key;
@@ -207,10 +133,7 @@ class LocalizationDialogUI extends HookConsumerWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"${item.value.info}",
style: const TextStyle(fontSize: 19),
),
Text("${item.value.info}", style: const TextStyle(fontSize: 19)),
const SizedBox(height: 4),
Text(
S.current.localization_info_version_number(item.value.versionName ?? ""),
@@ -230,40 +153,30 @@ class LocalizationDialogUI extends HookConsumerWidget {
),
),
if (isMineWorking)
const Padding(
padding: EdgeInsets.only(right: 12),
child: ProgressRing(),
)
else
...[
Icon(
isInstalled
? FluentIcons.check_mark
: isItemEnabled
? FluentIcons.download
: FluentIcons.disable_updates,
color: Colors.white.withValues(alpha: .8),
size: 18,
),
const SizedBox(width: 6),
Text(
isInstalled
? S.current.localization_info_installed
: (isItemEnabled
? S.current.localization_action_install
: S.current.localization_info_unavailable),
style: TextStyle(
color: Colors.white.withValues(alpha: .8),
),
),
const SizedBox(width: 6),
if ((!isInstalled) && isItemEnabled)
Icon(
FluentIcons.chevron_right,
size: 14,
color: Colors.white.withValues(alpha: .6),
)
]
const Padding(padding: EdgeInsets.only(right: 12), child: ProgressRing())
else ...[
Icon(
isInstalled
? FluentIcons.check_mark
: isItemEnabled
? FluentIcons.download
: FluentIcons.disable_updates,
color: Colors.white.withValues(alpha: .8),
size: 18,
),
const SizedBox(width: 6),
Text(
isInstalled
? S.current.localization_info_installed
: (isItemEnabled
? S.current.localization_action_install
: S.current.localization_info_unavailable),
style: TextStyle(color: Colors.white.withValues(alpha: .8)),
),
const SizedBox(width: 6),
if ((!isInstalled) && isItemEnabled)
Icon(FluentIcons.chevron_right, size: 14, color: Colors.white.withValues(alpha: .6)),
],
],
),
if (item.value.note != null) ...[
@@ -272,10 +185,7 @@ class LocalizationDialogUI extends HookConsumerWidget {
"${item.value.note}",
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: Colors.white.withValues(alpha: .4),
fontSize: 13,
),
style: TextStyle(color: Colors.white.withValues(alpha: .4), fontSize: 13),
),
],
],
@@ -286,16 +196,20 @@ class LocalizationDialogUI extends HookConsumerWidget {
);
}
Widget makeListContainer(String title, List<Widget> children, BuildContext context,
{List<Widget> actions = const [], bool gridViewMode = false, int gridViewCrossAxisCount = 2}) {
Widget makeListContainer(
String title,
List<Widget> children,
BuildContext context, {
List<Widget> actions = const [],
bool gridViewMode = false,
int gridViewCrossAxisCount = 2,
}) {
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: AnimatedSize(
duration: const Duration(milliseconds: 130),
child: Container(
decoration: BoxDecoration(color: FluentTheme
.of(context)
.cardColor, borderRadius: BorderRadius.circular(7)),
decoration: BoxDecoration(color: FluentTheme.of(context).cardColor, borderRadius: BorderRadius.circular(7)),
child: Padding(
padding: const EdgeInsets.only(top: 12, bottom: 12, left: 24, right: 24),
child: Column(
@@ -303,21 +217,13 @@ class LocalizationDialogUI extends HookConsumerWidget {
children: [
Row(
children: [
Text(
title,
style: const TextStyle(fontSize: 22),
),
Text(title, style: const TextStyle(fontSize: 22)),
const Spacer(),
if (actions.isNotEmpty) ...actions,
],
),
const SizedBox(
height: 6,
),
Container(
color: Colors.white.withValues(alpha: .1),
height: 1,
),
const SizedBox(height: 6),
Container(color: Colors.white.withValues(alpha: .1), height: 1),
const SizedBox(height: 12),
if (gridViewMode)
AlignedGridView.count(
@@ -332,7 +238,7 @@ class LocalizationDialogUI extends HookConsumerWidget {
itemCount: children.length,
)
else
...children
...children,
],
),
),
@@ -344,55 +250,54 @@ class LocalizationDialogUI extends HookConsumerWidget {
Widget makeTitle(BuildContext context, LocalizationUIModel model, LocalizationUIState state) {
return Row(
children: [
IconButton(
icon: const Icon(
FluentIcons.back,
size: 22,
),
onPressed: model.onBack(context)),
IconButton(icon: const Icon(FluentIcons.back, size: 22), onPressed: model.onBack(context)),
const SizedBox(width: 12),
Text(S.current.home_action_localization_management),
const SizedBox(width: 24),
Text(
"${model.getScInstallPath()}",
style: const TextStyle(fontSize: 13),
),
const Spacer(),
SizedBox(
height: 36,
child: Row(
children: [
Text(
S.current.localization_info_language,
style: const TextStyle(fontSize: 16),
),
Text(S.current.localization_info_language, style: const TextStyle(fontSize: 16)),
const SizedBox(width: 12),
ComboBox<String>(
value: state.selectedLanguage,
items: [
for (final lang in LocalizationUIModel.languageSupport.entries)
ComboBoxItem(
value: lang.key,
child: Text(lang.value),
)
ComboBoxItem(value: lang.key, child: Text(lang.value)),
],
onChanged: state.workingVersion.isNotEmpty
? null
: (v) {
if (v == null) return;
model.selectLang(v);
},
)
if (v == null) return;
model.selectLang(v);
},
),
const SizedBox(width: 12),
const Text("频道选择", style: TextStyle(fontSize: 16)),
const SizedBox(width: 12),
ComboBox<String>(
value: state.selectedChannel,
items: const [
ComboBoxItem(value: "LIVE", child: Text("LIVE")),
ComboBoxItem(value: "PTU", child: Text("PTU")),
],
onChanged: state.workingVersion.isNotEmpty
? null
: (v) {
if (v == null) return;
model.selectChannel(v);
},
),
],
),
),
const SizedBox(width: 12),
Button(
onPressed: model.doRefresh(),
child: const Padding(
padding: EdgeInsets.all(6),
child: Icon(FluentIcons.refresh),
)),
onPressed: model.doRefresh(),
child: const Padding(padding: EdgeInsets.all(6), child: Icon(FluentIcons.refresh)),
),
],
);
}
@@ -400,85 +305,77 @@ class LocalizationDialogUI extends HookConsumerWidget {
Widget makeToolsListContainer(BuildContext context, LocalizationUIModel model, LocalizationUIState state) {
final toolsMenu = {
"launcher_mod": (
const Icon(FluentIcons.c_plus_plus, size: 24),
(S.current.home_localization_action_rsi_launcher_localization),
),
"advanced": (
const Icon(FluentIcons.queue_advanced, size: 24),
(S.current.home_localization_action_advanced),
const Icon(FluentIcons.c_plus_plus, size: 24),
(S.current.home_localization_action_rsi_launcher_localization),
),
"advanced": (const Icon(FluentIcons.queue_advanced, size: 24), (S.current.home_localization_action_advanced)),
"custom_files": (
const Icon(FluentIcons.custom_activity, size: 24),
(S.current.home_localization_action_install_customize),
const Icon(FluentIcons.custom_activity, size: 24),
(S.current.home_localization_action_install_customize),
),
};
final enableTap = state.workingVersion.isEmpty;
return makeListContainer(
S.current.home_localization_title_localization_tools,
[
for (final item in toolsMenu.entries)
Tilt(
disable: !enableTap,
shadowConfig: const ShadowConfig(maxIntensity: .3),
borderRadius: BorderRadius.circular(7),
child: GestureDetector(
onTap: enableTap
? () async {
switch (item.key) {
case "launcher_mod":
ToolsUIModel.rsiEnhance(context);
break;
case "advanced":
context.push("/index/advanced_localization");
break;
case "custom_files":
final sb = await showDialog(
context: context,
builder: (BuildContext context) => const LocalizationFromFileDialogUI(),
);
if (sb is (StringBuffer, bool)) {
if (!context.mounted) return;
await model.installFormString(
sb.$1,
S.current.localization_info_custom_files,
isEnableCommunityInputMethod: sb.$2,
context: context,
);
S.current.home_localization_title_localization_tools,
[
for (final item in toolsMenu.entries)
Tilt(
disable: !enableTap,
shadowConfig: const ShadowConfig(maxIntensity: .3),
borderRadius: BorderRadius.circular(7),
child: GestureDetector(
onTap: enableTap
? () async {
switch (item.key) {
case "launcher_mod":
ToolsUIModel.rsiEnhance(context);
break;
case "advanced":
context.push("/advanced_localization");
break;
case "custom_files":
final sb = await showDialog(
context: context,
builder: (BuildContext context) => const LocalizationFromFileDialogUI(),
);
if (sb is (StringBuffer, bool)) {
if (!context.mounted) return;
await model.installFormString(
sb.$1,
S.current.localization_info_custom_files,
isEnableCommunityInputMethod: sb.$2,
context: context,
);
}
break;
}
break;
}
}
: null,
child: Container(
decoration: BoxDecoration(
color: FluentTheme
.of(context)
.cardColor,
borderRadius: BorderRadius.circular(7),
),
padding: const EdgeInsets.all(12),
child: Row(
children: [
item.value.$1,
const SizedBox(width: 12),
Text(item.value.$2),
const SizedBox(width: 12),
const Spacer(),
Icon(
FluentIcons.chevron_right,
size: 14,
color: Colors.white.withValues(alpha: .6),
)
],
),
}
: null,
child: Container(
decoration: BoxDecoration(
color: FluentTheme.of(context).cardColor,
borderRadius: BorderRadius.circular(7),
),
padding: const EdgeInsets.all(12),
child: Row(
children: [
item.value.$1,
const SizedBox(width: 12),
Text(item.value.$2),
const SizedBox(width: 12),
const Spacer(),
Icon(FluentIcons.chevron_right, size: 14, color: Colors.white.withValues(alpha: .6)),
],
),
),
),
],
context,
gridViewMode: true,
gridViewCrossAxisCount: 3);
),
],
context,
gridViewMode: true,
gridViewCrossAxisCount: 3,
);
}
}

View File

@@ -2,10 +2,11 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:archive/archive_io.dart';
import 'package:archive/archive.dart';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/foundation.dart' show kIsWeb, compute;
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:hive_ce/hive.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
@@ -23,8 +24,8 @@ import 'package:starcitizen_doctor/ui/home/home_ui_model.dart';
import 'package:starcitizen_doctor/ui/tools/dialogs/vehicle_sorting_dialog_ui.dart';
import 'package:starcitizen_doctor/widgets/widgets.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:starcitizen_doctor/common/rust/api/win32_api.dart' as win32;
import 'dart:js_interop';
import 'package:web/web.dart' as web;
part 'localization_ui_model.g.dart';
@@ -34,6 +35,7 @@ part 'localization_ui_model.freezed.dart';
abstract class LocalizationUIState with _$LocalizationUIState {
factory LocalizationUIState({
String? selectedLanguage,
@Default("LIVE") String selectedChannel,
String? installedCommunityInputMethodSupportVersion,
InputMethodApiLanguageData? communityInputMethodLanguageData,
Map<String, ScLocalizationData>? apiLocalizationData,
@@ -46,10 +48,7 @@ abstract class LocalizationUIState with _$LocalizationUIState {
@riverpod
class LocalizationUIModel extends _$LocalizationUIModel {
static const languageSupport = {
"chinese_(simplified)": NoL10n.langZHS,
"chinese_(traditional)": NoL10n.langZHT,
};
static const languageSupport = {"chinese_(simplified)": NoL10n.langZHS, "chinese_(traditional)": NoL10n.langZHT};
Directory get _downloadDir => Directory("${appGlobalState.applicationSupportDir}\\Localizations");
@@ -71,7 +70,7 @@ class LocalizationUIModel extends _$LocalizationUIModel {
}
Future<void> _init() async {
if (_scInstallPath == "not_install") {
if (!kIsWeb && _scInstallPath == "not_install") {
return;
}
ref.onDispose(() {
@@ -108,7 +107,16 @@ class LocalizationUIModel extends _$LocalizationUIModel {
Future<void> _loadData() async {
_allVersionLocalizationData.clear();
await _updateStatus();
if (!kIsWeb) {
await _updateStatus();
} else {
await Future.delayed(Duration(milliseconds: 100));
state = state.copyWith(
patchStatus: MapEntry(false, S.current.home_action_info_game_built_in),
isInstalledAdvanced: false,
installedCommunityInputMethodSupportVersion: null,
);
}
await _loadCommunityInputMethodData();
for (var lang in languageSupport.keys) {
final l = await Api.getScLocalizationData(lang).unwrap();
@@ -116,7 +124,7 @@ class LocalizationUIModel extends _$LocalizationUIModel {
if (lang == state.selectedLanguage) {
final apiLocalizationData = <String, ScLocalizationData>{};
for (var element in l) {
final isPTU = !_scInstallPath.contains("LIVE");
final isPTU = !state.selectedChannel.contains("LIVE");
if (isPTU && element.gameChannel == "PTU") {
apiLocalizationData[element.versionName ?? ""] = element;
} else if (!isPTU && element.gameChannel == "PU") {
@@ -135,14 +143,20 @@ class LocalizationUIModel extends _$LocalizationUIModel {
}
void checkUserCfg(BuildContext context) async {
// Web 版本不支持此功能
if (kIsWeb) return;
final userCfgFile = File("$_scInstallPath\\USER.cfg");
if (await userCfgFile.exists()) {
final cfgString = await userCfgFile.readAsString();
if (cfgString.contains("g_language") && !cfgString.contains("g_language=${state.selectedLanguage}")) {
if (!context.mounted) return;
final ok = await showConfirmDialogs(context, S.current.localization_info_remove_incompatible_translation_params,
Text(S.current.localization_info_incompatible_translation_params_warning),
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * .35));
final ok = await showConfirmDialogs(
context,
S.current.localization_info_remove_incompatible_translation_params,
Text(S.current.localization_info_incompatible_translation_params_warning),
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * .35),
);
if (ok == true) {
var finalString = "";
for (var item in cfgString.split("\n")) {
@@ -160,6 +174,9 @@ class LocalizationUIModel extends _$LocalizationUIModel {
}
Future<void> updateLangCfg(bool enable) async {
// Web 版本不支持此功能
if (kIsWeb) return;
final selectedLanguage = state.selectedLanguage!;
final status = await _getLangCfgEnableLang(lang: selectedLanguage);
final exists = await _cfgFile.exists();
@@ -216,7 +233,25 @@ class LocalizationUIModel extends _$LocalizationUIModel {
launchUrlString(URLConf.feedbackUrl);
}
Future<String> genLangCfg() async {
final selectedLanguage = state.selectedLanguage!;
StringBuffer newStr = StringBuffer();
if (!newStr.toString().contains("sys_languages=$selectedLanguage")) {
newStr.writeln("sys_languages=$selectedLanguage");
}
if (!newStr.toString().contains("g_language=$selectedLanguage")) {
newStr.writeln("g_language=$selectedLanguage");
}
if (!newStr.toString().contains("g_languageAudio")) {
newStr.writeln("g_languageAudio=english");
}
return newStr.toString();
}
VoidCallback? doDelIniFile() {
// Web 版本不支持此功能
if (kIsWeb) return null;
return () async {
final iniFile = File("${_scDataDir.absolute.path}\\Localization\\${state.selectedLanguage}\\global.ini");
if (await iniFile.exists()) await iniFile.delete();
@@ -238,7 +273,7 @@ class LocalizationUIModel extends _$LocalizationUIModel {
BuildContext? context,
}) async {
dPrint("LocalizationUIModel -> installFormString $versionName");
final iniFile = File("${_scDataDir.absolute.path}\\Localization\\${state.selectedLanguage}\\global.ini");
if (versionName.isNotEmpty) {
if (!globalIni.toString().endsWith("\n")) {
globalIni.write("\n");
@@ -246,7 +281,7 @@ class LocalizationUIModel extends _$LocalizationUIModel {
String? communityInputMethodVersion;
String? communityInputMethodSupportData;
if (isEnableCommunityInputMethod) {
if (isEnableCommunityInputMethod && !kIsWeb) {
final data = state.communityInputMethodLanguageData;
if (data != null) {
communityInputMethodVersion = data.version;
@@ -258,8 +293,9 @@ class LocalizationUIModel extends _$LocalizationUIModel {
}
if (communityInputMethodVersion != null) {
globalIni
.write("_starcitizen_doctor_localization_community_input_method_version=$communityInputMethodVersion\n");
globalIni.write(
"_starcitizen_doctor_localization_community_input_method_version=$communityInputMethodVersion\n",
);
}
if (communityInputMethodSupportData != null) {
for (var line in communityInputMethodSupportData.split("\n")) {
@@ -274,17 +310,29 @@ class LocalizationUIModel extends _$LocalizationUIModel {
var iniStringData = globalIni.toString().trim();
// 载具排序对话框 - 在生成最终文件前执行
if ((context?.mounted ?? false) && isEnableVehicleSorting) {
if (!context!.mounted) return;
final iniStringDataVN = ValueNotifier(iniStringData);
final ok = await showConfirmDialogs(context, S.current.tools_vehicle_sorting_title, VehicleSortingDialogUi(iniStringData: iniStringDataVN),constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * .75,
));
final ok = await showConfirmDialogs(
context,
S.current.tools_vehicle_sorting_title,
VehicleSortingDialogUi(iniStringData: iniStringDataVN),
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * .75),
);
if (ok) {
iniStringData = iniStringDataVN.value;
}
}
// Web 版本生成下载文件
if (kIsWeb) {
await _generateAndDownloadWebFile(iniStringData, versionName);
return;
}
final iniFile = File("${_scDataDir.absolute.path}\\Localization\\${state.selectedLanguage}\\global.ini");
/// write ini
if (await iniFile.exists()) {
await iniFile.delete();
@@ -295,6 +343,28 @@ class LocalizationUIModel extends _$LocalizationUIModel {
await _updateStatus();
}
Future<void> _generateAndDownloadWebFile(String iniStringData, String versionName) async {
final selectedLanguage = state.selectedLanguage!;
final iniFileString = "\uFEFF$iniStringData";
final cfg = await genLangCfg();
final archive = Archive();
archive.addFile(
ArchiveFile("data/Localization/$selectedLanguage/global.ini", iniFileString.length, utf8.encode(iniFileString)),
);
archive.addFile(ArchiveFile("data/system.cfg", cfg.length, utf8.encode(cfg)));
final zip = await compute(_encodeZipFile, archive);
if (zip == null) return;
final blob = Blob.fromBytes(zip, opt: {"type": "application/zip"});
final url = web.URL.createObjectURL(blob);
await Future.delayed(const Duration(seconds: 1));
jsDownloadBlobFile(url, "Localization_$versionName.zip");
}
List<int>? _encodeZipFile(Archive archive) {
final zip = ZipEncoder().encode(archive);
return zip;
}
Future<Map<String, String>?> getCommunityInputMethodSupportData() async {
final iniPath = "${_scDataDir.absolute.path}\\Localization\\${state.selectedLanguage}\\global.ini";
final iniFile = File(iniPath);
@@ -348,10 +418,41 @@ class LocalizationUIModel extends _$LocalizationUIModel {
return ("", "");
}
Future? doRemoteInstall(BuildContext context, ScLocalizationData value,
{bool isEnableCommunityInputMethod = false, bool isEnableVehicleSorting = false}) async {
Future? doRemoteInstall(
BuildContext context,
ScLocalizationData value, {
bool isEnableCommunityInputMethod = false,
bool isEnableVehicleSorting = false,
}) async {
AnalyticsApi.touch("install_localization");
// Web 版本直接下载并生成 ZIP
if (kIsWeb) {
try {
state = state.copyWith(workingVersion: value.versionName!);
final data = await downloadLocalizationFileForWeb(value);
await Future.delayed(const Duration(milliseconds: 300));
// check file
final globalIni = await compute(readArchiveFromBytes, data);
if (globalIni.isEmpty) {
throw S.current.localization_info_corrupted_file;
}
if (!context.mounted) return;
await installFormString(
globalIni,
value.versionName ?? "",
isEnableCommunityInputMethod: isEnableCommunityInputMethod,
isEnableVehicleSorting: isEnableVehicleSorting,
context: context,
);
} catch (e) {
if (!context.mounted) return;
await showToast(context, S.current.localization_info_installation_error(e));
}
state = state.copyWith(workingVersion: "");
return;
}
final savePath = File("${_downloadDir.absolute.path}\\${value.versionName}.sclang");
try {
state = state.copyWith(workingVersion: value.versionName!);
@@ -385,7 +486,8 @@ class LocalizationUIModel extends _$LocalizationUIModel {
}
Future<String> downloadOrGetCachedCommunityInputMethodSupportFile(
InputMethodApiLanguageData communityInputMethodData) async {
InputMethodApiLanguageData communityInputMethodData,
) async {
final lang = state.selectedLanguage ?? "_";
final box = await Hive.openBox("community_input_method_data");
final cachedVersion = box.get("${lang}_version");
@@ -410,6 +512,18 @@ class LocalizationUIModel extends _$LocalizationUIModel {
}
}
// Web 版本下载方法,返回字节数据
Future<Uint8List> downloadLocalizationFileForWeb(ScLocalizationData value) async {
dPrint("downloading file for web");
final downloadUrl = "${URLConf.gitlabLocalizationUrl}/archive/${value.versionName}.tar.gz";
final r = await RSHttp.get(downloadUrl);
if (r.statusCode == 200 && r.data != null) {
return r.data!;
} else {
throw "statusCode Error : ${r.statusCode}";
}
}
static StringBuffer readArchive(String savePath) {
final inputStream = InputFileStream(savePath);
final output = GZipDecoder().decodeBytes(inputStream.toUint8List());
@@ -429,6 +543,25 @@ class LocalizationUIModel extends _$LocalizationUIModel {
return globalIni;
}
// Web 版本从字节数据读取 Archive
static StringBuffer readArchiveFromBytes(Uint8List data) {
final output = GZipDecoder().decodeBytes(data);
final archive = TarDecoder().decodeBytes(output);
StringBuffer globalIni = StringBuffer("");
for (var element in archive.files) {
if (element.name.contains("global.ini")) {
if (element.rawContent == null) continue;
final stringContent = utf8.decode(element.rawContent!.readBytes());
for (var value in (stringContent).split("\n")) {
final tv = value.trim();
if (tv.isNotEmpty) globalIni.writeln(value);
}
}
}
archive.clear();
return globalIni;
}
String? getScInstallPath() {
return ref.read(homeUIModelProvider).scInstalledPath;
}
@@ -440,6 +573,13 @@ class LocalizationUIModel extends _$LocalizationUIModel {
await appConfBox.put("localization_selectedLanguage", v);
}
void selectChannel(String v) async {
state = state.copyWith(selectedChannel: v);
_loadData();
final appConfBox = await Hive.openBox("app_conf");
await appConfBox.put("localization_selectedChannel", v);
}
VoidCallback? onBack(BuildContext context) {
if (state.workingVersion.isNotEmpty) return null;
return () {
@@ -456,14 +596,20 @@ class LocalizationUIModel extends _$LocalizationUIModel {
}
Future<void> _updateStatus() async {
// Web 版本不支持此功能
if (kIsWeb) return;
final iniPath = "${_scDataDir.absolute.path}\\Localization\\${state.selectedLanguage}\\global.ini";
final patchStatus =
MapEntry(await _getLangCfgEnableLang(lang: state.selectedLanguage!), await _getInstalledIniVersion(iniPath));
final patchStatus = MapEntry(
await _getLangCfgEnableLang(lang: state.selectedLanguage!),
await _getInstalledIniVersion(iniPath),
);
final isInstalledAdvanced = await _checkAdvancedStatus(iniPath);
final installedCommunityInputMethodSupportVersion = await getInstalledCommunityInputMethodSupportVersion(iniPath);
dPrint(
"_updateStatus updateStatus: $patchStatus , isInstalledAdvanced: $isInstalledAdvanced ,installedCommunityInputMethodSupportVersion: $installedCommunityInputMethodSupportVersion");
"_updateStatus updateStatus: $patchStatus , isInstalledAdvanced: $isInstalledAdvanced ,installedCommunityInputMethodSupportVersion: $installedCommunityInputMethodSupportVersion",
);
state = state.copyWith(
patchStatus: patchStatus,
@@ -473,6 +619,9 @@ class LocalizationUIModel extends _$LocalizationUIModel {
}
Future<String?> getInstalledCommunityInputMethodSupportVersion(String path) async {
// Web 版本不支持此功能
if (kIsWeb) return null;
final iniFile = File(path);
if (!await iniFile.exists()) {
return null;
@@ -488,6 +637,9 @@ class LocalizationUIModel extends _$LocalizationUIModel {
}
Future<bool> _checkAdvancedStatus(String path) async {
// Web 版本不支持此功能
if (kIsWeb) return false;
final iniFile = File(path);
if (!await iniFile.exists()) {
return false;
@@ -497,6 +649,9 @@ class LocalizationUIModel extends _$LocalizationUIModel {
}
Future<bool> _getLangCfgEnableLang({String lang = "", String gamePath = ""}) async {
// Web 版本不支持此功能
if (kIsWeb) return false;
if (gamePath.isEmpty) {
gamePath = _scInstallPath;
}
@@ -509,6 +664,9 @@ class LocalizationUIModel extends _$LocalizationUIModel {
}
static Future<String> _getInstalledIniVersion(String iniPath) async {
// Web 版本不支持此功能
if (kIsWeb) return S.current.home_action_info_game_built_in;
final iniFile = File(iniPath);
if (!await iniFile.exists()) {
return S.current.home_action_info_game_built_in;
@@ -524,6 +682,9 @@ class LocalizationUIModel extends _$LocalizationUIModel {
}
Future<List<String>> checkLangUpdate({bool skipReload = false}) async {
// Web 版本不支持此功能
if (kIsWeb) return [];
if (_scInstallPath == "not_install") {
return [];
}
@@ -571,6 +732,7 @@ class LocalizationUIModel extends _$LocalizationUIModel {
}
Future<void> checkCommunityInputMethodUpdate() async {
if (kIsWeb) return; // Web 版本不支持自动更新检查
final cloudVersion = state.communityInputMethodLanguageData?.version;
final localVersion = state.installedCommunityInputMethodSupportVersion;
if (cloudVersion == null || localVersion == null) return;
@@ -582,11 +744,14 @@ class LocalizationUIModel extends _$LocalizationUIModel {
return;
}
await installFormString(StringBuffer(localIniString), versioName, isEnableCommunityInputMethod: true);
await win32.sendNotify(
summary: S.current.input_method_support_updated,
body: S.current.input_method_support_updated_to_version(cloudVersion),
appName: S.current.home_title_app_name,
appId: ConstConf.win32AppId);
if (!kIsWeb) {
// Web 版本不支持系统通知
// await win32.sendNotify(
// summary: S.current.input_method_support_updated,
// body: S.current.input_method_support_updated_to_version(cloudVersion),
// appName: S.current.home_title_app_name,
// appId: ConstConf.win32AppId);
}
}
}
@@ -595,7 +760,10 @@ class LocalizationUIModel extends _$LocalizationUIModel {
}
Future<void> onRemoteInsTall(
BuildContext context, MapEntry<String, ScLocalizationData> item, LocalizationUIState state) async {
BuildContext context,
MapEntry<String, ScLocalizationData> item,
LocalizationUIState state,
) async {
final appBox = Hive.box("app_conf");
bool enableCommunityInputMethod = state.communityInputMethodLanguageData != null;
bool isEnableVehicleSorting = appBox.get("vehicle_sorting", defaultValue: false) ?? false;
@@ -646,9 +814,7 @@ class LocalizationUIModel extends _$LocalizationUIModel {
SizedBox(height: 12),
Row(
children: [
Text(
S.current.input_method_install_community_input_method_support,
),
Text(S.current.input_method_install_community_input_method_support),
Spacer(),
StatefulBuilder(
builder: (BuildContext context, void Function(void Function()) setState) {
@@ -662,15 +828,13 @@ class LocalizationUIModel extends _$LocalizationUIModel {
},
);
},
)
),
],
),
SizedBox(height: 12),
Row(
children: [
Text(
S.current.tools_vehicle_sorting_title,
),
Text(S.current.tools_vehicle_sorting_title),
Spacer(),
StatefulBuilder(
builder: (BuildContext context, void Function(void Function()) setState) {
@@ -683,7 +847,7 @@ class LocalizationUIModel extends _$LocalizationUIModel {
},
);
},
)
),
],
),
],
@@ -717,4 +881,21 @@ class LocalizationUIModel extends _$LocalizationUIModel {
}
}
}
}
}
// Web 平台支持 - JS 互操作
@JS("Blob")
extension type Blob._(JSObject _) implements JSObject {
external factory Blob(JSArray<JSArrayBuffer> blobParts, JSAny? options);
factory Blob.fromBytes(List<int> bytes, {Map? opt}) {
final data = Uint8List.fromList(bytes).buffer.toJS;
return Blob([data].toJS, opt?.jsify());
}
external JSArrayBuffer? get blobParts;
external JSObject? get options;
}
@JS()
external void jsDownloadBlobFile(String blobUrl, String filename);

View File

@@ -14,7 +14,7 @@ T _$identity<T>(T value) => value;
/// @nodoc
mixin _$LocalizationUIState {
String? get selectedLanguage; String? get installedCommunityInputMethodSupportVersion; InputMethodApiLanguageData? get communityInputMethodLanguageData; Map<String, ScLocalizationData>? get apiLocalizationData; String get workingVersion; MapEntry<bool, String>? get patchStatus; bool? get isInstalledAdvanced; List<String>? get customizeList;
String? get selectedLanguage; String get selectedChannel; String? get installedCommunityInputMethodSupportVersion; InputMethodApiLanguageData? get communityInputMethodLanguageData; Map<String, ScLocalizationData>? get apiLocalizationData; String get workingVersion; MapEntry<bool, String>? get patchStatus; bool? get isInstalledAdvanced; List<String>? get customizeList;
/// Create a copy of LocalizationUIState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@@ -25,16 +25,16 @@ $LocalizationUIStateCopyWith<LocalizationUIState> get copyWith => _$Localization
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is LocalizationUIState&&(identical(other.selectedLanguage, selectedLanguage) || other.selectedLanguage == selectedLanguage)&&(identical(other.installedCommunityInputMethodSupportVersion, installedCommunityInputMethodSupportVersion) || other.installedCommunityInputMethodSupportVersion == installedCommunityInputMethodSupportVersion)&&(identical(other.communityInputMethodLanguageData, communityInputMethodLanguageData) || other.communityInputMethodLanguageData == communityInputMethodLanguageData)&&const DeepCollectionEquality().equals(other.apiLocalizationData, apiLocalizationData)&&(identical(other.workingVersion, workingVersion) || other.workingVersion == workingVersion)&&(identical(other.patchStatus, patchStatus) || other.patchStatus == patchStatus)&&(identical(other.isInstalledAdvanced, isInstalledAdvanced) || other.isInstalledAdvanced == isInstalledAdvanced)&&const DeepCollectionEquality().equals(other.customizeList, customizeList));
return identical(this, other) || (other.runtimeType == runtimeType&&other is LocalizationUIState&&(identical(other.selectedLanguage, selectedLanguage) || other.selectedLanguage == selectedLanguage)&&(identical(other.selectedChannel, selectedChannel) || other.selectedChannel == selectedChannel)&&(identical(other.installedCommunityInputMethodSupportVersion, installedCommunityInputMethodSupportVersion) || other.installedCommunityInputMethodSupportVersion == installedCommunityInputMethodSupportVersion)&&(identical(other.communityInputMethodLanguageData, communityInputMethodLanguageData) || other.communityInputMethodLanguageData == communityInputMethodLanguageData)&&const DeepCollectionEquality().equals(other.apiLocalizationData, apiLocalizationData)&&(identical(other.workingVersion, workingVersion) || other.workingVersion == workingVersion)&&(identical(other.patchStatus, patchStatus) || other.patchStatus == patchStatus)&&(identical(other.isInstalledAdvanced, isInstalledAdvanced) || other.isInstalledAdvanced == isInstalledAdvanced)&&const DeepCollectionEquality().equals(other.customizeList, customizeList));
}
@override
int get hashCode => Object.hash(runtimeType,selectedLanguage,installedCommunityInputMethodSupportVersion,communityInputMethodLanguageData,const DeepCollectionEquality().hash(apiLocalizationData),workingVersion,patchStatus,isInstalledAdvanced,const DeepCollectionEquality().hash(customizeList));
int get hashCode => Object.hash(runtimeType,selectedLanguage,selectedChannel,installedCommunityInputMethodSupportVersion,communityInputMethodLanguageData,const DeepCollectionEquality().hash(apiLocalizationData),workingVersion,patchStatus,isInstalledAdvanced,const DeepCollectionEquality().hash(customizeList));
@override
String toString() {
return 'LocalizationUIState(selectedLanguage: $selectedLanguage, installedCommunityInputMethodSupportVersion: $installedCommunityInputMethodSupportVersion, communityInputMethodLanguageData: $communityInputMethodLanguageData, apiLocalizationData: $apiLocalizationData, workingVersion: $workingVersion, patchStatus: $patchStatus, isInstalledAdvanced: $isInstalledAdvanced, customizeList: $customizeList)';
return 'LocalizationUIState(selectedLanguage: $selectedLanguage, selectedChannel: $selectedChannel, installedCommunityInputMethodSupportVersion: $installedCommunityInputMethodSupportVersion, communityInputMethodLanguageData: $communityInputMethodLanguageData, apiLocalizationData: $apiLocalizationData, workingVersion: $workingVersion, patchStatus: $patchStatus, isInstalledAdvanced: $isInstalledAdvanced, customizeList: $customizeList)';
}
@@ -45,7 +45,7 @@ abstract mixin class $LocalizationUIStateCopyWith<$Res> {
factory $LocalizationUIStateCopyWith(LocalizationUIState value, $Res Function(LocalizationUIState) _then) = _$LocalizationUIStateCopyWithImpl;
@useResult
$Res call({
String? selectedLanguage, String? installedCommunityInputMethodSupportVersion, InputMethodApiLanguageData? communityInputMethodLanguageData, Map<String, ScLocalizationData>? apiLocalizationData, String workingVersion, MapEntry<bool, String>? patchStatus, bool? isInstalledAdvanced, List<String>? customizeList
String? selectedLanguage, String selectedChannel, String? installedCommunityInputMethodSupportVersion, InputMethodApiLanguageData? communityInputMethodLanguageData, Map<String, ScLocalizationData>? apiLocalizationData, String workingVersion, MapEntry<bool, String>? patchStatus, bool? isInstalledAdvanced, List<String>? customizeList
});
@@ -62,10 +62,11 @@ class _$LocalizationUIStateCopyWithImpl<$Res>
/// Create a copy of LocalizationUIState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? selectedLanguage = freezed,Object? installedCommunityInputMethodSupportVersion = freezed,Object? communityInputMethodLanguageData = freezed,Object? apiLocalizationData = freezed,Object? workingVersion = null,Object? patchStatus = freezed,Object? isInstalledAdvanced = freezed,Object? customizeList = freezed,}) {
@pragma('vm:prefer-inline') @override $Res call({Object? selectedLanguage = freezed,Object? selectedChannel = null,Object? installedCommunityInputMethodSupportVersion = freezed,Object? communityInputMethodLanguageData = freezed,Object? apiLocalizationData = freezed,Object? workingVersion = null,Object? patchStatus = freezed,Object? isInstalledAdvanced = freezed,Object? customizeList = freezed,}) {
return _then(_self.copyWith(
selectedLanguage: freezed == selectedLanguage ? _self.selectedLanguage : selectedLanguage // ignore: cast_nullable_to_non_nullable
as String?,installedCommunityInputMethodSupportVersion: freezed == installedCommunityInputMethodSupportVersion ? _self.installedCommunityInputMethodSupportVersion : installedCommunityInputMethodSupportVersion // ignore: cast_nullable_to_non_nullable
as String?,selectedChannel: null == selectedChannel ? _self.selectedChannel : selectedChannel // ignore: cast_nullable_to_non_nullable
as String,installedCommunityInputMethodSupportVersion: freezed == installedCommunityInputMethodSupportVersion ? _self.installedCommunityInputMethodSupportVersion : installedCommunityInputMethodSupportVersion // ignore: cast_nullable_to_non_nullable
as String?,communityInputMethodLanguageData: freezed == communityInputMethodLanguageData ? _self.communityInputMethodLanguageData : communityInputMethodLanguageData // ignore: cast_nullable_to_non_nullable
as InputMethodApiLanguageData?,apiLocalizationData: freezed == apiLocalizationData ? _self.apiLocalizationData : apiLocalizationData // ignore: cast_nullable_to_non_nullable
as Map<String, ScLocalizationData>?,workingVersion: null == workingVersion ? _self.workingVersion : workingVersion // ignore: cast_nullable_to_non_nullable
@@ -157,10 +158,10 @@ return $default(_that);case _:
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String? selectedLanguage, String? installedCommunityInputMethodSupportVersion, InputMethodApiLanguageData? communityInputMethodLanguageData, Map<String, ScLocalizationData>? apiLocalizationData, String workingVersion, MapEntry<bool, String>? patchStatus, bool? isInstalledAdvanced, List<String>? customizeList)? $default,{required TResult orElse(),}) {final _that = this;
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String? selectedLanguage, String selectedChannel, String? installedCommunityInputMethodSupportVersion, InputMethodApiLanguageData? communityInputMethodLanguageData, Map<String, ScLocalizationData>? apiLocalizationData, String workingVersion, MapEntry<bool, String>? patchStatus, bool? isInstalledAdvanced, List<String>? customizeList)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _LocalizationUIState() when $default != null:
return $default(_that.selectedLanguage,_that.installedCommunityInputMethodSupportVersion,_that.communityInputMethodLanguageData,_that.apiLocalizationData,_that.workingVersion,_that.patchStatus,_that.isInstalledAdvanced,_that.customizeList);case _:
return $default(_that.selectedLanguage,_that.selectedChannel,_that.installedCommunityInputMethodSupportVersion,_that.communityInputMethodLanguageData,_that.apiLocalizationData,_that.workingVersion,_that.patchStatus,_that.isInstalledAdvanced,_that.customizeList);case _:
return orElse();
}
@@ -178,10 +179,10 @@ return $default(_that.selectedLanguage,_that.installedCommunityInputMethodSuppor
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String? selectedLanguage, String? installedCommunityInputMethodSupportVersion, InputMethodApiLanguageData? communityInputMethodLanguageData, Map<String, ScLocalizationData>? apiLocalizationData, String workingVersion, MapEntry<bool, String>? patchStatus, bool? isInstalledAdvanced, List<String>? customizeList) $default,) {final _that = this;
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String? selectedLanguage, String selectedChannel, String? installedCommunityInputMethodSupportVersion, InputMethodApiLanguageData? communityInputMethodLanguageData, Map<String, ScLocalizationData>? apiLocalizationData, String workingVersion, MapEntry<bool, String>? patchStatus, bool? isInstalledAdvanced, List<String>? customizeList) $default,) {final _that = this;
switch (_that) {
case _LocalizationUIState():
return $default(_that.selectedLanguage,_that.installedCommunityInputMethodSupportVersion,_that.communityInputMethodLanguageData,_that.apiLocalizationData,_that.workingVersion,_that.patchStatus,_that.isInstalledAdvanced,_that.customizeList);case _:
return $default(_that.selectedLanguage,_that.selectedChannel,_that.installedCommunityInputMethodSupportVersion,_that.communityInputMethodLanguageData,_that.apiLocalizationData,_that.workingVersion,_that.patchStatus,_that.isInstalledAdvanced,_that.customizeList);case _:
throw StateError('Unexpected subclass');
}
@@ -198,10 +199,10 @@ return $default(_that.selectedLanguage,_that.installedCommunityInputMethodSuppor
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String? selectedLanguage, String? installedCommunityInputMethodSupportVersion, InputMethodApiLanguageData? communityInputMethodLanguageData, Map<String, ScLocalizationData>? apiLocalizationData, String workingVersion, MapEntry<bool, String>? patchStatus, bool? isInstalledAdvanced, List<String>? customizeList)? $default,) {final _that = this;
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String? selectedLanguage, String selectedChannel, String? installedCommunityInputMethodSupportVersion, InputMethodApiLanguageData? communityInputMethodLanguageData, Map<String, ScLocalizationData>? apiLocalizationData, String workingVersion, MapEntry<bool, String>? patchStatus, bool? isInstalledAdvanced, List<String>? customizeList)? $default,) {final _that = this;
switch (_that) {
case _LocalizationUIState() when $default != null:
return $default(_that.selectedLanguage,_that.installedCommunityInputMethodSupportVersion,_that.communityInputMethodLanguageData,_that.apiLocalizationData,_that.workingVersion,_that.patchStatus,_that.isInstalledAdvanced,_that.customizeList);case _:
return $default(_that.selectedLanguage,_that.selectedChannel,_that.installedCommunityInputMethodSupportVersion,_that.communityInputMethodLanguageData,_that.apiLocalizationData,_that.workingVersion,_that.patchStatus,_that.isInstalledAdvanced,_that.customizeList);case _:
return null;
}
@@ -213,10 +214,11 @@ return $default(_that.selectedLanguage,_that.installedCommunityInputMethodSuppor
class _LocalizationUIState implements LocalizationUIState {
_LocalizationUIState({this.selectedLanguage, this.installedCommunityInputMethodSupportVersion, this.communityInputMethodLanguageData, final Map<String, ScLocalizationData>? apiLocalizationData, this.workingVersion = "", this.patchStatus, this.isInstalledAdvanced, final List<String>? customizeList}): _apiLocalizationData = apiLocalizationData,_customizeList = customizeList;
_LocalizationUIState({this.selectedLanguage, this.selectedChannel = "LIVE", this.installedCommunityInputMethodSupportVersion, this.communityInputMethodLanguageData, final Map<String, ScLocalizationData>? apiLocalizationData, this.workingVersion = "", this.patchStatus, this.isInstalledAdvanced, final List<String>? customizeList}): _apiLocalizationData = apiLocalizationData,_customizeList = customizeList;
@override final String? selectedLanguage;
@override@JsonKey() final String selectedChannel;
@override final String? installedCommunityInputMethodSupportVersion;
@override final InputMethodApiLanguageData? communityInputMethodLanguageData;
final Map<String, ScLocalizationData>? _apiLocalizationData;
@@ -251,16 +253,16 @@ _$LocalizationUIStateCopyWith<_LocalizationUIState> get copyWith => __$Localizat
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _LocalizationUIState&&(identical(other.selectedLanguage, selectedLanguage) || other.selectedLanguage == selectedLanguage)&&(identical(other.installedCommunityInputMethodSupportVersion, installedCommunityInputMethodSupportVersion) || other.installedCommunityInputMethodSupportVersion == installedCommunityInputMethodSupportVersion)&&(identical(other.communityInputMethodLanguageData, communityInputMethodLanguageData) || other.communityInputMethodLanguageData == communityInputMethodLanguageData)&&const DeepCollectionEquality().equals(other._apiLocalizationData, _apiLocalizationData)&&(identical(other.workingVersion, workingVersion) || other.workingVersion == workingVersion)&&(identical(other.patchStatus, patchStatus) || other.patchStatus == patchStatus)&&(identical(other.isInstalledAdvanced, isInstalledAdvanced) || other.isInstalledAdvanced == isInstalledAdvanced)&&const DeepCollectionEquality().equals(other._customizeList, _customizeList));
return identical(this, other) || (other.runtimeType == runtimeType&&other is _LocalizationUIState&&(identical(other.selectedLanguage, selectedLanguage) || other.selectedLanguage == selectedLanguage)&&(identical(other.selectedChannel, selectedChannel) || other.selectedChannel == selectedChannel)&&(identical(other.installedCommunityInputMethodSupportVersion, installedCommunityInputMethodSupportVersion) || other.installedCommunityInputMethodSupportVersion == installedCommunityInputMethodSupportVersion)&&(identical(other.communityInputMethodLanguageData, communityInputMethodLanguageData) || other.communityInputMethodLanguageData == communityInputMethodLanguageData)&&const DeepCollectionEquality().equals(other._apiLocalizationData, _apiLocalizationData)&&(identical(other.workingVersion, workingVersion) || other.workingVersion == workingVersion)&&(identical(other.patchStatus, patchStatus) || other.patchStatus == patchStatus)&&(identical(other.isInstalledAdvanced, isInstalledAdvanced) || other.isInstalledAdvanced == isInstalledAdvanced)&&const DeepCollectionEquality().equals(other._customizeList, _customizeList));
}
@override
int get hashCode => Object.hash(runtimeType,selectedLanguage,installedCommunityInputMethodSupportVersion,communityInputMethodLanguageData,const DeepCollectionEquality().hash(_apiLocalizationData),workingVersion,patchStatus,isInstalledAdvanced,const DeepCollectionEquality().hash(_customizeList));
int get hashCode => Object.hash(runtimeType,selectedLanguage,selectedChannel,installedCommunityInputMethodSupportVersion,communityInputMethodLanguageData,const DeepCollectionEquality().hash(_apiLocalizationData),workingVersion,patchStatus,isInstalledAdvanced,const DeepCollectionEquality().hash(_customizeList));
@override
String toString() {
return 'LocalizationUIState(selectedLanguage: $selectedLanguage, installedCommunityInputMethodSupportVersion: $installedCommunityInputMethodSupportVersion, communityInputMethodLanguageData: $communityInputMethodLanguageData, apiLocalizationData: $apiLocalizationData, workingVersion: $workingVersion, patchStatus: $patchStatus, isInstalledAdvanced: $isInstalledAdvanced, customizeList: $customizeList)';
return 'LocalizationUIState(selectedLanguage: $selectedLanguage, selectedChannel: $selectedChannel, installedCommunityInputMethodSupportVersion: $installedCommunityInputMethodSupportVersion, communityInputMethodLanguageData: $communityInputMethodLanguageData, apiLocalizationData: $apiLocalizationData, workingVersion: $workingVersion, patchStatus: $patchStatus, isInstalledAdvanced: $isInstalledAdvanced, customizeList: $customizeList)';
}
@@ -271,7 +273,7 @@ abstract mixin class _$LocalizationUIStateCopyWith<$Res> implements $Localizatio
factory _$LocalizationUIStateCopyWith(_LocalizationUIState value, $Res Function(_LocalizationUIState) _then) = __$LocalizationUIStateCopyWithImpl;
@override @useResult
$Res call({
String? selectedLanguage, String? installedCommunityInputMethodSupportVersion, InputMethodApiLanguageData? communityInputMethodLanguageData, Map<String, ScLocalizationData>? apiLocalizationData, String workingVersion, MapEntry<bool, String>? patchStatus, bool? isInstalledAdvanced, List<String>? customizeList
String? selectedLanguage, String selectedChannel, String? installedCommunityInputMethodSupportVersion, InputMethodApiLanguageData? communityInputMethodLanguageData, Map<String, ScLocalizationData>? apiLocalizationData, String workingVersion, MapEntry<bool, String>? patchStatus, bool? isInstalledAdvanced, List<String>? customizeList
});
@@ -288,10 +290,11 @@ class __$LocalizationUIStateCopyWithImpl<$Res>
/// Create a copy of LocalizationUIState
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? selectedLanguage = freezed,Object? installedCommunityInputMethodSupportVersion = freezed,Object? communityInputMethodLanguageData = freezed,Object? apiLocalizationData = freezed,Object? workingVersion = null,Object? patchStatus = freezed,Object? isInstalledAdvanced = freezed,Object? customizeList = freezed,}) {
@override @pragma('vm:prefer-inline') $Res call({Object? selectedLanguage = freezed,Object? selectedChannel = null,Object? installedCommunityInputMethodSupportVersion = freezed,Object? communityInputMethodLanguageData = freezed,Object? apiLocalizationData = freezed,Object? workingVersion = null,Object? patchStatus = freezed,Object? isInstalledAdvanced = freezed,Object? customizeList = freezed,}) {
return _then(_LocalizationUIState(
selectedLanguage: freezed == selectedLanguage ? _self.selectedLanguage : selectedLanguage // ignore: cast_nullable_to_non_nullable
as String?,installedCommunityInputMethodSupportVersion: freezed == installedCommunityInputMethodSupportVersion ? _self.installedCommunityInputMethodSupportVersion : installedCommunityInputMethodSupportVersion // ignore: cast_nullable_to_non_nullable
as String?,selectedChannel: null == selectedChannel ? _self.selectedChannel : selectedChannel // ignore: cast_nullable_to_non_nullable
as String,installedCommunityInputMethodSupportVersion: freezed == installedCommunityInputMethodSupportVersion ? _self.installedCommunityInputMethodSupportVersion : installedCommunityInputMethodSupportVersion // ignore: cast_nullable_to_non_nullable
as String?,communityInputMethodLanguageData: freezed == communityInputMethodLanguageData ? _self.communityInputMethodLanguageData : communityInputMethodLanguageData // ignore: cast_nullable_to_non_nullable
as InputMethodApiLanguageData?,apiLocalizationData: freezed == apiLocalizationData ? _self._apiLocalizationData : apiLocalizationData // ignore: cast_nullable_to_non_nullable
as Map<String, ScLocalizationData>?,workingVersion: null == workingVersion ? _self.workingVersion : workingVersion // ignore: cast_nullable_to_non_nullable

View File

@@ -42,7 +42,7 @@ final class LocalizationUIModelProvider
}
String _$localizationUIModelHash() =>
r'd3797a7ff3d31dd1d4b05aed4a9969f4be6853c5';
r'93c4172a4048a083e941a9011067dc8b17c33ac5';
abstract class _$LocalizationUIModel extends $Notifier<LocalizationUIState> {
LocalizationUIState build();

View File

@@ -1,4 +1,5 @@
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:starcitizen_doctor/common/utils/log.dart';
@@ -30,12 +31,8 @@ class HomePerformanceUI extends HookConsumerWidget {
children: [
if (state.showGraphicsPerformanceTip)
InfoBar(
title: Text(S.current
.performance_info_graphic_optimization_hint),
content: Text(
S.current
.performance_info_graphic_optimization_warning,
),
title: Text(S.current.performance_info_graphic_optimization_hint),
content: Text(S.current.performance_info_graphic_optimization_warning),
onClose: () => model.closeTip(),
),
const SizedBox(height: 16),
@@ -43,65 +40,74 @@ class HomePerformanceUI extends HookConsumerWidget {
children: [
Text(
S.current.performance_info_current_status(
state.enabled
? S.current.performance_info_applied
: S.current.performance_info_not_applied),
state.enabled
? S.current.performance_info_applied
: S.current.performance_info_not_applied,
),
style: const TextStyle(fontSize: 18),
),
const SizedBox(width: 32),
Text(
S.current.performance_action_preset,
style: const TextStyle(fontSize: 18),
),
Text(S.current.performance_action_preset, style: const TextStyle(fontSize: 18)),
for (final item in {
"low": S.current.performance_action_low,
"medium": S.current.performance_action_medium,
"high": S.current.performance_action_high,
"ultra": S.current.performance_action_super
"ultra": S.current.performance_action_super,
}.entries)
Padding(
padding: const EdgeInsets.only(left: 6, right: 6),
child: Button(
child: Padding(
padding: const EdgeInsets.only(
top: 2, bottom: 2, left: 4, right: 4),
child: Text(item.value),
),
onPressed: () =>
model.onChangePreProfile(item.key)),
child: Padding(
padding: const EdgeInsets.only(top: 2, bottom: 2, left: 4, right: 4),
child: Text(item.value),
),
onPressed: () => model.onChangePreProfile(item.key),
),
),
Text(S.current
.performance_action_info_preset_only_changes_graphics),
Text(S.current.performance_action_info_preset_only_changes_graphics),
const Spacer(),
Button(
onPressed: () => model.refresh(),
child: const Padding(
padding: EdgeInsets.all(6),
child: Icon(FluentIcons.refresh),
),
child: const Padding(padding: EdgeInsets.all(6), child: Icon(FluentIcons.refresh)),
),
const SizedBox(width: 12),
Button(
if (!kIsWeb)
Button(
child: Text(
S.current.performance_action_reset_to_default,
style: const TextStyle(fontSize: 16),
),
onPressed: () => model.clean(context)),
const SizedBox(width: 24),
Button(
onPressed: () => model.clean(context),
),
if (!kIsWeb) const SizedBox(width: 24),
if (kIsWeb)
// Web 平台:下载配置文件
Button(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(FluentIcons.download, size: 16),
const SizedBox(width: 6),
Text("下载配置", style: const TextStyle(fontSize: 16)),
],
),
onPressed: () => model.downloadConfigForWeb(),
)
else ...[
// 桌面平台:应用配置
Button(
child: Text(S.current.performance_action_apply, style: const TextStyle(fontSize: 16)),
onPressed: () => model.applyProfile(false),
),
const SizedBox(width: 6),
Button(
child: Text(
S.current.performance_action_apply,
S.current.performance_action_apply_and_clear_shaders,
style: const TextStyle(fontSize: 16),
),
onPressed: () => model.applyProfile(false)),
const SizedBox(width: 6),
Button(
child: Text(
S.current
.performance_action_apply_and_clear_shaders,
style: const TextStyle(fontSize: 16),
),
onPressed: () => model.applyProfile(true)),
onPressed: () => model.applyProfile(true),
),
],
],
),
const SizedBox(height: 16),
@@ -109,73 +115,60 @@ class HomePerformanceUI extends HookConsumerWidget {
),
),
Expanded(
child: MasonryGridView.count(
crossAxisCount: 2,
mainAxisSpacing: 1,
crossAxisSpacing: 1,
itemCount: state.performanceMap!.length,
itemBuilder: (context, index) {
return makeItemGroup(context,
state.performanceMap!.entries.elementAt(index), model);
},
)),
child: MasonryGridView.count(
crossAxisCount: 2,
mainAxisSpacing: 1,
crossAxisSpacing: 1,
itemCount: state.performanceMap!.length,
itemBuilder: (context, index) {
return makeItemGroup(context, state.performanceMap!.entries.elementAt(index), model);
},
),
),
],
),
),
if (state.workingString.isNotEmpty)
Container(
decoration: BoxDecoration(
color: Colors.black.withAlpha(150),
),
decoration: BoxDecoration(color: Colors.black.withAlpha(150)),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const ProgressRing(),
const SizedBox(height: 12),
Text(state.workingString),
],
children: [const ProgressRing(), const SizedBox(height: 12), Text(state.workingString)],
),
),
)
),
],
);
}
return makeDefaultPage(context,
title:
S.current.performance_title_performance_optimization(model.scPath),
useBodyContainer: true,
content: content);
return makeDefaultPage(
context,
title: S.current.performance_title_performance_optimization(model.scPath),
useBodyContainer: true,
content: content,
);
}
Widget makeItemGroup(
BuildContext context,
MapEntry<String?, List<GamePerformanceData>> group,
HomePerformanceUIModel model) {
BuildContext context,
MapEntry<String?, List<GamePerformanceData>> group,
HomePerformanceUIModel model,
) {
return Padding(
padding: const EdgeInsets.all(12),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: FluentTheme.of(context).cardColor,
),
decoration: BoxDecoration(borderRadius: BorderRadius.circular(12), color: FluentTheme.of(context).cardColor),
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"${group.key}",
style: const TextStyle(fontSize: 20),
),
Text("${group.key}", style: const TextStyle(fontSize: 20)),
const SizedBox(height: 6),
Container(
color:
FluentTheme.of(context).cardColor.withValues(alpha: .2),
height: 1),
Container(color: FluentTheme.of(context).cardColor.withValues(alpha: .2), height: 1),
const SizedBox(height: 6),
for (final item in group.value) makeItem(context, item, model)
for (final item in group.value) makeItem(context, item, model),
],
),
),
@@ -183,17 +176,13 @@ class HomePerformanceUI extends HookConsumerWidget {
);
}
Widget makeItem(BuildContext context, GamePerformanceData item,
HomePerformanceUIModel model) {
Widget makeItem(BuildContext context, GamePerformanceData item, HomePerformanceUIModel model) {
return Padding(
padding: const EdgeInsets.only(top: 8, bottom: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"${item.name}",
style: const TextStyle(fontSize: 16),
),
Text("${item.name}", style: const TextStyle(fontSize: 16)),
const SizedBox(height: 12),
if (item.type == "int")
Column(
@@ -209,9 +198,7 @@ class HomePerformanceUI extends HookConsumerWidget {
dPrint(str);
if (str.isEmpty) return;
final v = int.tryParse(str);
if (v != null &&
v < (item.max ?? 0) &&
v >= (item.min ?? 0)) {
if (v != null && v < (item.max ?? 0) && v >= (item.min ?? 0)) {
item.value = v;
}
model.updateState();
@@ -233,9 +220,9 @@ class HomePerformanceUI extends HookConsumerWidget {
model.updateState();
},
),
)
),
],
)
),
],
)
else if (item.type == "bool")
@@ -247,7 +234,7 @@ class HomePerformanceUI extends HookConsumerWidget {
item.value = value ? 1 : 0;
model.updateState();
},
)
),
],
)
else if (item.type == "customize")
@@ -258,11 +245,7 @@ class HomePerformanceUI extends HookConsumerWidget {
),
if (item.info != null && item.info!.isNotEmpty) ...[
const SizedBox(height: 12),
Text(
"${item.info}",
style: TextStyle(
fontSize: 14, color: Colors.white.withValues(alpha: .6)),
),
Text("${item.info}", style: TextStyle(fontSize: 14, color: Colors.white.withValues(alpha: .6))),
],
const SizedBox(height: 12),
if (item.type != "customize")
@@ -270,16 +253,13 @@ class HomePerformanceUI extends HookConsumerWidget {
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
S.current.performance_info_min_max_values(
item.key ?? "", item.min ?? "", item.max ?? ""),
S.current.performance_info_min_max_values(item.key ?? "", item.min ?? "", item.max ?? ""),
style: TextStyle(color: Colors.white.withValues(alpha: .6)),
)
),
],
),
const SizedBox(height: 6),
Container(
color: FluentTheme.of(context).cardColor.withValues(alpha: .1),
height: 1),
Container(color: FluentTheme.of(context).cardColor.withValues(alpha: .1), height: 1),
],
),
);

View File

@@ -1,7 +1,12 @@
// ignore_for_file: avoid_build_context_in_providers, avoid_public_notifier_properties
import 'dart:io';
import 'dart:js_interop';
import 'dart:typed_data';
import 'package:archive/archive.dart';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/foundation.dart' show kIsWeb, compute;
import 'package:web/web.dart' as web;
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:hive_ce/hive.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
@@ -36,7 +41,7 @@ class HomePerformanceUIModel extends _$HomePerformanceUIModel {
final List<String> _inAppKeys = [];
late final confFile = File("$scPath\\USER.cfg");
late final confFile = kIsWeb ? null : File("$scPath\\USER.cfg");
static const _graphicsPerformanceTipVersion = 1;
@@ -66,7 +71,7 @@ class HomePerformanceUIModel extends _$HomePerformanceUIModel {
}
state = state.copyWith(performanceMap: performanceMap);
if (await confFile.exists()) {
if (!kIsWeb && await confFile!.exists()) {
await _readConf();
} else {
state = state.copyWith(enabled: false);
@@ -78,10 +83,10 @@ class HomePerformanceUIModel extends _$HomePerformanceUIModel {
}
Future<void> _readConf() async {
if (state.performanceMap == null) return;
if (state.performanceMap == null || kIsWeb) return;
state = state.copyWith(enabled: true);
final confString = await confFile.readAsString();
final confString = await confFile!.readAsString();
for (var value in confString.split("\n")) {
final kv = value.split("=");
for (var m in state.performanceMap!.entries) {
@@ -151,9 +156,15 @@ class HomePerformanceUIModel extends _$HomePerformanceUIModel {
}
Future<void> clean(BuildContext context) async {
if (kIsWeb) {
// Web 平台只需要重置状态
await _init();
return;
}
state = state.copyWith(workingString: S.current.performance_info_delete_config_file);
if (await confFile.exists()) {
await confFile.delete(recursive: true);
if (await confFile!.exists()) {
await confFile!.delete(recursive: true);
}
state = state.copyWith(workingString: S.current.performance_action_clear_shaders);
if (!context.mounted) return;
@@ -181,6 +192,12 @@ class HomePerformanceUIModel extends _$HomePerformanceUIModel {
}
Future<void> applyProfile(bool cleanShader) async {
if (kIsWeb) {
// Web 平台使用下载功能
await downloadConfigForWeb();
return;
}
if (state.performanceMap == null) return;
AnalyticsApi.touch("performance_apply");
state = state.copyWith(workingString: S.current.performance_info_generate_config_file);
@@ -203,11 +220,11 @@ class HomePerformanceUIModel extends _$HomePerformanceUIModel {
}
}
state = state.copyWith(workingString: S.current.performance_info_write_out_config_file);
if (await confFile.exists()) {
await confFile.delete();
if (await confFile!.exists()) {
await confFile!.delete();
}
await confFile.create();
await confFile.writeAsString(conf);
await confFile!.create();
await confFile!.writeAsString(conf);
if (cleanShader) {
state = state.copyWith(workingString: S.current.performance_action_clear_shaders);
await cleanShaderCache(null);
@@ -221,4 +238,70 @@ class HomePerformanceUIModel extends _$HomePerformanceUIModel {
void updateState() {
state = state.copyWith();
}
/// Web 平台下载配置文件
Future<void> downloadConfigForWeb() async {
if (!kIsWeb) return;
if (state.performanceMap == null) return;
AnalyticsApi.touch("performance_download_web");
state = state.copyWith(workingString: S.current.performance_info_generate_config_file);
String conf = "";
for (var v in state.performanceMap!.entries) {
for (var c in v.value) {
if (c.key != "customize") {
conf = "$conf${c.key}=${c.value}\n";
}
}
}
if (customizeCtrl.text.trim().isNotEmpty) {
final lines = customizeCtrl.text.split("\n");
for (var value in lines) {
final sp = value.split("=");
// 忽略无效的配置文件
if (sp.length == 2) {
conf = "$conf${sp[0].trim()}=${sp[1].trim()}\n";
}
}
}
await _generateAndDownloadWebFile(conf);
state = state.copyWith(workingString: "");
}
Future<void> _generateAndDownloadWebFile(String confContent) async {
final archive = Archive();
archive.addFile(ArchiveFile("USER.cfg", confContent.length, confContent.codeUnits));
final zip = await compute(_encodeZipFile, archive);
if (zip == null) return;
final blob = Blob.fromBytes(zip, opt: {"type": "application/zip"});
final url = web.URL.createObjectURL(blob);
jsDownloadBlobFile(url, "StarCitizen_Performance_Config.zip");
}
List<int>? _encodeZipFile(Archive archive) {
final zip = ZipEncoder().encode(archive);
return zip;
}
}
// Web 平台支持 - JS 互操作
@JS("Blob")
extension type Blob._(JSObject _) implements JSObject {
external factory Blob(JSArray<JSArrayBuffer> blobParts, JSAny? options);
factory Blob.fromBytes(List<int> bytes, {Map? opt}) {
final data = Uint8List.fromList(bytes).buffer.toJS;
return Blob([data].toJS, opt?.jsify());
}
external JSArrayBuffer? get blobParts;
external JSObject? get options;
}
@JS()
external void jsDownloadBlobFile(String blobUrl, String filename);

View File

@@ -42,7 +42,7 @@ final class HomePerformanceUIModelProvider
}
String _$homePerformanceUIModelHash() =>
r'c3c55c0470ef8c8be4915a1878deba332653ecde';
r'4c5c33fe7d85dc8f6bf0d019c1b870d285d594ff';
abstract class _$HomePerformanceUIModel
extends $Notifier<HomePerformanceUIState> {