feat:riverpod 迁移 HomePerformanceUI

This commit is contained in:
xkeyC 2024-03-10 16:56:32 +08:00
parent 5c45e23d23
commit 01f1533ab0
7 changed files with 765 additions and 2 deletions

View File

@ -11,6 +11,7 @@ import 'package:path_provider/path_provider.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:starcitizen_doctor/common/conf/const_conf.dart';
import 'package:starcitizen_doctor/common/utils/log.dart';
import 'package:starcitizen_doctor/ui/home/performance/performance_ui.dart';
import 'package:starcitizen_doctor/ui/splash_ui.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:starcitizen_doctor/widgets/widgets.dart';
@ -50,6 +51,11 @@ GoRouter router(RouterRef ref) {
pageBuilder: (context, state) =>
myPageBuilder(context, state, const HomeGameDoctorUI()),
),
GoRoute(
path: 'performance',
pageBuilder: (context, state) =>
myPageBuilder(context, state, const HomePerformanceUI()),
),
],
),
],

View File

@ -6,7 +6,7 @@ part of 'app.dart';
// RiverpodGenerator
// **************************************************************************
String _$routerHash() => r'd8cf08526e81cdcda0203c32fc89140f2ffb0058';
String _$routerHash() => r'1277f4e4a70e811181503413f6dda3fb7e461f9d';
/// See also [router].
@ProviderFor(router)

View File

