feat: Migrate more PowerShell calls to Rust implementation

This commit is contained in:
xkeyC
2025-12-05 11:06:54 +08:00
parent f6676ed3d8
commit 62b8718dbd
16 changed files with 1377 additions and 357 deletions

View File

@@ -6,6 +6,7 @@ import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:starcitizen_doctor/common/helper/log_helper.dart';
import 'package:starcitizen_doctor/common/helper/system_helper.dart';
import 'package:starcitizen_doctor/common/rust/api/win32_api.dart' as win32;
import 'package:starcitizen_doctor/common/utils/base_utils.dart';
import 'package:starcitizen_doctor/common/utils/log.dart';
import 'package:starcitizen_doctor/ui/home/home_ui_model.dart';
@@ -35,11 +36,11 @@ class HomeGameDoctorUIModel extends _$HomeGameDoctorUIModel {
}
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 +50,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 +70,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 +78,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 +97,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 +109,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);
@@ -144,11 +137,8 @@ class HomeGameDoctorUIModel extends _$HomeGameDoctorUIModel {
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)) {
@@ -158,8 +148,11 @@ class HomeGameDoctorUIModel extends _$HomeGameDoctorUIModel {
}
// ignore: avoid_build_context_in_providers
Future _checkGameRunningLog(BuildContext context, String scInstalledPath,
List<MapEntry<String, String>> checkResult) async {
Future _checkGameRunningLog(
BuildContext context,
String scInstalledPath,
List<MapEntry<String, String>> checkResult,
) async {
if (scInstalledPath == "not_install") return;
final lastScreenInfo = S.current.doctor_action_tip_checking_game_log;
state = state.copyWith(lastScreenInfo: lastScreenInfo);
@@ -168,28 +161,27 @@ class HomeGameDoctorUIModel extends _$HomeGameDoctorUIModel {
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 +204,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 +229,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) {
@@ -262,19 +253,16 @@ class HomeGameDoctorUIModel extends _$HomeGameDoctorUIModel {
}
}
// call check
// call check using Rust API
for (var element in p) {
var result = await Process.run('powershell', [
"(fsutil fsinfo sectorinfo $element: | Select-String 'PhysicalBytesPerSectorForPerformance').ToString().Split(':')[1].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);
try {
final physicalBytesPerSectorForPerformance = await win32.getDiskPhysicalSectorSize(driveLetter: element);
dPrint("disk sector info for $element: -> $physicalBytesPerSectorForPerformance");
if (physicalBytesPerSectorForPerformance > 4096) {
checkResult.add(MapEntry("nvme_PhysicalBytes", element));
}
} catch (e) {
dPrint("getDiskPhysicalSectorSize error: $e");
}
}
} catch (e) {

View File

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

View File

@@ -12,7 +12,6 @@ import 'package:starcitizen_doctor/api/news_api.dart';
import 'package:starcitizen_doctor/common/conf/conf.dart';
import 'package:starcitizen_doctor/common/conf/url_conf.dart';
import 'package:starcitizen_doctor/common/helper/log_helper.dart';
import 'package:starcitizen_doctor/common/helper/system_helper.dart';
import 'package:starcitizen_doctor/common/io/rs_http.dart';
import 'package:starcitizen_doctor/common/rust/api/win32_api.dart' as win32;
import 'package:starcitizen_doctor/common/utils/async.dart';
@@ -323,7 +322,7 @@ class HomeUIModel extends _$HomeUIModel {
if (ConstConf.isMSE) {
if (state.isCurGameRunning) {
await Process.run(SystemHelper.powershellPath, ["ps \"StarCitizen\" | kill"]);
await win32.killProcessByName(processName: "StarCitizen");
return;
}
AnalyticsApi.touch("gameLaunch");

View File

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

View File

@@ -9,6 +9,7 @@ import 'package:hive_ce/hive.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:starcitizen_doctor/common/conf/conf.dart';
import 'package:starcitizen_doctor/common/helper/system_helper.dart';
import 'package:starcitizen_doctor/common/rust/api/win32_api.dart' as win32;
import 'package:starcitizen_doctor/common/utils/log.dart';
import 'package:starcitizen_doctor/common/utils/provider.dart';
import 'package:starcitizen_doctor/widgets/widgets.dart';
@@ -50,14 +51,15 @@ class SettingsUIModel extends _$SettingsUIModel {
Future<void> setGameLaunchECore(BuildContext context) async {
final userBox = await Hive.openBox("app_conf");
final defaultInput =
userBox.get("gameLaunch_eCore_count", defaultValue: "0");
final defaultInput = userBox.get("gameLaunch_eCore_count", defaultValue: "0");
if (!context.mounted) return;
final input = await showInputDialogs(context,
title: S.current.setting_action_info_enter_cpu_core_to_ignore,
content: S.current.setting_action_info_cpu_core_tip,
initialValue: defaultInput,
inputFormatters: [FilteringTextInputFormatter.digitsOnly]);
final input = await showInputDialogs(
context,
title: S.current.setting_action_info_enter_cpu_core_to_ignore,
content: S.current.setting_action_info_cpu_core_tip,
initialValue: defaultInput,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
);
if (input == null) return;
userBox.put("gameLaunch_eCore_count", input);
_initState();
@@ -65,8 +67,7 @@ class SettingsUIModel extends _$SettingsUIModel {
Future _updateGameLaunchECore() async {
final userBox = await Hive.openBox("app_conf");
final inputGameLaunchECore =
userBox.get("gameLaunch_eCore_count", defaultValue: "0");
final inputGameLaunchECore = userBox.get("gameLaunch_eCore_count", defaultValue: "0");
state = state.copyWith(inputGameLaunchECore: inputGameLaunchECore);
}
@@ -102,9 +103,7 @@ class SettingsUIModel extends _$SettingsUIModel {
if (r == null || r.files.firstOrNull?.path == null) return;
final fileName = r.files.first.path!;
dPrint(fileName);
final fileNameRegExp = RegExp(
r"^(.*\\StarCitizen\\.*\\)Bin64\\StarCitizen\.exe$",
caseSensitive: false);
final fileNameRegExp = RegExp(r"^(.*\\StarCitizen\\.*\\)Bin64\\StarCitizen\.exe$", caseSensitive: false);
if (fileNameRegExp.hasMatch(fileName)) {
RegExp pathRegex = RegExp(r"\\[^\\]+\\Bin64\\StarCitizen\.exe$");
String extractedPath = fileName.replaceFirst(pathRegex, '');
@@ -127,8 +126,7 @@ class SettingsUIModel extends _$SettingsUIModel {
final confBox = await Hive.openBox("app_conf");
final customLauncherPath = confBox.get("custom_launcher_path");
final customGamePath = confBox.get("custom_game_path");
state = state.copyWith(
customLauncherPath: customLauncherPath, customGamePath: customGamePath);
state = state.copyWith(customLauncherPath: customLauncherPath, customGamePath: customGamePath);
}
Future<void> delName(String key) async {
@@ -138,24 +136,21 @@ class SettingsUIModel extends _$SettingsUIModel {
}
Future _loadLocationCacheSize() async {
final len1 = await SystemHelper.getDirLen(
"${appGlobalState.applicationSupportDir}/Localizations");
final len2 = await SystemHelper.getDirLen(
"${appGlobalState.applicationSupportDir}/launcher_enhance_data");
final len1 = await SystemHelper.getDirLen("${appGlobalState.applicationSupportDir}/Localizations");
final len2 = await SystemHelper.getDirLen("${appGlobalState.applicationSupportDir}/launcher_enhance_data");
final locationCacheSize = len1 + len2;
state = state.copyWith(locationCacheSize: locationCacheSize);
}
Future<void> cleanLocationCache(BuildContext context) async {
final ok = await showConfirmDialogs(
context,
S.current.setting_action_info_confirm_clear_cache,
Text(S.current.setting_action_info_clear_cache_warning));
context,
S.current.setting_action_info_confirm_clear_cache,
Text(S.current.setting_action_info_clear_cache_warning),
);
if (ok == true) {
final dir1 =
Directory("${appGlobalState.applicationSupportDir}/Localizations");
final dir2 = Directory(
"${appGlobalState.applicationSupportDir}/launcher_enhance_data");
final dir1 = Directory("${appGlobalState.applicationSupportDir}/Localizations");
final dir2 = Directory("${appGlobalState.applicationSupportDir}/launcher_enhance_data");
if (!context.mounted) return;
if (await dir1.exists()) {
if (!context.mounted) return;
@@ -172,36 +167,27 @@ class SettingsUIModel extends _$SettingsUIModel {
Future<void> addShortCut(BuildContext context) async {
if (ConstConf.isMSE) {
showToast(
context, S.current.setting_action_info_microsoft_version_limitation);
showToast(context, S.current.setting_action_info_microsoft_version_limitation);
await Future.delayed(const Duration(seconds: 1));
Process.run("explorer.exe", ["shell:AppsFolder"]);
return;
}
dPrint(Platform.resolvedExecutable);
final shortCuntName = S.current.app_shortcut_name;
final script = """
\$targetPath = "${Platform.resolvedExecutable}";
\$shortcutPath = [System.IO.Path]::Combine([System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::DesktopDirectory), "$shortCuntName");
\$shell = New-Object -ComObject WScript.Shell
\$shortcut = \$shell.CreateShortcut(\$shortcutPath)
if (\$shortcut -eq \$null) {
Write-Host "Failed to create shortcut."
} else {
\$shortcut.TargetPath = \$targetPath
\$shortcut.Save()
Write-Host "Shortcut created successfully."
final shortcutName = S.current.app_shortcut_name;
try {
await win32.createDesktopShortcut(targetPath: Platform.resolvedExecutable, shortcutName: shortcutName);
if (!context.mounted) return;
showToast(context, S.current.setting_action_info_shortcut_created);
} catch (e) {
dPrint("createDesktopShortcut error: $e");
if (!context.mounted) return;
showToast(context, "Failed to create shortcut: $e");
}
""";
await Process.run(SystemHelper.powershellPath, [script]);
if (!context.mounted) return;
showToast(context, S.current.setting_action_info_shortcut_created);
}
Future _loadToolSiteMirrorState() async {
final userBox = await Hive.openBox("app_conf");
final isEnableToolSiteMirrors =
userBox.get("isEnableToolSiteMirrors", defaultValue: false);
final isEnableToolSiteMirrors = userBox.get("isEnableToolSiteMirrors", defaultValue: false);
state = state.copyWith(isEnableToolSiteMirrors: isEnableToolSiteMirrors);
}
@@ -213,8 +199,7 @@ class SettingsUIModel extends _$SettingsUIModel {
}
Future<void> showLogs() async {
SystemHelper.openDir(getDPrintFile()?.absolute.path.replaceAll("/", "\\"),
isFile: true);
SystemHelper.openDir(getDPrintFile()?.absolute.path.replaceAll("/", "\\"), isFile: true);
}
void onChangeUseInternalDNS(bool? b) {
@@ -225,8 +210,7 @@ class SettingsUIModel extends _$SettingsUIModel {
Future _loadUseInternalDNS() async {
final userBox = await Hive.openBox("app_conf");
final isUseInternalDNS =
userBox.get("isUseInternalDNS", defaultValue: false);
final isUseInternalDNS = userBox.get("isUseInternalDNS", defaultValue: false);
state = state.copyWith(isUseInternalDNS: isUseInternalDNS);
}
@@ -238,8 +222,7 @@ class SettingsUIModel extends _$SettingsUIModel {
Future _loadOnnxXnnPackState() async {
final userBox = await Hive.openBox("app_conf");
final isEnableOnnxXnnPack =
userBox.get("isEnableOnnxXnnPack", defaultValue: true);
final isEnableOnnxXnnPack = userBox.get("isEnableOnnxXnnPack", defaultValue: true);
state = state.copyWith(isEnableOnnxXnnPack: isEnableOnnxXnnPack);
}
}

View File

@@ -41,7 +41,7 @@ final class SettingsUIModelProvider
}
}
String _$settingsUIModelHash() => r'72947d5ed36290df865cb010b056dc632f5dccec';
String _$settingsUIModelHash() => r'd34b1a2fac69d10f560d9a2e1a7431dd5a7954ca';
abstract class _$SettingsUIModel extends $Notifier<SettingsUIState> {
SettingsUIState build();

View File

@@ -11,6 +11,7 @@ import 'package:starcitizen_doctor/app.dart';
import 'package:starcitizen_doctor/common/conf/conf.dart';
import 'package:starcitizen_doctor/common/conf/url_conf.dart';
import 'package:starcitizen_doctor/common/helper/system_helper.dart';
import 'package:starcitizen_doctor/common/rust/api/win32_api.dart' as win32;
import 'package:starcitizen_doctor/common/utils/log.dart';
import 'package:starcitizen_doctor/widgets/widgets.dart';
import 'package:html/parser.dart' as html_parser;
@@ -44,39 +45,36 @@ class UpgradeDialogUI extends HookConsumerWidget {
return Material(
child: ContentDialog(
title:
Text(S.current.app_upgrade_title_new_version_found(targetVersion)),
constraints:
BoxConstraints(maxWidth: MediaQuery.of(context).size.width * .55),
title: Text(S.current.app_upgrade_title_new_version_found(targetVersion)),
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * .55),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.only(left: 24, right: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
if (description.value == null) ...[
Center(
child: Column(
children: [
const ProgressRing(),
const SizedBox(height: 16),
Text(S.current
.app_upgrade_info_getting_new_version_details)
],
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.only(left: 24, right: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
if (description.value == null) ...[
Center(
child: Column(
children: [
const ProgressRing(),
const SizedBox(height: 16),
Text(S.current.app_upgrade_info_getting_new_version_details),
],
),
),
)
] else
...makeMarkdownView(description.value!,
attachmentsUrl: URLConf.giteaAttachmentsUrl),
],
] else
...makeMarkdownView(description.value!, attachmentsUrl: URLConf.giteaAttachmentsUrl),
],
),
),
),
)),
),
if (isUsingDiversion.value) ...[
const SizedBox(height: 24),
GestureDetector(
@@ -84,13 +82,12 @@ class UpgradeDialogUI extends HookConsumerWidget {
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: .1),
borderRadius: BorderRadius.circular(7)),
color: Colors.white.withValues(alpha: .1),
borderRadius: BorderRadius.circular(7),
),
child: Text(
S.current.app_upgrade_info_update_server_tip,
style: TextStyle(
fontSize: 14,
color: Colors.white.withValues(alpha: .7)),
style: TextStyle(fontSize: 14, color: Colors.white.withValues(alpha: .7)),
),
),
),
@@ -99,14 +96,12 @@ class UpgradeDialogUI extends HookConsumerWidget {
const SizedBox(height: 24),
Row(
children: [
Text(progress.value == 100
? S.current.app_upgrade_info_installing
: S.current.app_upgrade_info_downloading(
progress.value.toStringAsFixed(2))),
Expanded(
child: ProgressBar(
value: progress.value == 100 ? null : progress.value,
)),
Text(
progress.value == 100
? S.current.app_upgrade_info_installing
: S.current.app_upgrade_info_downloading(progress.value.toStringAsFixed(2)),
),
Expanded(child: ProgressBar(value: progress.value == 100 ? null : progress.value)),
],
),
],
@@ -117,38 +112,40 @@ class UpgradeDialogUI extends HookConsumerWidget {
: [
if (downloadUrl.value.isNotEmpty)
FilledButton(
onPressed: () => _doUpgrade(
context,
appState,
isUpgrading,
appModel,
downloadUrl,
description,
isUsingDiversion,
progress),
child: Padding(
padding: const EdgeInsets.only(
top: 4, bottom: 4, left: 8, right: 8),
child: Text(S.current.app_upgrade_action_update_now),
)),
onPressed: () => _doUpgrade(
context,
appState,
isUpgrading,
appModel,
downloadUrl,
description,
isUsingDiversion,
progress,
),
child: Padding(
padding: const EdgeInsets.only(top: 4, bottom: 4, left: 8, right: 8),
child: Text(S.current.app_upgrade_action_update_now),
),
),
if (ConstConf.appVersionCode >= (minVersionCode ?? 0))
Button(
onPressed: () => _doCancel(context),
child: Padding(
padding: const EdgeInsets.only(
top: 4, bottom: 4, left: 8, right: 8),
child: Text(S.current.app_upgrade_action_next_time),
)),
onPressed: () => _doCancel(context),
child: Padding(
padding: const EdgeInsets.only(top: 4, bottom: 4, left: 8, right: 8),
child: Text(S.current.app_upgrade_action_next_time),
),
),
],
),
);
}
Future<void> _getUpdateInfo(
BuildContext context,
String targetVersion,
ValueNotifier<String?> description,
ValueNotifier<String> downloadUrl) async {
BuildContext context,
String targetVersion,
ValueNotifier<String?> description,
ValueNotifier<String> downloadUrl,
) async {
try {
final r = await Api.getAppReleaseDataByVersionName(targetVersion);
description.value = r["body"];
@@ -193,19 +190,19 @@ class UpgradeDialogUI extends HookConsumerWidget {
}
Future<void> _doUpgrade(
BuildContext context,
AppGlobalState appState,
ValueNotifier<bool> isUpgrading,
AppGlobalModel appModel,
ValueNotifier<String> downloadUrl,
ValueNotifier<String?> description,
ValueNotifier<bool> isUsingDiversion,
ValueNotifier<double> progress) async {
BuildContext context,
AppGlobalState appState,
ValueNotifier<bool> isUpgrading,
AppGlobalModel appModel,
ValueNotifier<String> downloadUrl,
ValueNotifier<String?> description,
ValueNotifier<bool> isUsingDiversion,
ValueNotifier<double> progress,
) async {
if (ConstConf.isMSE) {
launchUrlString("ms-windows-store://pdp/?productid=9NF3SWFWNKL1");
await Future.delayed(const Duration(seconds: 3));
if (ConstConf.appVersionCode <
(appState.networkVersionData?.minVersionCode ?? 0)) {
if (ConstConf.appVersionCode < (appState.networkVersionData?.minVersionCode ?? 0)) {
exit(0);
}
if (!context.mounted) return;
@@ -221,10 +218,10 @@ class UpgradeDialogUI extends HookConsumerWidget {
final dio = Dio();
if (diversionDownloadUrl.isNotEmpty) {
try {
final resp = await dio.head(diversionDownloadUrl,
options: Options(
sendTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 10)));
final resp = await dio.head(
diversionDownloadUrl,
options: Options(sendTimeout: const Duration(seconds: 10), receiveTimeout: const Duration(seconds: 10)),
);
if (resp.statusCode == 200) {
isUsingDiversion.value = true;
url = diversionDownloadUrl;
@@ -236,10 +233,13 @@ class UpgradeDialogUI extends HookConsumerWidget {
dPrint("diversionDownloadUrl err:$e");
}
}
await dio.download(url, fileName,
onReceiveProgress: (int count, int total) {
progress.value = (count / total) * 100;
});
await dio.download(
url,
fileName,
onReceiveProgress: (int count, int total) {
progress.value = (count / total) * 100;
},
);
} catch (_) {
isUpgrading.value = false;
progress.value = 0;
@@ -249,11 +249,7 @@ class UpgradeDialogUI extends HookConsumerWidget {
}
try {
final r = await (Process.run(
SystemHelper.powershellPath, ["start", fileName, "/SILENT"]));
if (r.stderr.toString().isNotEmpty) {
throw r.stderr;
}
await win32.startProcess(program: fileName, args: ["/SILENT"]);
exit(0);
} catch (_) {
isUpgrading.value = false;

View File

@@ -7,7 +7,9 @@ import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:starcitizen_doctor/api/analytics.dart';
import 'package:starcitizen_doctor/common/helper/system_helper.dart';
import 'package:starcitizen_doctor/common/io/rs_http.dart';
import 'package:starcitizen_doctor/common/rust/api/win32_api.dart' as win32;
import 'package:starcitizen_doctor/common/utils/async.dart';
import 'package:starcitizen_doctor/common/utils/base_utils.dart';
import 'package:starcitizen_doctor/common/utils/log.dart';
class HostsBoosterDialogUI extends HookConsumerWidget {
@@ -15,12 +17,8 @@ class HostsBoosterDialogUI extends HookConsumerWidget {
static final _hostsMap = {
"Recaptcha": ["www.recaptcha.net", "recaptcha.net"],
S.current.tools_hosts_info_rsi_official_website: [
"robertsspaceindustries.com"
],
S.current.tools_hosts_info_rsi_customer_service: [
"support.robertsspaceindustries.com"
],
S.current.tools_hosts_info_rsi_official_website: ["robertsspaceindustries.com"],
S.current.tools_hosts_info_rsi_customer_service: ["support.robertsspaceindustries.com"],
};
@override
@@ -31,9 +29,7 @@ class HostsBoosterDialogUI extends HookConsumerWidget {
doHost(BuildContext context) async {
if (workingMap.value.isEmpty) {
final hasTrue =
checkedMap.value.values.where((element) => element).firstOrNull !=
null;
final hasTrue = checkedMap.value.values.where((element) => element).firstOrNull != null;
if (!hasTrue) {
for (var k in _hostsMap.keys) {
checkedMap.value[k] = true;
@@ -59,32 +55,29 @@ class HostsBoosterDialogUI extends HookConsumerWidget {
}, []);
return ContentDialog(
constraints:
BoxConstraints(maxWidth: MediaQuery.of(context).size.width * .55),
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * .55),
title: Row(
children: [
IconButton(
icon: const Icon(
FluentIcons.back,
size: 22,
),
onPressed:
workingText.value.isEmpty ? Navigator.of(context).pop : null),
icon: const Icon(FluentIcons.back, size: 22),
onPressed: workingText.value.isEmpty ? Navigator.of(context).pop : null,
),
const SizedBox(width: 12),
Text(S.current.tools_hosts_info_hosts_acceleration),
const Spacer(),
Button(
onPressed: () => _openHostsFile(context),
child: Padding(
padding: const EdgeInsets.all(3),
child: Row(
children: [
const Icon(FluentIcons.open_file),
const SizedBox(width: 6),
Text(S.current.tools_hosts_info_open_hosts_file),
],
),
))
onPressed: () => _openHostsFile(context),
child: Padding(
padding: const EdgeInsets.all(3),
child: Row(
children: [
const Icon(FluentIcons.open_file),
const SizedBox(width: 6),
Text(S.current.tools_hosts_info_open_hosts_file),
],
),
),
),
],
),
content: AnimatedSize(
@@ -111,10 +104,8 @@ class HostsBoosterDialogUI extends HookConsumerWidget {
padding: const EdgeInsets.all(6),
physics: const NeverScrollableScrollPhysics(),
itemBuilder: (BuildContext context, int index) {
final isEnable =
checkedMap.value[_hostsMap.keys.elementAt(index)] ?? false;
final workingState =
workingMap.value[_hostsMap.keys.elementAt(index)];
final isEnable = checkedMap.value[_hostsMap.keys.elementAt(index)] ?? false;
final workingState = workingMap.value[_hostsMap.keys.elementAt(index)];
return Container(
padding: const EdgeInsets.all(12),
margin: const EdgeInsets.only(bottom: 12),
@@ -124,23 +115,16 @@ class HostsBoosterDialogUI extends HookConsumerWidget {
),
child: Row(
children: [
if (workingState == null)
Icon(FontAwesomeIcons.xmark,
size: 24, color: Colors.red),
if (workingState == 0)
const SizedBox(
width: 24, height: 24, child: ProgressRing()),
if (workingState == 1)
Icon(FontAwesomeIcons.check,
size: 24, color: Colors.green),
if (workingState == null) Icon(FontAwesomeIcons.xmark, size: 24, color: Colors.red),
if (workingState == 0) const SizedBox(width: 24, height: 24, child: ProgressRing()),
if (workingState == 1) Icon(FontAwesomeIcons.check, size: 24, color: Colors.green),
const SizedBox(width: 24),
const SizedBox(width: 12),
Text(_hostsMap.keys.elementAt(index)),
const Spacer(),
ToggleSwitch(
onChanged: (value) {
checkedMap.value[_hostsMap.keys.elementAt(index)] =
value;
checkedMap.value[_hostsMap.keys.elementAt(index)] = value;
checkedMap.value = Map.from(checkedMap.value);
},
checked: isEnable,
@@ -156,8 +140,7 @@ class HostsBoosterDialogUI extends HookConsumerWidget {
height: 86,
child: Column(
children: [
const SizedBox(
height: 42, width: 42, child: ProgressRing()),
const SizedBox(height: 42, width: 42, child: ProgressRing()),
const SizedBox(height: 12),
Text(workingText.value),
],
@@ -169,10 +152,8 @@ class HostsBoosterDialogUI extends HookConsumerWidget {
child: FilledButton(
onPressed: () => doHost(context),
child: Padding(
padding: const EdgeInsets.only(
top: 3, bottom: 3, left: 12, right: 12),
child: Text(
S.current.tools_hosts_action_one_click_acceleration),
padding: const EdgeInsets.only(top: 3, bottom: 3, left: 12, right: 12),
child: Text(S.current.tools_hosts_action_one_click_acceleration),
),
),
),
@@ -183,17 +164,19 @@ class HostsBoosterDialogUI extends HookConsumerWidget {
}
Future<void> _openHostsFile(BuildContext context) async {
// 使用管理员权限调用记事本${S.current.tools_hosts_info_open_hosts_file}
Process.run(SystemHelper.powershellPath, [
"-Command",
"Start-Process notepad.exe -Verb runAs -ArgumentList ${SystemHelper.getHostsFilePath()}"
// ignore: use_build_context_synchronously
]).unwrap(context: context);
// 使用管理员权限调用记事本
try {
await win32.runAsAdmin(program: "notepad.exe", args: SystemHelper.getHostsFilePath());
} catch (e) {
if (!context.mounted) return;
showToast(context, "Failed to open hosts file: $e");
}
}
Future<Map<String, String>> _doCheckDns(
ValueNotifier<Map<String, int?>> workingMap,
ValueNotifier<Map<String, bool>> checkedMap) async {
ValueNotifier<Map<String, int?>> workingMap,
ValueNotifier<Map<String, bool>> checkedMap,
) async {
Map<String, String> result = {};
final trueLen = checkedMap.value.values.where((element) => element).length;
if (trueLen == 0) {
@@ -207,36 +190,37 @@ class HostsBoosterDialogUI extends HookConsumerWidget {
}
workingMap.value[siteName] = 0;
workingMap.value = Map.from(workingMap.value);
RSHttp.dnsLookupIps(siteHost).then((ips) async {
int tryCount = ips.length;
try {
for (var ip in ips) {
final resp =
await RSHttp.head("https://$siteHost", withIpAddress: ip);
dPrint(
"[HostsBooster] host== $siteHost ip== $ip resp== ${resp.headers}");
if (resp.headers.isNotEmpty) {
if (result[siteName] == null) {
result[siteName] = ip;
workingMap.value[siteName] = 1;
workingMap.value = Map.from(workingMap.value);
break;
RSHttp.dnsLookupIps(siteHost).then(
(ips) async {
int tryCount = ips.length;
try {
for (var ip in ips) {
final resp = await RSHttp.head("https://$siteHost", withIpAddress: ip);
dPrint("[HostsBooster] host== $siteHost ip== $ip resp== ${resp.headers}");
if (resp.headers.isNotEmpty) {
if (result[siteName] == null) {
result[siteName] = ip;
workingMap.value[siteName] = 1;
workingMap.value = Map.from(workingMap.value);
break;
}
}
}
} catch (e) {
tryCount--;
if (tryCount == 0) {
workingMap.value[siteName] = null;
workingMap.value = Map.from(workingMap.value);
result[siteName] = "";
}
}
} catch (e) {
tryCount--;
if (tryCount == 0) {
workingMap.value[siteName] = null;
workingMap.value = Map.from(workingMap.value);
result[siteName] = "";
}
}
}, onError: (e) {
workingMap.value[siteName] = null;
workingMap.value = Map.from(workingMap.value);
result[siteName] = "";
});
},
onError: (e) {
workingMap.value[siteName] = null;
workingMap.value = Map.from(workingMap.value);
result[siteName] = "";
},
);
}
while (true) {
await Future.delayed(const Duration(milliseconds: 100));
@@ -265,16 +249,17 @@ class HostsBoosterDialogUI extends HookConsumerWidget {
final domains = _hostsMap[kv.key] ?? <String>[];
for (var domain in domains) {
if (kv.value != "") {
newHostsFileLines
.add("${kv.value} $domain #StarCitizenToolBox");
newHostsFileLines.add("${kv.value} $domain #StarCitizenToolBox");
}
}
}
await hostsFile.writeAsString(newHostsFileLines.join("\n"), flush: true);
}
Future<void> _readHostsState(ValueNotifier<Map<String, int?>> workingMap,
ValueNotifier<Map<String, bool>> checkedMap) async {
Future<void> _readHostsState(
ValueNotifier<Map<String, int?>> workingMap,
ValueNotifier<Map<String, bool>> checkedMap,
) async {
workingMap.value.clear();
final hostsFile = File(SystemHelper.getHostsFilePath());
final hostsFileString = await hostsFile.readAsString();