feat: VehicleSorting

This commit is contained in:
xkeyC 2025-06-01 16:36:10 +08:00
parent 4679d559d9
commit 488ad2a485
11 changed files with 530 additions and 279 deletions

View File

@ -11,6 +11,9 @@ class ConstConf {
"HOTFIX", "HOTFIX",
]; ];
static const isMSE = String.fromEnvironment("MSE", defaultValue: "false") == "true"; static const isMSE = String.fromEnvironment("MSE", defaultValue: "false") == "true";
static const win32AppId = isMSE
? "56575xkeyC.MSE_bsn1nexg8e4qe!starcitizendoctor"
: "{6D809377-6AF0-444B-8957-A3773F02200E}\\Starcitizen_Doctor\\starcitizen_doctor.exe";
static const dohAddress = "https://223.6.6.6/resolve"; static const dohAddress = "https://223.6.6.6/resolve";
static const inputMethodServerPort = 59399; static const inputMethodServerPort = 59399;
} }

View File

@ -76,17 +76,15 @@ class HomeUIModel extends _$HomeUIModel {
} }
Future<void> reScanPath() async { Future<void> reScanPath() async {
state = state.copyWith( state = state.copyWith(scInstalledPath: "not_install", lastScreenInfo: S.current.home_action_info_scanning);
scInstalledPath: "not_install",
lastScreenInfo: S.current.home_action_info_scanning);
try { try {
final listData = await SCLoggerHelper.getLauncherLogList(); final listData = await SCLoggerHelper.getLauncherLogList();
if (listData == null) { if (listData == null) {
state = state.copyWith(scInstalledPath: "not_install"); state = state.copyWith(scInstalledPath: "not_install");
return; return;
} }
final scInstallPaths = await SCLoggerHelper.getGameInstallPath(listData, final scInstallPaths =
withVersion: AppConf.gameChannels, checkExists: true); await SCLoggerHelper.getGameInstallPath(listData, withVersion: AppConf.gameChannels, checkExists: true);
String scInstalledPath = "not_install"; String scInstalledPath = "not_install";
@ -95,17 +93,13 @@ class HomeUIModel extends _$HomeUIModel {
scInstalledPath = scInstallPaths.first; scInstalledPath = scInstallPaths.first;
} }
} }
final lastScreenInfo = S.current final lastScreenInfo =
.home_action_info_scan_complete_valid_directories_found( S.current.home_action_info_scan_complete_valid_directories_found(scInstallPaths.length.toString());
scInstallPaths.length.toString());
state = state.copyWith( state = state.copyWith(
scInstalledPath: scInstalledPath, scInstalledPath: scInstalledPath, scInstallPaths: scInstallPaths, lastScreenInfo: lastScreenInfo);
scInstallPaths: scInstallPaths,
lastScreenInfo: lastScreenInfo);
} catch (e) { } catch (e) {
state = state.copyWith( state = state.copyWith(
scInstalledPath: "not_install", scInstalledPath: "not_install", lastScreenInfo: S.current.home_action_info_log_file_parse_fail);
lastScreenInfo: S.current.home_action_info_log_file_parse_fail);
AnalyticsApi.touch("error_launchLogs"); AnalyticsApi.touch("error_launchLogs");
// showToast(context!, // showToast(context!,
// "${S.current.home_action_info_log_file_parse_fail} \n请关闭游戏退出RSI启动器后重试若仍有问题请使用工具箱中的 RSI Launcher log 修复。"); // "${S.current.home_action_info_log_file_parse_fail} \n请关闭游戏退出RSI启动器后重试若仍有问题请使用工具箱中的 RSI Launcher log 修复。");
@ -134,14 +128,11 @@ class HomeUIModel extends _$HomeUIModel {
// ignore: avoid_build_context_in_providers // ignore: avoid_build_context_in_providers
Future<void> goWebView(BuildContext context, String title, String url, Future<void> goWebView(BuildContext context, String title, String url,
{bool useLocalization = false, {bool useLocalization = false, bool loginMode = false, RsiLoginCallback? rsiLoginCallback}) async {
bool loginMode = false,
RsiLoginCallback? rsiLoginCallback}) async {
if (useLocalization) { if (useLocalization) {
const tipVersion = 2; const tipVersion = 2;
final box = await Hive.openBox("app_conf"); final box = await Hive.openBox("app_conf");
final skip = final skip = await box.get("skip_web_localization_tip_version", defaultValue: 0);
await box.get("skip_web_localization_tip_version", defaultValue: 0);
if (skip != tipVersion) { if (skip != tipVersion) {
if (!context.mounted) return; if (!context.mounted) return;
final ok = await showConfirmDialogs( final ok = await showConfirmDialogs(
@ -151,8 +142,7 @@ class HomeUIModel extends _$HomeUIModel {
S.current.home_action_info_web_localization_plugin_disclaimer, S.current.home_action_info_web_localization_plugin_disclaimer,
style: const TextStyle(fontSize: 16), style: const TextStyle(fontSize: 16),
), ),
constraints: BoxConstraints( constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * .6));
maxWidth: MediaQuery.of(context).size.width * .6));
if (!ok) { if (!ok) {
if (loginMode) { if (loginMode) {
rsiLoginCallback?.call(null, false); rsiLoginCallback?.call(null, false);
@ -164,19 +154,14 @@ class HomeUIModel extends _$HomeUIModel {
} }
if (!await WebviewWindow.isWebviewAvailable()) { if (!await WebviewWindow.isWebviewAvailable()) {
if (!context.mounted) return; if (!context.mounted) return;
showToast( showToast(context, S.current.home_login_action_title_need_webview2_runtime);
context, S.current.home_login_action_title_need_webview2_runtime); launchUrlString("https://developer.microsoft.com/en-us/microsoft-edge/webview2/");
launchUrlString(
"https://developer.microsoft.com/en-us/microsoft-edge/webview2/");
return; return;
} }
if (!context.mounted) return; if (!context.mounted) return;
final webViewModel = WebViewModel(context, final webViewModel = WebViewModel(context, loginMode: loginMode, loginCallback: rsiLoginCallback);
loginMode: loginMode, loginCallback: rsiLoginCallback);
if (useLocalization) { if (useLocalization) {
state = state.copyWith( state = state.copyWith(isFixing: true, isFixingString: S.current.home_action_info_initializing_resources);
isFixing: true,
isFixingString: S.current.home_action_info_initializing_resources);
try { try {
await webViewModel.initLocalization(state.webLocalizationVersionsData!); await webViewModel.initLocalization(state.webLocalizationVersionsData!);
} catch (e) { } catch (e) {
@ -236,10 +221,8 @@ class HomeUIModel extends _$HomeUIModel {
} }
} }
final appWebLocalizationVersionsData = final appWebLocalizationVersionsData = AppWebLocalizationVersionsData.fromJson(
AppWebLocalizationVersionsData.fromJson(json.decode( json.decode((await RSHttp.getText("${URLConf.webTranslateHomeUrl}/versions.json"))));
(await RSHttp.getText(
"${URLConf.webTranslateHomeUrl}/versions.json"))));
final countdownFestivalListData = await Api.getFestivalCountdownList(); final countdownFestivalListData = await Api.getFestivalCountdownList();
state = state.copyWith( state = state.copyWith(
webLocalizationVersionsData: appWebLocalizationVersionsData, webLocalizationVersionsData: appWebLocalizationVersionsData,
@ -284,20 +267,16 @@ class HomeUIModel extends _$HomeUIModel {
state = state.copyWith(localizationUpdateInfo: null); state = state.copyWith(localizationUpdateInfo: null);
return; return;
} }
state = state = state.copyWith(localizationUpdateInfo: MapEntry(updates.first, true));
state.copyWith(localizationUpdateInfo: MapEntry(updates.first, true));
if (_appUpdateTimer != null) { if (_appUpdateTimer != null) {
_appUpdateTimer?.cancel(); _appUpdateTimer?.cancel();
_appUpdateTimer = null; _appUpdateTimer = null;
// //
await win32.sendNotify( await win32.sendNotify(
summary: S.current.home_localization_new_version_available, summary: S.current.home_localization_new_version_available,
body: body: S.current.home_localization_new_version_installed(updates.first),
S.current.home_localization_new_version_installed(updates.first),
appName: S.current.home_title_app_name, appName: S.current.home_title_app_name,
appId: ConstConf.isMSE appId: ConstConf.win32AppId);
? "56575xkeyC.MSE_bsn1nexg8e4qe!starcitizendoctor"
: "{6D809377-6AF0-444B-8957-A3773F02200E}\\Starcitizen_Doctor\\starcitizen_doctor.exe");
} }
} }
@ -310,25 +289,17 @@ class HomeUIModel extends _$HomeUIModel {
if (ConstConf.isMSE) { if (ConstConf.isMSE) {
if (state.isCurGameRunning) { if (state.isCurGameRunning) {
await Process.run( await Process.run(SystemHelper.powershellPath, ["ps \"StarCitizen\" | kill"]);
SystemHelper.powershellPath, ["ps \"StarCitizen\" | kill"]);
return; return;
} }
AnalyticsApi.touch("gameLaunch"); AnalyticsApi.touch("gameLaunch");
showDialog( showDialog(context: context, dismissWithEsc: false, builder: (context) => HomeGameLoginDialogUI(context));
context: context,
dismissWithEsc: false,
builder: (context) => HomeGameLoginDialogUI(context));
} else { } else {
final ok = await showConfirmDialogs( final ok = await showConfirmDialogs(
context, context, S.current.home_info_one_click_launch_warning, Text(S.current.home_info_account_security_warning),
S.current.home_info_one_click_launch_warning, confirm: S.current.home_action_install_microsoft_store_version, cancel: S.current.home_action_cancel);
Text(S.current.home_info_account_security_warning),
confirm: S.current.home_action_install_microsoft_store_version,
cancel: S.current.home_action_cancel);
if (ok == true) { if (ok == true) {
await launchUrlString( await launchUrlString("https://apps.microsoft.com/detail/9NF3SWFWNKL1?launch=true");
"https://apps.microsoft.com/detail/9NF3SWFWNKL1?launch=true");
await Future.delayed(const Duration(seconds: 2)); await Future.delayed(const Duration(seconds: 2));
exit(0); exit(0);
} }
@ -338,9 +309,7 @@ class HomeUIModel extends _$HomeUIModel {
void onChangeInstallPath(String? value) { void onChangeInstallPath(String? value) {
if (value == null) return; if (value == null) return;
state = state.copyWith(scInstalledPath: value); state = state.copyWith(scInstalledPath: value);
ref ref.read(localizationUIModelProvider.notifier).onChangeGameInstallPath(value);
.read(localizationUIModelProvider.notifier)
.onChangeGameInstallPath(value);
} }
doLaunchGame( doLaunchGame(
@ -359,16 +328,8 @@ class HomeUIModel extends _$HomeUIModel {
result = await Process.run(launchExe, args); result = await Process.run(launchExe, args);
} else { } else {
dPrint("set Affinity === $processorAffinity launchExe === $launchExe"); dPrint("set Affinity === $processorAffinity launchExe === $launchExe");
result = await Process.run("cmd.exe", [ result = await Process.run(
'/C', "cmd.exe", ['/C', 'Start', '"StarCitizen"', '/High', '/Affinity', processorAffinity, launchExe, ...args]);
'Start',
'"StarCitizen"',
'/High',
'/Affinity',
processorAffinity,
launchExe,
...args
]);
} }
dPrint('Exit code: ${result.exitCode}'); dPrint('Exit code: ${result.exitCode}');
dPrint('stdout: ${result.stdout}'); dPrint('stdout: ${result.stdout}');
@ -394,12 +355,8 @@ class HomeUIModel extends _$HomeUIModel {
result.exitCode.toString(), result.exitCode.toString(),
result.stdout ?? "", result.stdout ?? "",
result.stderr ?? "", result.stderr ?? "",
exitInfo == null exitInfo == null ? S.current.home_action_info_unknown_error : exitInfo.key,
? S.current.home_action_info_unknown_error hasUrl ? S.current.home_action_info_check_web_link : exitInfo?.value ?? ""));
: exitInfo.key,
hasUrl
? S.current.home_action_info_check_web_link
: exitInfo?.value ?? ""));
if (hasUrl) { if (hasUrl) {
await Future.delayed(const Duration(seconds: 3)); await Future.delayed(const Duration(seconds: 3));
launchUrlString(exitInfo!.value); launchUrlString(exitInfo!.value);

View File

@ -6,7 +6,7 @@ part of 'home_ui_model.dart';
// RiverpodGenerator // RiverpodGenerator
// ************************************************************************** // **************************************************************************
String _$homeUIModelHash() => r'3ff5a689cae80acdaf95ee823da9b86615bed95f'; String _$homeUIModelHash() => r'8bde330ebc2cd73f76d2d49df8b328f301d42e44';
/// See also [HomeUIModel]. /// See also [HomeUIModel].
@ProviderFor(HomeUIModel) @ProviderFor(HomeUIModel)

View File

@ -33,7 +33,7 @@ class InputMethodDialogUIModel extends _$InputMethodDialogUIModel {
return state; return state;
} }
_init({bool skipUpdate = false}) async { Future<void> _init({bool skipUpdate = false}) async {
final localizationState = ref.read(localizationUIModelProvider); final localizationState = ref.read(localizationUIModelProvider);
final localizationModel = ref.read(localizationUIModelProvider.notifier); final localizationModel = ref.read(localizationUIModelProvider.notifier);
if (localizationState.installedCommunityInputMethodSupportVersion == null) { if (localizationState.installedCommunityInputMethodSupportVersion == null) {

View File

@ -7,7 +7,7 @@ part of 'input_method_dialog_ui_model.dart';
// ************************************************************************** // **************************************************************************
String _$inputMethodDialogUIModelHash() => String _$inputMethodDialogUIModelHash() =>
r'397b36296183404c07298d83c14f4bce590375fc'; r'7086eb73fc75e4a79d1490646b25cd23ac611c80';
/// See also [InputMethodDialogUIModel]. /// See also [InputMethodDialogUIModel].
@ProviderFor(InputMethodDialogUIModel) @ProviderFor(InputMethodDialogUIModel)

View File

@ -45,12 +45,11 @@ extension AdvancedLocalizationUIStateEx on AdvancedLocalizationUIState {
Map<AppAdvancedLocalizationClassKeysDataMode, String> get typeNames => { Map<AppAdvancedLocalizationClassKeysDataMode, String> get typeNames => {
AppAdvancedLocalizationClassKeysDataMode.localization: AppAdvancedLocalizationClassKeysDataMode.localization:
S.current.home_localization_advanced_action_mod_change_localization, S.current.home_localization_advanced_action_mod_change_localization,
AppAdvancedLocalizationClassKeysDataMode.unLocalization: S.current AppAdvancedLocalizationClassKeysDataMode.unLocalization:
.home_localization_advanced_action_mod_change_un_localization, S.current.home_localization_advanced_action_mod_change_un_localization,
AppAdvancedLocalizationClassKeysDataMode.mixed: AppAdvancedLocalizationClassKeysDataMode.mixed: S.current.home_localization_advanced_action_mod_change_mixed,
S.current.home_localization_advanced_action_mod_change_mixed, AppAdvancedLocalizationClassKeysDataMode.mixedNewline:
AppAdvancedLocalizationClassKeysDataMode.mixedNewline: S S.current.home_localization_advanced_action_mod_change_mixed_newline,
.current.home_localization_advanced_action_mod_change_mixed_newline,
}; };
} }
@ -65,14 +64,11 @@ class AdvancedLocalizationUIModel extends _$AdvancedLocalizationUIModel {
return state; return state;
} }
Future<void> _init(LocalizationUIState localizationUIState, Future<void> _init(LocalizationUIState localizationUIState, LocalizationUIModel localizationUIModel) async {
LocalizationUIModel localizationUIModel) async { final (p4kGlobalIni, serverGlobalIni) = await _readIni(localizationUIState, localizationUIModel);
final (p4kGlobalIni, serverGlobalIni) =
await _readIni(localizationUIState, localizationUIModel);
final ald = await _readClassJson(); final ald = await _readClassJson();
if (ald.classKeys == null) return; if (ald.classKeys == null) return;
state = state.copyWith( state = state.copyWith(workingText: S.current.home_localization_advanced_msg_classifying);
workingText: S.current.home_localization_advanced_msg_classifying);
final m = await compute(_doClassIni, ( final m = await compute(_doClassIni, (
ald, ald,
p4kGlobalIni, p4kGlobalIni,
@ -133,10 +129,8 @@ class AdvancedLocalizationUIModel extends _$AdvancedLocalizationUIModel {
final p4kIniMap = readIniAsMap(p4kGlobalIni); final p4kIniMap = readIniAsMap(p4kGlobalIni);
final serverIniMap = readIniAsMap(serverGlobalIni); final serverIniMap = readIniAsMap(serverGlobalIni);
var regexList = classMap.values var regexList =
.expand((c) => classMap.values.expand((c) => c.keys!.map((k) => MapEntry(c, RegExp(k, caseSensitive: false)))).toList();
c.keys!.map((k) => MapEntry(c, RegExp(k, caseSensitive: false))))
.toList();
iniKeysLoop: iniKeysLoop:
for (var p4kIniKey in p4kIniMap.keys) { for (var p4kIniKey in p4kIniMap.keys) {
@ -185,39 +179,31 @@ class AdvancedLocalizationUIModel extends _$AdvancedLocalizationUIModel {
return AppAdvancedLocalizationData.fromJson(advancedLocalizationJsonData); return AppAdvancedLocalizationData.fromJson(advancedLocalizationJsonData);
} }
Future<(String, String)> _readIni(LocalizationUIState localizationUIState, Future<(String, String)> _readIni(
LocalizationUIModel localizationUIModel) async { LocalizationUIState localizationUIState, LocalizationUIModel localizationUIModel) async {
final homeUIState = ref.read(homeUIModelProvider); final homeUIState = ref.read(homeUIModelProvider);
final gameDir = homeUIState.scInstalledPath; final gameDir = homeUIState.scInstalledPath;
if (gameDir == null) return ("", ""); if (gameDir == null) return ("", "");
state = state.copyWith( state = state.copyWith(workingText: S.current.home_localization_advanced_msg_reading_p4k);
workingText: S.current.home_localization_advanced_msg_reading_p4k);
final p4kGlobalIni = await readEnglishInI(gameDir); final p4kGlobalIni = await readEnglishInI(gameDir);
dPrint("read p4kGlobalIni => ${p4kGlobalIni.length}"); dPrint("read p4kGlobalIni => ${p4kGlobalIni.length}");
state = state.copyWith( state = state.copyWith(workingText: S.current.home_localization_advanced_msg_reading_server_localization_text);
workingText: S.current
.home_localization_advanced_msg_reading_server_localization_text);
if (state.customizeGlobalIni != null) { if (state.customizeGlobalIni != null) {
final apiLocalizationData = ScLocalizationData( final apiLocalizationData =
versionName: S.current.localization_info_custom_files, ScLocalizationData(versionName: S.current.localization_info_custom_files, info: "Customize");
info: "Customize");
state = state.copyWith(apiLocalizationData: apiLocalizationData); state = state.copyWith(apiLocalizationData: apiLocalizationData);
return (p4kGlobalIni, state.customizeGlobalIni!); return (p4kGlobalIni, state.customizeGlobalIni!);
} else { } else {
final apiLocalizationData = final apiLocalizationData = localizationUIState.apiLocalizationData?.values.firstOrNull;
localizationUIState.apiLocalizationData?.values.firstOrNull;
if (apiLocalizationData == null) return ("", ""); if (apiLocalizationData == null) return ("", "");
final file = File( final file =
"${localizationUIModel.getDownloadDir().absolute.path}\\${apiLocalizationData.versionName}.sclang"); File("${localizationUIModel.getDownloadDir().absolute.path}\\${apiLocalizationData.versionName}.sclang");
if (!await file.exists()) { if (!await file.exists()) {
await localizationUIModel.downloadLocalizationFile( await localizationUIModel.downloadLocalizationFile(file, apiLocalizationData);
file, apiLocalizationData);
} }
state = state.copyWith(apiLocalizationData: apiLocalizationData); state = state.copyWith(apiLocalizationData: apiLocalizationData);
final serverGlobalIni = final serverGlobalIni = (await compute(LocalizationUIModel.readArchive, file.absolute.path)).toString();
(await compute(LocalizationUIModel.readArchive, file.absolute.path))
.toString();
dPrint("read serverGlobalIni => ${serverGlobalIni.length}"); dPrint("read serverGlobalIni => ${serverGlobalIni.length}");
return (p4kGlobalIni, serverGlobalIni); return (p4kGlobalIni, serverGlobalIni);
} }
@ -225,17 +211,10 @@ class AdvancedLocalizationUIModel extends _$AdvancedLocalizationUIModel {
Future<String> readEnglishInI(String gameDir) async { Future<String> readEnglishInI(String gameDir) async {
try { try {
var data = await Unp4kCModel.unp4kTools( var data = await Unp4kCModel.unp4kTools(appGlobalState.applicationBinaryModuleDir!,
appGlobalState.applicationBinaryModuleDir!, [ ["extract_memory", "$gameDir\\Data.p4k", "Data\\Localization\\english\\global.ini"]);
"extract_memory",
"$gameDir\\Data.p4k",
"Data\\Localization\\english\\global.ini"
]);
// remove bom // remove bom
if (data.length > 3 && if (data.length > 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF) {
data[0] == 0xEF &&
data[1] == 0xBB &&
data[2] == 0xBF) {
data = data.sublist(3); data = data.sublist(3);
} }
final iniData = String.fromCharCodes(data); final iniData = String.fromCharCodes(data);
@ -253,13 +232,11 @@ class AdvancedLocalizationUIModel extends _$AdvancedLocalizationUIModel {
return ""; return "";
} }
onChangeMod(AppAdvancedLocalizationClassKeysData item, Future<void> onChangeMod(AppAdvancedLocalizationClassKeysData item, AppAdvancedLocalizationClassKeysDataMode mode) async {
AppAdvancedLocalizationClassKeysDataMode mode) async {
if (item.lockMod) return; if (item.lockMod) return;
item.mode = mode; item.mode = mode;
item.isWorking = true; item.isWorking = true;
final classMap = final classMap = Map<String, AppAdvancedLocalizationClassKeysData>.from(state.classMap!);
Map<String, AppAdvancedLocalizationClassKeysData>.from(state.classMap!);
classMap[item.id!] = item; classMap[item.id!] = item;
state = state.copyWith(classMap: classMap); state = state.copyWith(classMap: classMap);
@ -276,12 +253,10 @@ class AdvancedLocalizationUIModel extends _$AdvancedLocalizationUIModel {
newValuesMap[kv.key] = p4kIniMap[kv.key] ?? ""; newValuesMap[kv.key] = p4kIniMap[kv.key] ?? "";
break; break;
case AppAdvancedLocalizationClassKeysDataMode.mixed: case AppAdvancedLocalizationClassKeysDataMode.mixed:
newValuesMap[kv.key] = newValuesMap[kv.key] = "${serverIniMap[kv.key]} [${p4kIniMap[kv.key]}]";
"${serverIniMap[kv.key]} [${p4kIniMap[kv.key]}]";
break; break;
case AppAdvancedLocalizationClassKeysDataMode.mixedNewline: case AppAdvancedLocalizationClassKeysDataMode.mixedNewline:
newValuesMap[kv.key] = newValuesMap[kv.key] = "${serverIniMap[kv.key]}\\n${p4kIniMap[kv.key]}";
"${serverIniMap[kv.key]}\\n${p4kIniMap[kv.key]}";
break; break;
} }
await Future.delayed(Duration.zero); await Future.delayed(Duration.zero);
@ -292,11 +267,10 @@ class AdvancedLocalizationUIModel extends _$AdvancedLocalizationUIModel {
state = state.copyWith(classMap: classMap); state = state.copyWith(classMap: classMap);
} }
Future<bool> doInstall({bool isEnableCommunityInputMethod = false}) async { // ignore: avoid_build_context_in_providers
Future<bool> doInstall(BuildContext context, {bool isEnableCommunityInputMethod = false}) async {
AnalyticsApi.touch("advanced_localization_apply"); AnalyticsApi.touch("advanced_localization_apply");
state = state.copyWith( state = state.copyWith(workingText: S.current.home_localization_advanced_msg_gen_localization_text);
workingText:
S.current.home_localization_advanced_msg_gen_localization_text);
final classMap = state.classMap!; final classMap = state.classMap!;
final globalIni = StringBuffer(); final globalIni = StringBuffer();
for (var item in classMap.values) { for (var item in classMap.values) {
@ -305,15 +279,11 @@ class AdvancedLocalizationUIModel extends _$AdvancedLocalizationUIModel {
await Future.delayed(Duration.zero); await Future.delayed(Duration.zero);
} }
} }
state = state.copyWith( state = state.copyWith(workingText: S.current.home_localization_advanced_msg_gen_localization_install);
workingText:
S.current.home_localization_advanced_msg_gen_localization_install);
final localizationUIModel = ref.read(localizationUIModelProvider.notifier); final localizationUIModel = ref.read(localizationUIModelProvider.notifier);
if (!context.mounted) return false;
await localizationUIModel.installFormString( await localizationUIModel.installFormString(globalIni, state.apiLocalizationData?.versionName ?? "-",
globalIni, state.apiLocalizationData?.versionName ?? "-", advanced: true, isEnableCommunityInputMethod: isEnableCommunityInputMethod, context: context);
advanced: true,
isEnableCommunityInputMethod: isEnableCommunityInputMethod);
state = state.copyWith(workingText: ""); state = state.copyWith(workingText: "");
return true; return true;
} }
@ -321,9 +291,8 @@ class AdvancedLocalizationUIModel extends _$AdvancedLocalizationUIModel {
// ignore: avoid_build_context_in_providers // ignore: avoid_build_context_in_providers
Future<void> onInstall(BuildContext context) async { Future<void> onInstall(BuildContext context) async {
var isEnableCommunityInputMethod = true; var isEnableCommunityInputMethod = true;
final userOK = await showConfirmDialogs( final userOK =
context, S.current.input_method_confirm_install_advanced_localization, await showConfirmDialogs(context, S.current.input_method_confirm_install_advanced_localization, HookConsumer(
HookConsumer(
builder: (BuildContext context, WidgetRef ref, Widget? child) { builder: (BuildContext context, WidgetRef ref, Widget? child) {
final globalIni = useState<StringBuffer?>(null); final globalIni = useState<StringBuffer?>(null);
final enableCommunityInputMethod = useState(true); final enableCommunityInputMethod = useState(true);
@ -354,13 +323,10 @@ class AdvancedLocalizationUIModel extends _$AdvancedLocalizationUIModel {
? makeLoading(context) ? makeLoading(context)
: CodeEditor( : CodeEditor(
readOnly: true, readOnly: true,
controller: CodeLineEditingController.fromText( controller: CodeLineEditingController.fromText(globalIni.value!.toString()),
globalIni.value!.toString()),
style: CodeEditorStyle( style: CodeEditorStyle(
codeTheme: CodeHighlightTheme( codeTheme: CodeHighlightTheme(
languages: { languages: {'ini': CodeHighlightThemeMode(mode: langIni)},
'ini': CodeHighlightThemeMode(mode: langIni)
},
theme: vs2015Theme, theme: vs2015Theme,
), ),
), ),
@ -376,13 +342,12 @@ class AdvancedLocalizationUIModel extends _$AdvancedLocalizationUIModel {
Spacer(), Spacer(),
ToggleSwitch( ToggleSwitch(
checked: enableCommunityInputMethod.value, checked: enableCommunityInputMethod.value,
onChanged: onChanged: localizationState.communityInputMethodLanguageData == null
localizationState.communityInputMethodLanguageData == null ? null
? null : (v) {
: (v) { isEnableCommunityInputMethod = v;
isEnableCommunityInputMethod = v; enableCommunityInputMethod.value = v;
enableCommunityInputMethod.value = v; },
},
) )
], ],
) )
@ -390,12 +355,12 @@ class AdvancedLocalizationUIModel extends _$AdvancedLocalizationUIModel {
); );
}, },
), ),
constraints: BoxConstraints( constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * .8, maxWidth: MediaQuery.of(context).size.width * .8,
)); ));
if (userOK) { if (userOK) {
await doInstall( if (!context.mounted) return;
isEnableCommunityInputMethod: isEnableCommunityInputMethod); await doInstall(context, isEnableCommunityInputMethod: isEnableCommunityInputMethod);
} }
} }
} }

View File

@ -7,7 +7,7 @@ part of 'advanced_localization_ui_model.dart';
// ************************************************************************** // **************************************************************************
String _$advancedLocalizationUIModelHash() => String _$advancedLocalizationUIModelHash() =>
r'52d4f40f20e9f4d2f34fae7d0378acb31cf681ac'; r'2f890c854bc56e506c441acabc2014438a163617';
/// See also [AdvancedLocalizationUIModel]. /// See also [AdvancedLocalizationUIModel].
@ProviderFor(AdvancedLocalizationUIModel) @ProviderFor(AdvancedLocalizationUIModel)

View File

@ -438,10 +438,12 @@ class LocalizationDialogUI extends HookConsumerWidget {
builder: (BuildContext context) => const LocalizationFromFileDialogUI(), builder: (BuildContext context) => const LocalizationFromFileDialogUI(),
); );
if (sb is (StringBuffer, bool)) { if (sb is (StringBuffer, bool)) {
if (!context.mounted) return;
await model.installFormString( await model.installFormString(
sb.$1, sb.$1,
S.current.localization_info_custom_files, S.current.localization_info_custom_files,
isEnableCommunityInputMethod: sb.$2, isEnableCommunityInputMethod: sb.$2,
context: context,
); );
} }
break; break;

View File

@ -20,6 +20,7 @@ import 'package:starcitizen_doctor/data/input_method_api_data.dart';
import 'package:starcitizen_doctor/data/sc_localization_data.dart'; import 'package:starcitizen_doctor/data/sc_localization_data.dart';
import 'package:starcitizen_doctor/generated/no_l10n_strings.dart'; import 'package:starcitizen_doctor/generated/no_l10n_strings.dart';
import 'package:starcitizen_doctor/ui/home/home_ui_model.dart'; 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:starcitizen_doctor/widgets/widgets.dart';
import 'package:url_launcher/url_launcher_string.dart'; import 'package:url_launcher/url_launcher_string.dart';
@ -50,13 +51,11 @@ class LocalizationUIModel extends _$LocalizationUIModel {
"chinese_(traditional)": NoL10n.langZHT, "chinese_(traditional)": NoL10n.langZHT,
}; };
Directory get _downloadDir => Directory get _downloadDir => Directory("${appGlobalState.applicationSupportDir}\\Localizations");
Directory("${appGlobalState.applicationSupportDir}\\Localizations");
Directory getDownloadDir() => _downloadDir; Directory getDownloadDir() => _downloadDir;
Directory get _scDataDir => Directory get _scDataDir => Directory("${ref.read(homeUIModelProvider).scInstalledPath}\\data");
Directory("${ref.read(homeUIModelProvider).scInstalledPath}\\data");
File get _cfgFile => File("${_scDataDir.absolute.path}\\system.cfg"); File get _cfgFile => File("${_scDataDir.absolute.path}\\system.cfg");
@ -80,16 +79,14 @@ class LocalizationUIModel extends _$LocalizationUIModel {
_customizeDirListenSub = null; _customizeDirListenSub = null;
}); });
final appConfBox = await Hive.openBox("app_conf"); final appConfBox = await Hive.openBox("app_conf");
final lang = await appConfBox.get("localization_selectedLanguage", final lang = await appConfBox.get("localization_selectedLanguage", defaultValue: languageSupport.keys.first);
defaultValue: languageSupport.keys.first);
state = state.copyWith(selectedLanguage: lang); state = state.copyWith(selectedLanguage: lang);
// fix for ui performance // fix for ui performance
await Future.delayed(Duration(milliseconds: 250)); await Future.delayed(Duration(milliseconds: 250));
await _loadData(); await _loadData();
} }
final Map<String, Map<String, ScLocalizationData>> final Map<String, Map<String, ScLocalizationData>> _allVersionLocalizationData = {};
_allVersionLocalizationData = {};
Future<void> _loadCommunityInputMethodData() async { Future<void> _loadCommunityInputMethodData() async {
try { try {
@ -141,16 +138,11 @@ class LocalizationUIModel extends _$LocalizationUIModel {
final userCfgFile = File("$_scInstallPath\\USER.cfg"); final userCfgFile = File("$_scInstallPath\\USER.cfg");
if (await userCfgFile.exists()) { if (await userCfgFile.exists()) {
final cfgString = await userCfgFile.readAsString(); final cfgString = await userCfgFile.readAsString();
if (cfgString.contains("g_language") && if (cfgString.contains("g_language") && !cfgString.contains("g_language=${state.selectedLanguage}")) {
!cfgString.contains("g_language=${state.selectedLanguage}")) {
if (!context.mounted) return; if (!context.mounted) return;
final ok = await showConfirmDialogs( final ok = await showConfirmDialogs(context, S.current.localization_info_remove_incompatible_translation_params,
context, Text(S.current.localization_info_incompatible_translation_params_warning),
S.current.localization_info_remove_incompatible_translation_params, constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * .35));
Text(S.current
.localization_info_incompatible_translation_params_warning),
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * .35));
if (ok == true) { if (ok == true) {
var finalString = ""; var finalString = "";
for (var item in cfgString.split("\n")) { for (var item in cfgString.split("\n")) {
@ -226,8 +218,7 @@ class LocalizationUIModel extends _$LocalizationUIModel {
VoidCallback? doDelIniFile() { VoidCallback? doDelIniFile() {
return () async { return () async {
final iniFile = File( final iniFile = File("${_scDataDir.absolute.path}\\Localization\\${state.selectedLanguage}\\global.ini");
"${_scDataDir.absolute.path}\\Localization\\${state.selectedLanguage}\\global.ini");
if (await iniFile.exists()) await iniFile.delete(); if (await iniFile.exists()) await iniFile.delete();
await updateLangCfg(false); await updateLangCfg(false);
await _updateStatus(); await _updateStatus();
@ -243,10 +234,11 @@ class LocalizationUIModel extends _$LocalizationUIModel {
String versionName, { String versionName, {
bool? advanced, bool? advanced,
bool isEnableCommunityInputMethod = false, bool isEnableCommunityInputMethod = false,
bool isEnableVehicleSorting = false,
BuildContext? context,
}) async { }) async {
dPrint("LocalizationUIModel -> installFormString $versionName"); dPrint("LocalizationUIModel -> installFormString $versionName");
final iniFile = File( final iniFile = File("${_scDataDir.absolute.path}\\Localization\\${state.selectedLanguage}\\global.ini");
"${_scDataDir.absolute.path}\\Localization\\${state.selectedLanguage}\\global.ini");
if (versionName.isNotEmpty) { if (versionName.isNotEmpty) {
if (!globalIni.toString().endsWith("\n")) { if (!globalIni.toString().endsWith("\n")) {
globalIni.write("\n"); globalIni.write("\n");
@ -258,8 +250,7 @@ class LocalizationUIModel extends _$LocalizationUIModel {
final data = state.communityInputMethodLanguageData; final data = state.communityInputMethodLanguageData;
if (data != null) { if (data != null) {
communityInputMethodVersion = data.version; communityInputMethodVersion = data.version;
final str = final str = await downloadOrGetCachedCommunityInputMethodSupportFile(data);
await downloadOrGetCachedCommunityInputMethodSupportFile(data);
if (str.trim().isNotEmpty) { if (str.trim().isNotEmpty) {
communityInputMethodSupportData = str; communityInputMethodSupportData = str;
} }
@ -267,8 +258,8 @@ class LocalizationUIModel extends _$LocalizationUIModel {
} }
if (communityInputMethodVersion != null) { if (communityInputMethodVersion != null) {
globalIni.write( globalIni
"_starcitizen_doctor_localization_community_input_method_version=$communityInputMethodVersion\n"); .write("_starcitizen_doctor_localization_community_input_method_version=$communityInputMethodVersion\n");
} }
if (communityInputMethodSupportData != null) { if (communityInputMethodSupportData != null) {
for (var line in communityInputMethodSupportData.split("\n")) { for (var line in communityInputMethodSupportData.split("\n")) {
@ -278,27 +269,34 @@ class LocalizationUIModel extends _$LocalizationUIModel {
if (advanced ?? false) { if (advanced ?? false) {
globalIni.write("_starcitizen_doctor_localization_advanced=true\n"); globalIni.write("_starcitizen_doctor_localization_advanced=true\n");
} }
globalIni globalIni.write("_starcitizen_doctor_localization_version=$versionName\n");
.write("_starcitizen_doctor_localization_version=$versionName\n");
} }
/// write cfg var iniStringData = globalIni.toString().trim();
if (await _cfgFile.exists()) {}
if ((context?.mounted ?? false) && isEnableVehicleSorting) {
if (!context!.mounted) return;
final iniStringDataVN = ValueNotifier(iniStringData);
final ok = await showConfirmDialogs(context, "载具排序", VehicleSortingDialogUi(iniStringData: iniStringDataVN),constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * .75,
));
if (ok) {
iniStringData = iniStringDataVN.value;
}
}
/// write ini /// write ini
if (await iniFile.exists()) { if (await iniFile.exists()) {
await iniFile.delete(); await iniFile.delete();
} }
await iniFile.create(recursive: true); await iniFile.create(recursive: true);
await iniFile.writeAsString("\uFEFF${globalIni.toString().trim()}", await iniFile.writeAsString("\uFEFF$iniStringData", flush: true);
flush: true);
await updateLangCfg(true); await updateLangCfg(true);
await _updateStatus(); await _updateStatus();
} }
Future<Map<String, String>?> getCommunityInputMethodSupportData() async { Future<Map<String, String>?> getCommunityInputMethodSupportData() async {
final iniPath = final iniPath = "${_scDataDir.absolute.path}\\Localization\\${state.selectedLanguage}\\global.ini";
"${_scDataDir.absolute.path}\\Localization\\${state.selectedLanguage}\\global.ini";
final iniFile = File(iniPath); final iniFile = File(iniPath);
if (!await iniFile.exists()) { if (!await iniFile.exists()) {
return {}; return {};
@ -309,13 +307,10 @@ class LocalizationUIModel extends _$LocalizationUIModel {
for (var i = 0; i < iniStringSplit.length; i++) { for (var i = 0; i < iniStringSplit.length; i++) {
final line = iniStringSplit[i]; final line = iniStringSplit[i];
if (line.trim().startsWith( if (line.trim().startsWith("_starcitizen_doctor_localization_community_input_method_version=")) {
"_starcitizen_doctor_localization_community_input_method_version=")) {
b = true; b = true;
continue; continue;
} else if (line } else if (line.trim().startsWith("_starcitizen_doctor_localization_version=")) {
.trim()
.startsWith("_starcitizen_doctor_localization_version=")) {
b = false; b = false;
return communityInputMethodSupportData; return communityInputMethodSupportData;
} else if (b) { } else if (b) {
@ -328,10 +323,8 @@ class LocalizationUIModel extends _$LocalizationUIModel {
return null; return null;
} }
Future<(String, String)> Future<(String, String)> getIniContentWithoutCommunityInputMethodSupportData() async {
getIniContentWithoutCommunityInputMethodSupportData() async { final iniPath = "${_scDataDir.absolute.path}\\Localization\\${state.selectedLanguage}\\global.ini";
final iniPath =
"${_scDataDir.absolute.path}\\Localization\\${state.selectedLanguage}\\global.ini";
final iniFile = File(iniPath); final iniFile = File(iniPath);
if (!await iniFile.exists()) { if (!await iniFile.exists()) {
return ("", ""); return ("", "");
@ -342,13 +335,10 @@ class LocalizationUIModel extends _$LocalizationUIModel {
for (var i = 0; i < iniStringSplit.length; i++) { for (var i = 0; i < iniStringSplit.length; i++) {
final line = iniStringSplit[i]; final line = iniStringSplit[i];
if (line.trim().startsWith( if (line.trim().startsWith("_starcitizen_doctor_localization_community_input_method_version=")) {
"_starcitizen_doctor_localization_community_input_method_version=")) {
b = true; b = true;
continue; continue;
} else if (line } else if (line.trim().startsWith("_starcitizen_doctor_localization_version=")) {
.trim()
.startsWith("_starcitizen_doctor_localization_version=")) {
b = false; b = false;
return (sb.toString(), line.split("=").last.trim()); return (sb.toString(), line.split("=").last.trim());
} else if (!b) { } else if (!b) {
@ -359,11 +349,10 @@ class LocalizationUIModel extends _$LocalizationUIModel {
} }
Future? doRemoteInstall(BuildContext context, ScLocalizationData value, Future? doRemoteInstall(BuildContext context, ScLocalizationData value,
{bool isEnableCommunityInputMethod = false}) async { {bool isEnableCommunityInputMethod = false, bool isEnableVehicleSorting = false}) async {
AnalyticsApi.touch("install_localization"); AnalyticsApi.touch("install_localization");
final savePath = final savePath = File("${_downloadDir.absolute.path}\\${value.versionName}.sclang");
File("${_downloadDir.absolute.path}\\${value.versionName}.sclang");
try { try {
state = state.copyWith(workingVersion: value.versionName!); state = state.copyWith(workingVersion: value.versionName!);
if (!await savePath.exists()) { if (!await savePath.exists()) {
@ -379,15 +368,17 @@ class LocalizationUIModel extends _$LocalizationUIModel {
if (globalIni.isEmpty) { if (globalIni.isEmpty) {
throw S.current.localization_info_corrupted_file; throw S.current.localization_info_corrupted_file;
} }
if (!context.mounted) return;
await installFormString( await installFormString(
globalIni, globalIni,
value.versionName ?? "", value.versionName ?? "",
isEnableCommunityInputMethod: isEnableCommunityInputMethod, isEnableCommunityInputMethod: isEnableCommunityInputMethod,
isEnableVehicleSorting: isEnableVehicleSorting,
context: context,
); );
} catch (e) { } catch (e) {
if (!context.mounted) return; if (!context.mounted) return;
await showToast( await showToast(context, S.current.localization_info_installation_error(e));
context, S.current.localization_info_installation_error(e));
if (await savePath.exists()) await savePath.delete(); if (await savePath.exists()) await savePath.delete();
} }
state = state.copyWith(workingVersion: ""); state = state.copyWith(workingVersion: "");
@ -400,19 +391,16 @@ class LocalizationUIModel extends _$LocalizationUIModel {
final cachedVersion = box.get("${lang}_version"); final cachedVersion = box.get("${lang}_version");
if (cachedVersion != communityInputMethodData.version) { if (cachedVersion != communityInputMethodData.version) {
final data = await Api.getCommunityInputMethodData( final data = await Api.getCommunityInputMethodData(communityInputMethodData.file ?? "");
communityInputMethodData.file ?? "");
await box.put("${lang}_data", data); await box.put("${lang}_data", data);
return data; return data;
} }
return box.get("${lang}_data").toString(); return box.get("${lang}_data").toString();
} }
Future<void> downloadLocalizationFile( Future<void> downloadLocalizationFile(File savePath, ScLocalizationData value) async {
File savePath, ScLocalizationData value) async {
dPrint("downloading file to $savePath"); dPrint("downloading file to $savePath");
final downloadUrl = final downloadUrl = "${URLConf.gitlabLocalizationUrl}/archive/${value.versionName}.tar.gz";
"${URLConf.gitlabLocalizationUrl}/archive/${value.versionName}.tar.gz";
final r = await RSHttp.get(downloadUrl); final r = await RSHttp.get(downloadUrl);
if (r.statusCode == 200 && r.data != null) { if (r.statusCode == 200 && r.data != null) {
await savePath.create(recursive: true); await savePath.create(recursive: true);
@ -446,8 +434,7 @@ class LocalizationUIModel extends _$LocalizationUIModel {
} }
void selectLang(String v) async { void selectLang(String v) async {
state = state.copyWith( state = state.copyWith(selectedLanguage: v, communityInputMethodLanguageData: null);
selectedLanguage: v, communityInputMethodLanguageData: null);
_loadData(); _loadData();
final appConfBox = await Hive.openBox("app_conf"); final appConfBox = await Hive.openBox("app_conf");
await appConfBox.put("localization_selectedLanguage", v); await appConfBox.put("localization_selectedLanguage", v);
@ -469,14 +456,11 @@ class LocalizationUIModel extends _$LocalizationUIModel {
} }
_updateStatus() async { _updateStatus() async {
final iniPath = final iniPath = "${_scDataDir.absolute.path}\\Localization\\${state.selectedLanguage}\\global.ini";
"${_scDataDir.absolute.path}\\Localization\\${state.selectedLanguage}\\global.ini"; final patchStatus =
final patchStatus = MapEntry( MapEntry(await _getLangCfgEnableLang(lang: state.selectedLanguage!), await _getInstalledIniVersion(iniPath));
await _getLangCfgEnableLang(lang: state.selectedLanguage!),
await _getInstalledIniVersion(iniPath));
final isInstalledAdvanced = await _checkAdvancedStatus(iniPath); final isInstalledAdvanced = await _checkAdvancedStatus(iniPath);
final installedCommunityInputMethodSupportVersion = final installedCommunityInputMethodSupportVersion = await getInstalledCommunityInputMethodSupportVersion(iniPath);
await getInstalledCommunityInputMethodSupportVersion(iniPath);
dPrint( dPrint(
"_updateStatus updateStatus: $patchStatus , isInstalledAdvanced: $isInstalledAdvanced ,installedCommunityInputMethodSupportVersion: $installedCommunityInputMethodSupportVersion"); "_updateStatus updateStatus: $patchStatus , isInstalledAdvanced: $isInstalledAdvanced ,installedCommunityInputMethodSupportVersion: $installedCommunityInputMethodSupportVersion");
@ -484,23 +468,19 @@ class LocalizationUIModel extends _$LocalizationUIModel {
state = state.copyWith( state = state.copyWith(
patchStatus: patchStatus, patchStatus: patchStatus,
isInstalledAdvanced: isInstalledAdvanced, isInstalledAdvanced: isInstalledAdvanced,
installedCommunityInputMethodSupportVersion: installedCommunityInputMethodSupportVersion: installedCommunityInputMethodSupportVersion,
installedCommunityInputMethodSupportVersion,
); );
} }
Future<String?> getInstalledCommunityInputMethodSupportVersion( Future<String?> getInstalledCommunityInputMethodSupportVersion(String path) async {
String path) async {
final iniFile = File(path); final iniFile = File(path);
if (!await iniFile.exists()) { if (!await iniFile.exists()) {
return null; return null;
} }
final iniStringSplit = (await iniFile.readAsString()).split("\n"); final iniStringSplit = (await iniFile.readAsString()).split("\n");
for (var i = iniStringSplit.length - 1; i > 0; i--) { for (var i = iniStringSplit.length - 1; i > 0; i--) {
if (iniStringSplit[i].contains( if (iniStringSplit[i].contains("_starcitizen_doctor_localization_community_input_method_version=")) {
"_starcitizen_doctor_localization_community_input_method_version=")) { final v = iniStringSplit[i].trim().split("_starcitizen_doctor_localization_community_input_method_version=")[1];
final v = iniStringSplit[i].trim().split(
"_starcitizen_doctor_localization_community_input_method_version=")[1];
return v; return v;
} }
} }
@ -516,8 +496,7 @@ class LocalizationUIModel extends _$LocalizationUIModel {
return iniString.contains("_starcitizen_doctor_localization_advanced=true"); return iniString.contains("_starcitizen_doctor_localization_advanced=true");
} }
Future<bool> _getLangCfgEnableLang( Future<bool> _getLangCfgEnableLang({String lang = "", String gamePath = ""}) async {
{String lang = "", String gamePath = ""}) async {
if (gamePath.isEmpty) { if (gamePath.isEmpty) {
gamePath = _scInstallPath; gamePath = _scInstallPath;
} }
@ -536,11 +515,8 @@ class LocalizationUIModel extends _$LocalizationUIModel {
} }
final iniStringSplit = (await iniFile.readAsString()).split("\n"); final iniStringSplit = (await iniFile.readAsString()).split("\n");
for (var i = iniStringSplit.length - 1; i > 0; i--) { for (var i = iniStringSplit.length - 1; i > 0; i--) {
if (iniStringSplit[i] if (iniStringSplit[i].contains("_starcitizen_doctor_localization_version=")) {
.contains("_starcitizen_doctor_localization_version=")) { final v = iniStringSplit[i].trim().split("_starcitizen_doctor_localization_version=")[1];
final v = iniStringSplit[i]
.trim()
.split("_starcitizen_doctor_localization_version=")[1];
return v; return v;
} }
} }
@ -567,11 +543,8 @@ class LocalizationUIModel extends _$LocalizationUIModel {
final dirList = await scDataDir.list().toList(); final dirList = await scDataDir.list().toList();
for (var element in dirList) { for (var element in dirList) {
for (var lang in languageSupport.keys) { for (var lang in languageSupport.keys) {
if (element.path.contains(lang) && if (element.path.contains(lang) && await _getLangCfgEnableLang(lang: lang, gamePath: scInstallPath)) {
await _getLangCfgEnableLang( final installedVersion = await _getInstalledIniVersion("${element.path}\\global.ini");
lang: lang, gamePath: scInstallPath)) {
final installedVersion =
await _getInstalledIniVersion("${element.path}\\global.ini");
if (installedVersion == S.current.home_action_info_game_built_in || if (installedVersion == S.current.home_action_info_game_built_in ||
installedVersion == S.current.localization_info_custom_files) { installedVersion == S.current.localization_info_custom_files) {
continue; continue;
@ -603,22 +576,17 @@ class LocalizationUIModel extends _$LocalizationUIModel {
if (cloudVersion == null || localVersion == null) return; if (cloudVersion == null || localVersion == null) return;
if (localVersion != cloudVersion) { if (localVersion != cloudVersion) {
// //
final (localIniString, versioName) = final (localIniString, versioName) = await getIniContentWithoutCommunityInputMethodSupportData();
await getIniContentWithoutCommunityInputMethodSupportData();
if (localIniString.trim().isEmpty) { if (localIniString.trim().isEmpty) {
dPrint( dPrint("[InputMethodDialogUIModel] check update Error localIniString is empty");
"[InputMethodDialogUIModel] check update Error localIniString is empty");
return; return;
} }
await installFormString(StringBuffer(localIniString), versioName, await installFormString(StringBuffer(localIniString), versioName, isEnableCommunityInputMethod: true);
isEnableCommunityInputMethod: true);
await win32.sendNotify( await win32.sendNotify(
summary: S.current.input_method_support_updated, summary: S.current.input_method_support_updated,
body: S.current.input_method_support_updated_to_version(cloudVersion), body: S.current.input_method_support_updated_to_version(cloudVersion),
appName: S.current.home_title_app_name, appName: S.current.home_title_app_name,
appId: ConstConf.isMSE appId: ConstConf.win32AppId);
? "56575xkeyC.MSE_bsn1nexg8e4qe!starcitizendoctor"
: "{6D809377-6AF0-444B-8957-A3773F02200E}\\Starcitizen_Doctor\\starcitizen_doctor.exe");
} }
} }
@ -627,11 +595,11 @@ class LocalizationUIModel extends _$LocalizationUIModel {
} }
Future<void> onRemoteInsTall( Future<void> onRemoteInsTall(
BuildContext context, BuildContext context, MapEntry<String, ScLocalizationData> item, LocalizationUIState state) async {
MapEntry<String, ScLocalizationData> item, final appBox = Hive.box("app_conf");
LocalizationUIState state) async { bool enableCommunityInputMethod = state.communityInputMethodLanguageData != null;
bool enableCommunityInputMethod = bool isEnableVehicleSorting = appBox.get("vehicle_sorting", defaultValue: false) ?? false;
state.communityInputMethodLanguageData != null; if (!context.mounted) return;
final userOK = await showConfirmDialogs( final userOK = await showConfirmDialogs(
context, context,
"${item.value.info}", "${item.value.info}",
@ -644,20 +612,17 @@ class LocalizationUIModel extends _$LocalizationUIModel {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
S.current.localization_info_version_number( S.current.localization_info_version_number(item.value.versionName ?? ""),
item.value.versionName ?? ""),
style: TextStyle(color: Colors.white.withValues(alpha: .6)), style: TextStyle(color: Colors.white.withValues(alpha: .6)),
), ),
const SizedBox(height: 4), const SizedBox(height: 4),
Text( Text(
S.current S.current.localization_info_channel(item.value.gameChannel ?? ""),
.localization_info_channel(item.value.gameChannel ?? ""),
style: TextStyle(color: Colors.white.withValues(alpha: .6)), style: TextStyle(color: Colors.white.withValues(alpha: .6)),
), ),
const SizedBox(height: 4), const SizedBox(height: 4),
Text( Text(
S.current S.current.localization_info_update_time(item.value.updateAt ?? ""),
.localization_info_update_time(item.value.updateAt ?? ""),
style: TextStyle(color: Colors.white.withValues(alpha: .6)), style: TextStyle(color: Colors.white.withValues(alpha: .6)),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
@ -665,9 +630,7 @@ class LocalizationUIModel extends _$LocalizationUIModel {
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
Container( Container(
decoration: BoxDecoration( decoration: BoxDecoration(color: FluentTheme.of(context).cardColor, borderRadius: BorderRadius.circular(7)),
color: FluentTheme.of(context).cardColor,
borderRadius: BorderRadius.circular(7)),
padding: const EdgeInsets.all(12), padding: const EdgeInsets.all(12),
child: Row( child: Row(
children: [ children: [
@ -688,8 +651,7 @@ class LocalizationUIModel extends _$LocalizationUIModel {
), ),
Spacer(), Spacer(),
StatefulBuilder( StatefulBuilder(
builder: (BuildContext context, builder: (BuildContext context, void Function(void Function()) setState) {
void Function(void Function()) setState) {
return ToggleSwitch( return ToggleSwitch(
checked: enableCommunityInputMethod, checked: enableCommunityInputMethod,
onChanged: state.communityInputMethodLanguageData == null onChanged: state.communityInputMethodLanguageData == null
@ -702,19 +664,44 @@ class LocalizationUIModel extends _$LocalizationUIModel {
}, },
) )
], ],
) ),
SizedBox(height: 12),
Row(
children: [
Text(
"载具排序",
),
Spacer(),
StatefulBuilder(
builder: (BuildContext context, void Function(void Function()) setState) {
return ToggleSwitch(
checked: isEnableVehicleSorting,
onChanged: (v) async {
setState(() {
isEnableVehicleSorting = v;
});
},
);
},
)
],
),
], ],
), ),
confirm: S.current.localization_action_install, confirm: S.current.localization_action_install,
cancel: S.current.home_action_cancel, cancel: S.current.home_action_cancel,
constraints: constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * .45),
BoxConstraints(maxWidth: MediaQuery.of(context).size.width * .45),
); );
if (userOK) { if (userOK) {
await appBox.put("vehicle_sorting", isEnableVehicleSorting);
if (!context.mounted) return; if (!context.mounted) return;
dPrint("doRemoteInstall ${item.value} $enableCommunityInputMethod"); dPrint("doRemoteInstall ${item.value} $enableCommunityInputMethod");
await doRemoteInstall(context, item.value, await doRemoteInstall(
isEnableCommunityInputMethod: enableCommunityInputMethod); context,
item.value,
isEnableCommunityInputMethod: enableCommunityInputMethod,
isEnableVehicleSorting: isEnableVehicleSorting,
);
} }
} }

View File

@ -7,7 +7,7 @@ part of 'localization_ui_model.dart';
// ************************************************************************** // **************************************************************************
String _$localizationUIModelHash() => String _$localizationUIModelHash() =>
r'9c45db7c36a19710584d04441c4b263010e59e4e'; r'640a129e8ecf7854d7668278046e808925d7f9d2';
/// See also [LocalizationUIModel]. /// See also [LocalizationUIModel].
@ProviderFor(LocalizationUIModel) @ProviderFor(LocalizationUIModel)

View File

@ -0,0 +1,337 @@
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hive_ce/hive.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:starcitizen_doctor/common/utils/log.dart';
class VehicleSortingDialogUi extends HookConsumerWidget {
final ValueNotifier<String> iniStringData;
const VehicleSortingDialogUi({
super.key,
required this.iniStringData,
});
static const List<String> vehicleLineRegExpList = ["vehicle_Name.*"];
@override
Widget build(BuildContext context, WidgetRef ref) {
final leftVehiclesList = useState<List<MapEntry<String, String>>?>(null);
final rightVehiclesList = useState<List<MapEntry<String, String>>>([]);
final leftSearchKey = useState<String>("");
final leftSearchController = useTextEditingController();
useEffect(() {
_loadVehiclesList(leftVehiclesList, rightVehiclesList);
return () {
_saveSortedVehicles(rightVehiclesList.value);
};
}, const []);
if (leftVehiclesList.value == null) {
return const Center(child: ProgressRing());
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: .03),
borderRadius: BorderRadius.circular(4.0),
),
child: Text(
"将左侧载具拖动到右侧列表中,这将会为载具名称增加 001、002 .. 等前缀,方便您在游戏内 UI 快速定位载具。在右侧列表上下拖动可以调整载具的顺序。",
),
),
const SizedBox(height: 12),
Expanded(
child: Row(
children: [
//
Expanded(
flex: 2,
child: Card(
padding: EdgeInsets.only(
left: 8.0,
top: 8.0,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Padding(
padding: EdgeInsets.all(4.0),
child: Text(
"载具",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Padding(
padding: const EdgeInsets.only(top: 12, bottom: 12),
child: Row(
children: [
Expanded(
child: TextFormBox(
controller: leftSearchController,
placeholder: "搜索载具",
onChanged: (value) {
leftSearchKey.value = value;
},
),
),
SizedBox(width: 6),
// clear button
Button(
child: Padding(
padding: const EdgeInsets.only(top: 4, bottom: 4),
child: const Icon(FluentIcons.clear),
),
onPressed: () {
leftSearchKey.value = "";
leftSearchController.clear();
},
),
],
),
),
Expanded(
child: ListView.builder(
itemCount: leftVehiclesList.value!.length,
padding: EdgeInsets.only(right: 8),
itemBuilder: (context, index) {
final vehicle = leftVehiclesList.value![index];
if (leftSearchKey.value.isNotEmpty) {
//
// key value
if (!vehicle.key.toLowerCase().contains(leftSearchKey.value.toLowerCase()) &&
!vehicle.value.toLowerCase().contains(leftSearchKey.value.toLowerCase())) {
return const SizedBox.shrink();
}
}
return Draggable<MapEntry<String, String>>(
data: vehicle,
feedback: _buildVehicleItem(context, vehicle, (MediaQuery.of(context).size.width / 3)),
childWhenDragging: _buildVehicleItem(context, vehicle, null, opacity: 0.5),
child: _buildVehicleItem(context, vehicle, null),
onDragCompleted: () {
//
final updatedList = [...leftVehiclesList.value!];
updatedList.removeAt(index);
leftVehiclesList.value = updatedList;
},
);
},
),
),
],
),
),
),
const SizedBox(width: 12),
// a
Expanded(
flex: 3,
child: Card(
padding: EdgeInsets.only(
left: 8.0,
top: 8.0,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Padding(
padding: EdgeInsets.all(4.0),
child: Text(
"已排序载具",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Expanded(
child: DragTarget<MapEntry<String, String>>(
onAcceptWithDetails: (detail) {
//
final updatedList = [...rightVehiclesList.value];
updatedList.add(detail.data);
rightVehiclesList.value = updatedList;
_applyChanges(rightVehiclesList.value);
},
builder: (context, candidateData, rejectedData) {
return ReorderableListView.builder(
buildDefaultDragHandles: false,
padding: EdgeInsets.only(right: 8.0),
onReorder: (oldIndex, newIndex) {
final updatedList = [...rightVehiclesList.value];
if (oldIndex < newIndex) {
newIndex -= 1;
}
final item = updatedList.removeAt(oldIndex);
updatedList.insert(newIndex, item);
rightVehiclesList.value = updatedList;
},
onReorderEnd: (_) {
_applyChanges(rightVehiclesList.value);
},
itemCount: rightVehiclesList.value.length,
itemBuilder: (context, index) {
final vehicle = rightVehiclesList.value[index];
//
final prefixedValue = _getPrefixedValue(index, vehicle.value);
return Container(
key: ValueKey(vehicle.key + index.toString()),
margin: const EdgeInsets.symmetric(vertical: 2.0),
child: Row(
children: [
IconButton(
icon: const Icon(FluentIcons.delete),
onPressed: () {
//
final updatedRightList = [...rightVehiclesList.value];
final removed = updatedRightList.removeAt(index);
rightVehiclesList.value = updatedRightList;
final updatedLeftList = [...leftVehiclesList.value!];
updatedLeftList.add(removed);
leftVehiclesList.value = updatedLeftList;
_applyChanges(rightVehiclesList.value);
},
),
Expanded(
child: ReorderableDragStartListener(
index: index,
child: _buildVehicleItem(
context,
MapEntry(vehicle.key, prefixedValue),
null,
isRightList: true,
),
),
),
],
),
);
},
);
},
),
),
],
),
),
),
],
),
),
],
);
}
Widget _buildVehicleItem(BuildContext context, MapEntry<String, String> vehicle, double? width,
{double opacity = 1.0, bool isRightList = false}) {
return Container(
width: width,
padding: const EdgeInsets.all(8.0),
margin: const EdgeInsets.symmetric(vertical: 2.0, horizontal: 4.0),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.05),
borderRadius: BorderRadius.circular(4.0),
),
child: Opacity(
opacity: opacity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
vehicle.value,
style: const TextStyle(fontSize: 14),
overflow: TextOverflow.ellipsis,
),
Text(
vehicle.key,
style: TextStyle(
fontSize: 12,
color: Colors.white.withValues(
alpha: .4,
),
),
overflow: TextOverflow.ellipsis,
),
],
),
),
);
}
String _getPrefixedValue(int index, String originalValue) {
// (001, 002, etc.)
final prefix = (index + 1).toString().padLeft(3, '0');
return "$prefix - $originalValue";
}
void _applyChanges(List<MapEntry<String, String>> sortedVehicles) async {
final lines = iniStringData.value.split('\n');
final updatedLines = <String>[];
for (final line in lines) {
bool matched = false;
final lineKey = line.split('=')[0].trim();
for (var i = 0; i < sortedVehicles.length; i++) {
final vehicle = sortedVehicles[i];
if (lineKey == vehicle.key) {
// 使
final prefixedValue = _getPrefixedValue(i, vehicle.value);
updatedLines.add("$lineKey=$prefixedValue");
matched = true;
break;
}
}
if (!matched) {
updatedLines.add(line);
}
}
iniStringData.value = updatedLines.join('\n');
dPrint("[VehicleSortingDialogUi] Applied changes to ${sortedVehicles.length} vehicles");
}
Future<void> _saveSortedVehicles(List<MapEntry<String, String>> sortedVehicles) async {
final appBox = await Hive.openBox("app_conf");
appBox.put("sorted_vehicles", sortedVehicles.map((e) => e.key).toList());
dPrint("[VehicleSortingDialogUi] Saved sorted vehicles: ${sortedVehicles.length}");
}
void _loadVehiclesList(
ValueNotifier<List<MapEntry<String, String>>?> vehiclesList,
ValueNotifier<List<MapEntry<String, String>>> rightVehiclesList,
) async {
final vehicleMap = <String, String>{};
final lines = iniStringData.value.split('\n');
for (final regExp in vehicleLineRegExpList) {
final pattern = RegExp(regExp);
for (final line in lines) {
if (pattern.hasMatch(line)) {
final parts = line.split('=');
if (parts.length == 2) {
final key = parts[0].trim();
final value = parts[1].trim();
vehicleMap[key] = value;
}
}
}
}
vehiclesList.value = vehicleMap.entries.toList();
dPrint("[VehicleSortingDialogUi] Loaded vehicles: ${vehiclesList.value?.length ?? 0}");
// Load sorted vehicles from app_conf
final appBox = await Hive.openBox("app_conf");
final sortedVehicles = appBox.get("sorted_vehicles", defaultValue: <String>[]) as List<String>;
if (sortedVehicles.isNotEmpty) {
//
rightVehiclesList.value = sortedVehicles
.where((key) => vehicleMap.containsKey(key))
.map((key) => MapEntry(key, vehicleMap[key]!))
.toList();
dPrint("[VehicleSortingDialogUi] Loaded sorted vehicles: ${rightVehiclesList.value.length}");
}
}
}