@ -30,7 +30,7 @@ class HomeGameDoctorUI extends HookConsumerWidget {
}, const []);
return makeDefaultPage(context,
title: "一键诊断",
title: "一键诊断 -> ${homeState.scInstalledPath}",
useBodyContainer: true,
content: Stack(
children: [

View File

@ -0,0 +1,278 @@
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:starcitizen_doctor/common/utils/log.dart';
import 'package:starcitizen_doctor/data/game_performance_data.dart';
import 'package:starcitizen_doctor/widgets/widgets.dart';
import 'performance_ui_model.dart';
class HomePerformanceUI extends HookConsumerWidget {
const HomePerformanceUI({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(homePerformanceUIModelProvider);
final model = ref.read(homePerformanceUIModelProvider.notifier);
var content = makeLoading(context);
if (state.performanceMap != null) {
content = Stack(
children: [
Padding(
padding: const EdgeInsets.only(top: 12, left: 12, right: 12),
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(left: 24, right: 24),
child: Column(
children: [
if (state.showGraphicsPerformanceTip)
InfoBar(
title: const Text("图形优化提示"),
content: const Text(
"该功能对优化显卡瓶颈有很大帮助,但对 CPU 瓶颈可能起反效果,如果您显卡性能强劲,可以尝试使用更好的画质来获得更高的显卡利用率。",
),
onClose: () => model.closeTip(),
),
const SizedBox(height: 16),
Row(
children: [
Text(
"当前状态:${state.enabled ? "已应用" : "未应用"}",
style: const TextStyle(fontSize: 18),
),
const SizedBox(width: 32),
const Text(
"预设:",
style: TextStyle(fontSize: 18),
),
for (final item in const {
"low": "",
"medium": "",
"high": "",
"ultra": "超级"
}.entries)
Padding(
padding: const EdgeInsets.only(left: 6, right: 6),
child: Button(
child: Padding(
padding: const EdgeInsets.only(
top: 2, bottom: 2, left: 4, right: 4),
child: Text(item.value),
),
onPressed: () =>
model.onChangePreProfile(item.key)),
),
const Text("(预设只修改图形设置)"),
const Spacer(),
Button(
onPressed: () => model.refresh(),
child: const Padding(
padding: EdgeInsets.all(6),
child: Icon(FluentIcons.refresh),
),
),
const SizedBox(width: 12),
Button(
child: const Text(
" 恢复默认 ",
style: TextStyle(fontSize: 16),
),
onPressed: () => model.clean(context)),
const SizedBox(width: 24),
Button(
child: const Text(
"应用",
style: TextStyle(fontSize: 16),
),
onPressed: () => model.applyProfile(false)),
const SizedBox(width: 6),
Button(
child: const Text(
"应用并清理着色器(推荐)",
style: TextStyle(fontSize: 16),
),
onPressed: () => model.applyProfile(true)),
],
),
const SizedBox(height: 16),
],
),
),
Expanded(
child: MasonryGridView.count(
crossAxisCount: 2,
mainAxisSpacing: 1,
crossAxisSpacing: 1,
itemCount: state.performanceMap!.length,
itemBuilder: (context, index) {
return makeItemGroup(context,
state.performanceMap!.entries.elementAt(index), model);
},
)),
],
),
),
if (state.workingString.isNotEmpty)
Container(
decoration: BoxDecoration(
color: Colors.black.withAlpha(150),
),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const ProgressRing(),
const SizedBox(height: 12),
Text(state.workingString),
],
),
),
)
],
);
}
return makeDefaultPage(context,
title: "性能优化 -> ${model.scPath}",
useBodyContainer: true,
content: content);
}
Widget makeItemGroup(
BuildContext context,
MapEntry<String?, List<GamePerformanceData>> group,
HomePerformanceUIModel model) {
return Padding(
padding: const EdgeInsets.all(12),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: FluentTheme.of(context).cardColor,
),
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"${group.key}",
style: const TextStyle(fontSize: 20),
),
const SizedBox(height: 6),
Container(
color: FluentTheme.of(context).cardColor.withOpacity(.2),
height: 1),
const SizedBox(height: 6),
for (final item in group.value) makeItem(context, item, model)
],
),
),
),
);
}
Widget makeItem(BuildContext context, GamePerformanceData item,
HomePerformanceUIModel model) {
return Padding(
padding: const EdgeInsets.only(top: 8, bottom: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"${item.name}",
style: const TextStyle(fontSize: 16),
),
const SizedBox(height: 12),
if (item.type == "int")
Column(
children: [
Row(
children: [
SizedBox(
width: 72,
child: TextFormBox(
key: UniqueKey(),
initialValue: "${item.value}",
onFieldSubmitted: (str) {
dPrint(str);
if (str.isEmpty) return;
final v = int.tryParse(str);
if (v != null &&
v < (item.max ?? 0) &&
v >= (item.min ?? 0)) {
item.value = v;
}
model.updateState();
},
onTapOutside: (e) {
model.updateState();
},
),
),
const SizedBox(width: 32),
SizedBox(
width: MediaQuery.of(context).size.width / 4,
child: Slider(
value: item.value?.toDouble() ?? 0,
min: item.min?.toDouble() ?? 0,
max: item.max?.toDouble() ?? 0,
onChanged: (double value) {
item.value = value.toInt();
model.updateState();
},
),
)
],
)
],
)
else if (item.type == "bool")
Column(
children: [
ToggleSwitch(
checked: item.value == 1,
onChanged: (bool value) {
item.value = value ? 1 : 0;
model.updateState();
},
)
],
)
else if (item.type == "customize")
TextFormBox(
maxLines: 10,
placeholder:
"您可以在这里输入未收录进盒子的自定义参数。配置示例:\n\nr_displayinfo=0\nr_VSync=0",
controller: model.customizeCtrl,
),
if (item.info != null && item.info!.isNotEmpty) ...[
const SizedBox(height: 12),
Text(
"${item.info}",
style:
TextStyle(fontSize: 14, color: Colors.white.withOpacity(.6)),
),
],
const SizedBox(height: 12),
if (item.type != "customize")
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
"${item.key} 最小值: ${item.min} / 最大值: ${item.max}",
style: TextStyle(color: Colors.white.withOpacity(.6)),
)
],
),
const SizedBox(height: 6),
Container(
color: FluentTheme.of(context).cardColor.withOpacity(.1),
height: 1),
],
),
);
}
}

View File

@ -0,0 +1,228 @@
// ignore_for_file: avoid_build_context_in_providers
import 'dart:convert';
import 'dart:io';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/services.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:hive/hive.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:starcitizen_doctor/api/analytics.dart';
import 'package:starcitizen_doctor/common/helper/log_helper.dart';
import 'package:starcitizen_doctor/common/utils/base_utils.dart';
import 'package:starcitizen_doctor/data/game_performance_data.dart';
import 'package:starcitizen_doctor/ui/home/home_ui_model.dart';
part 'performance_ui_model.freezed.dart';
part 'performance_ui_model.g.dart';
@freezed
class HomePerformanceUIState with _$HomePerformanceUIState {
const factory HomePerformanceUIState({
@Default(true) bool showGraphicsPerformanceTip,
@Default(false) bool enabled,
Map<String, List<GamePerformanceData>>? performanceMap,
@Default("") String workingString,
}) = _HomePerformanceUIState;
}
@riverpod
class HomePerformanceUIModel extends _$HomePerformanceUIModel {
String get scPath => ref.read(homeUIModelProvider).scInstalledPath!;
final customizeCtrl = TextEditingController(text: "");
final List<String> _inAppKeys = [];
late final confFile = File("$scPath\\USER.cfg");
static const _graphicsPerformanceTipVersion = 1;
@override
HomePerformanceUIState build() {
state = const HomePerformanceUIState();
_init();
return state;
}
Future<void> _init() async {
customizeCtrl.clear();
_inAppKeys.clear();
final String jsonString =
await rootBundle.loadString('assets/performance.json');
final list = json.decode(jsonString);
if (list is List) {
final performanceMap = <String, List<GamePerformanceData>>{};
for (var element in list) {
final item = GamePerformanceData.fromJson(element);
if (item.key != "customize") {
_inAppKeys.add(item.key ?? "");
}
performanceMap[item.group!] ??= [];
performanceMap[item.group]?.add(item);
}
state = state.copyWith(performanceMap: performanceMap);
}
if (await confFile.exists()) {
await _readConf();
} else {
state = state.copyWith(enabled: false);
}
final box = await Hive.openBox("app_conf");
final v = box.get("close_graphics_performance_tip", defaultValue: -1);
state = state.copyWith(
showGraphicsPerformanceTip: v != _graphicsPerformanceTipVersion);
}
_readConf() async {
if (state.performanceMap == null) return;
state = state.copyWith(enabled: true);
final confString = await confFile.readAsString();
for (var value in confString.split("\n")) {
final kv = value.split("=");
for (var m in state.performanceMap!.entries) {
for (var value in m.value) {
if (value.key == kv[0].trim()) {
final v = int.tryParse(kv[1].trim());
if (v != null) value.value = v;
}
}
}
if (kv.length == 2 && !_inAppKeys.contains(kv[0].trim())) {
customizeCtrl.text =
"${customizeCtrl.text}${kv[0].trim()}=${kv[1].trim()}\n";
}
}
}
closeTip() async {
final box = await Hive.openBox("app_conf");
await box.put(
"close_graphics_performance_tip", _graphicsPerformanceTipVersion);
_init();
}
onChangePreProfile(String key) {
switch (key) {
case "low":
state.performanceMap?.forEach((key, v) {
if (key.contains("图形")) {
for (var element in v) {
element.value = element.min;
}
}
});
break;
case "medium":
state.performanceMap?.forEach((key, v) {
if (key.contains("图形")) {
for (var element in v) {
element.value = ((element.max ?? 0) ~/ 2);
}
}
});
break;
case "high":
state.performanceMap?.forEach((key, v) {
if (key.contains("图形")) {
for (var element in v) {
element.value = ((element.max ?? 0) / 1.5).ceil();
}
}
});
break;
case "ultra":
state.performanceMap?.forEach((key, v) {
if (key.contains("图形")) {
for (var element in v) {
element.value = element.max;
}
}
});
break;
}
state = state.copyWith();
}
refresh() async {
_init();
}
clean(BuildContext context) async {
state = state.copyWith(workingString: "删除配置文件...");
if (await confFile.exists()) {
await confFile.delete(recursive: true);
}
state = state.copyWith(workingString: "清理着色器");
if (!context.mounted) return;
await cleanShaderCache(context);
state = state.copyWith(workingString: "完成...");
await await Future.delayed(const Duration(milliseconds: 300));
await _init();
state = state.copyWith(workingString: "");
}
cleanShaderCache(BuildContext? context) async {
final gameShaderCachePath = await SCLoggerHelper.getShaderCachePath();
final l =
await Directory(gameShaderCachePath!).list(recursive: false).toList();
for (var value in l) {
if (value is Directory) {
if (!value.absolute.path.contains("Crashes")) {
await value.delete(recursive: true);
}
}
}
await Future.delayed(const Duration(milliseconds: 300));
if (context != null && context.mounted) {
showToast(context, "清理着色器后首次进入游戏可能会出现卡顿,请耐心等待游戏初始化完毕。");
}
}
applyProfile(bool cleanShader) async {
if (state.performanceMap == null) return;
AnalyticsApi.touch("performance_apply");
state = state.copyWith(workingString: "生成配置文件");
String conf = "";
for (var v in state.performanceMap!.entries) {
for (var c in v.value) {
if (c.key != "customize") {
conf = "$conf${c.key}=${c.value}\n";
}
}
}
if (customizeCtrl.text.trim().isNotEmpty) {
final lines = customizeCtrl.text.split("\n");
for (var value in lines) {
final sp = value.split("=");
//
if (sp.length == 2) {
conf = "$conf${sp[0].trim()}=${sp[1].trim()}\n";
}
}
}
state = state.copyWith(workingString: "写出配置文件");
if (await confFile.exists()) {
await confFile.delete();
}
await confFile.create();
await confFile.writeAsString(conf);
if (cleanShader) {
state = state.copyWith(workingString: "清理着色器");
await cleanShaderCache(null);
}
state = state.copyWith(workingString: "完成...");
await await Future.delayed(const Duration(milliseconds: 300));
await _init();
state = state.copyWith(workingString: "清理着色器");
}
updateState() {
state = state.copyWith();
}
}

View File

@ -0,0 +1,224 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'performance_ui_model.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
T _$identity<T>(T value) => value;
final _privateConstructorUsedError = UnsupportedError(
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models');
/// @nodoc
mixin _$HomePerformanceUIState {
bool get showGraphicsPerformanceTip => throw _privateConstructorUsedError;
bool get enabled => throw _privateConstructorUsedError;
Map<String, List<GamePerformanceData>>? get performanceMap =>
throw _privateConstructorUsedError;
String get workingString => throw _privateConstructorUsedError;
@JsonKey(ignore: true)
$HomePerformanceUIStateCopyWith<HomePerformanceUIState> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $HomePerformanceUIStateCopyWith<$Res> {
factory $HomePerformanceUIStateCopyWith(HomePerformanceUIState value,
$Res Function(HomePerformanceUIState) then) =
_$HomePerformanceUIStateCopyWithImpl<$Res, HomePerformanceUIState>;
@useResult
$Res call(
{bool showGraphicsPerformanceTip,
bool enabled,
Map<String, List<GamePerformanceData>>? performanceMap,
String workingString});
}
/// @nodoc
class _$HomePerformanceUIStateCopyWithImpl<$Res,
$Val extends HomePerformanceUIState>
implements $HomePerformanceUIStateCopyWith<$Res> {
_$HomePerformanceUIStateCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
@pragma('vm:prefer-inline')
@override
$Res call({
Object? showGraphicsPerformanceTip = null,
Object? enabled = null,
Object? performanceMap = freezed,
Object? workingString = null,
}) {
return _then(_value.copyWith(
showGraphicsPerformanceTip: null == showGraphicsPerformanceTip
? _value.showGraphicsPerformanceTip
: showGraphicsPerformanceTip // ignore: cast_nullable_to_non_nullable
as bool,
enabled: null == enabled
? _value.enabled
: enabled // ignore: cast_nullable_to_non_nullable
as bool,
performanceMap: freezed == performanceMap
? _value.performanceMap
: performanceMap // ignore: cast_nullable_to_non_nullable
as Map<String, List<GamePerformanceData>>?,
workingString: null == workingString
? _value.workingString
: workingString // ignore: cast_nullable_to_non_nullable
as String,
) as $Val);
}
}
/// @nodoc
abstract class _$$HomePerformanceUIStateImplCopyWith<$Res>
implements $HomePerformanceUIStateCopyWith<$Res> {
factory _$$HomePerformanceUIStateImplCopyWith(
_$HomePerformanceUIStateImpl value,
$Res Function(_$HomePerformanceUIStateImpl) then) =
__$$HomePerformanceUIStateImplCopyWithImpl<$Res>;
@override
@useResult
$Res call(
{bool showGraphicsPerformanceTip,
bool enabled,
Map<String, List<GamePerformanceData>>? performanceMap,
String workingString});
}
/// @nodoc
class __$$HomePerformanceUIStateImplCopyWithImpl<$Res>
extends _$HomePerformanceUIStateCopyWithImpl<$Res,
_$HomePerformanceUIStateImpl>
implements _$$HomePerformanceUIStateImplCopyWith<$Res> {
__$$HomePerformanceUIStateImplCopyWithImpl(
_$HomePerformanceUIStateImpl _value,
$Res Function(_$HomePerformanceUIStateImpl) _then)
: super(_value, _then);
@pragma('vm:prefer-inline')
@override
$Res call({
Object? showGraphicsPerformanceTip = null,
Object? enabled = null,
Object? performanceMap = freezed,
Object? workingString = null,
}) {
return _then(_$HomePerformanceUIStateImpl(
showGraphicsPerformanceTip: null == showGraphicsPerformanceTip
? _value.showGraphicsPerformanceTip
: showGraphicsPerformanceTip // ignore: cast_nullable_to_non_nullable
as bool,
enabled: null == enabled
? _value.enabled
: enabled // ignore: cast_nullable_to_non_nullable
as bool,
performanceMap: freezed == performanceMap
? _value._performanceMap
: performanceMap // ignore: cast_nullable_to_non_nullable
as Map<String, List<GamePerformanceData>>?,
workingString: null == workingString
? _value.workingString
: workingString // ignore: cast_nullable_to_non_nullable
as String,
));
}
}
/// @nodoc
class _$HomePerformanceUIStateImpl implements _HomePerformanceUIState {
const _$HomePerformanceUIStateImpl(
{this.showGraphicsPerformanceTip = true,
this.enabled = false,
final Map<String, List<GamePerformanceData>>? performanceMap,
this.workingString = ""})
: _performanceMap = performanceMap;
@override
@JsonKey()
final bool showGraphicsPerformanceTip;
@override
@JsonKey()
final bool enabled;
final Map<String, List<GamePerformanceData>>? _performanceMap;
@override
Map<String, List<GamePerformanceData>>? get performanceMap {
final value = _performanceMap;
if (value == null) return null;
if (_performanceMap is EqualUnmodifiableMapView) return _performanceMap;
// ignore: implicit_dynamic_type
return EqualUnmodifiableMapView(value);
}
@override
@JsonKey()
final String workingString;
@override
String toString() {
return 'HomePerformanceUIState(showGraphicsPerformanceTip: $showGraphicsPerformanceTip, enabled: $enabled, performanceMap: $performanceMap, workingString: $workingString)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$HomePerformanceUIStateImpl &&
(identical(other.showGraphicsPerformanceTip,
showGraphicsPerformanceTip) ||
other.showGraphicsPerformanceTip ==
showGraphicsPerformanceTip) &&
(identical(other.enabled, enabled) || other.enabled == enabled) &&
const DeepCollectionEquality()
.equals(other._performanceMap, _performanceMap) &&
(identical(other.workingString, workingString) ||
other.workingString == workingString));
}
@override
int get hashCode => Object.hash(
runtimeType,
showGraphicsPerformanceTip,
enabled,
const DeepCollectionEquality().hash(_performanceMap),
workingString);
@JsonKey(ignore: true)
@override
@pragma('vm:prefer-inline')
_$$HomePerformanceUIStateImplCopyWith<_$HomePerformanceUIStateImpl>
get copyWith => __$$HomePerformanceUIStateImplCopyWithImpl<
_$HomePerformanceUIStateImpl>(this, _$identity);
}
abstract class _HomePerformanceUIState implements HomePerformanceUIState {
const factory _HomePerformanceUIState(
{final bool showGraphicsPerformanceTip,
final bool enabled,
final Map<String, List<GamePerformanceData>>? performanceMap,
final String workingString}) = _$HomePerformanceUIStateImpl;
@override
bool get showGraphicsPerformanceTip;
@override
bool get enabled;
@override
Map<String, List<GamePerformanceData>>? get performanceMap;
@override
String get workingString;
@override
@JsonKey(ignore: true)
_$$HomePerformanceUIStateImplCopyWith<_$HomePerformanceUIStateImpl>
get copyWith => throw _privateConstructorUsedError;
}

View File

@ -0,0 +1,27 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'performance_ui_model.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
String _$homePerformanceUIModelHash() =>
r'85e3390e954b35ffeb7cbacf85619b5a61f866bb';
/// See also [HomePerformanceUIModel].
@ProviderFor(HomePerformanceUIModel)
final homePerformanceUIModelProvider = AutoDisposeNotifierProvider<
HomePerformanceUIModel, HomePerformanceUIState>.internal(
HomePerformanceUIModel.new,
name: r'homePerformanceUIModelProvider',
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
? null
: _$homePerformanceUIModelHash,
dependencies: null,
allTransitiveDependencies: null,
);
typedef _$HomePerformanceUIModel = AutoDisposeNotifier<HomePerformanceUIState>;
// ignore_for_file: type=lint
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member