Remove SharedPreferences, debug win

Signed-off-by: fufesou <shuanglongchen@yeah.net>
This commit is contained in:
fufesou
2022-11-10 21:25:12 +08:00
parent 0cf2bfb5ef
commit 50d885d3e7
21 changed files with 297 additions and 182 deletions

View File

@@ -15,7 +15,6 @@ import 'package:flutter_hbb/main.dart';
import 'package:flutter_hbb/models/peer_model.dart';
import 'package:flutter_hbb/utils/multi_window_manager.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uni_links/uni_links.dart';
import 'package:uni_links_desktop/uni_links_desktop.dart';
import 'package:window_manager/window_manager.dart';
@@ -205,18 +204,17 @@ class MyTheme {
);
static ThemeMode getThemeModePreference() {
return themeModeFromString(
Get.find<SharedPreferences>().getString("themeMode") ?? "");
return themeModeFromString(bind.mainGetLocalOption(key: kCommConfKeyTheme));
}
static void changeDarkMode(ThemeMode mode) {
final preference = getThemeModePreference();
if (preference != mode) {
if (mode == ThemeMode.system) {
Get.find<SharedPreferences>().setString("themeMode", "");
bind.mainSetLocalOption(key: kCommConfKeyTheme, value: '');
} else {
Get.find<SharedPreferences>()
.setString("themeMode", mode.toShortString());
bind.mainSetLocalOption(
key: kCommConfKeyTheme, value: mode.toShortString());
}
Get.changeThemeMode(mode);
if (desktopType == DesktopType.main) {
@@ -1026,8 +1024,8 @@ Future<void> saveWindowPosition(WindowType type, {int? windowId}) async {
final isMaximized = await windowManager.isMaximized();
final pos = LastWindowPosition(
sz.width, sz.height, position.dx, position.dy, isMaximized);
await Get.find<SharedPreferences>()
.setString(kWindowPrefix + type.name, pos.toString());
await bind.setLocalFlutterConfig(
k: kWindowPrefix + type.name, v: pos.toString());
break;
default:
final wc = WindowController.fromWindowId(windowId!);
@@ -1037,9 +1035,10 @@ Future<void> saveWindowPosition(WindowType type, {int? windowId}) async {
final isMaximized = await wc.isMaximized();
final pos = LastWindowPosition(
sz.width, sz.height, position.dx, position.dy, isMaximized);
debugPrint("saving frame: ${windowId}: ${pos.width}/${pos.height}, offset:${pos.offsetWidth}/${pos.offsetHeight}");
await Get.find<SharedPreferences>()
.setString(kWindowPrefix + type.name, pos.toString());
debugPrint(
"saving frame: $windowId: ${pos.width}/${pos.height}, offset:${pos.offsetWidth}/${pos.offsetHeight}");
await bind.setLocalFlutterConfig(
k: kWindowPrefix + type.name, v: pos.toString());
break;
}
}
@@ -1109,7 +1108,7 @@ Future<Offset?> _adjustRestoreMainWindowOffset(
.toDouble();
if (isDesktop || isWebDesktop) {
for(final screen in await window_size.getScreenList()) {
for (final screen in await window_size.getScreenList()) {
frameLeft = min(screen.visibleFrame.left, frameLeft);
frameTop = min(screen.visibleFrame.top, frameTop);
frameRight = max(screen.visibleFrame.right, frameRight);
@@ -1136,13 +1135,7 @@ Future<bool> restoreWindowPosition(WindowType type, {int? windowId}) async {
debugPrint(
"Error: windowId cannot be null when saving positions for sub window");
}
final pos =
Get.find<SharedPreferences>().getString(kWindowPrefix + type.name);
if (pos == null) {
debugPrint("no window position saved, ignore restore");
return false;
}
final pos = bind.getLocalFlutterConfig(k: kWindowPrefix + type.name);
var lpos = LastWindowPosition.loadFromString(pos);
if (lpos == null) {
debugPrint("window position saved, but cannot be parsed");
@@ -1175,7 +1168,8 @@ Future<bool> restoreWindowPosition(WindowType type, {int? windowId}) async {
await _adjustRestoreMainWindowSize(lpos.width, lpos.height);
final offset = await _adjustRestoreMainWindowOffset(
lpos.offsetWidth, lpos.offsetHeight);
debugPrint("restore lpos: ${size.width}/${size.height}, offset:${offset?.dx}/${offset?.dy}");
debugPrint(
"restore lpos: ${size.width}/${size.height}, offset:${offset?.dx}/${offset?.dy}");
if (offset == null) {
await wc.center();
} else {
@@ -1327,8 +1321,7 @@ void connect(BuildContext context, String id,
Future<Map<String, String>> getHttpHeaders() async {
return {
'Authorization':
'Bearer ${await bind.mainGetLocalOption(key: 'access_token')}'
'Authorization': 'Bearer ${bind.mainGetLocalOption(key: 'access_token')}'
};
}

View File

@@ -22,27 +22,26 @@ class _PeerTabPageState extends State<PeerTabPage>
@override
void initState() {
() async {
await bind.mainGetLocalOption(key: 'peer-tab-index').then((value) {
if (value == '') return;
final tab = int.parse(value);
_tabIndex.value = tab;
});
await bind.mainGetLocalOption(key: 'peer-card-ui-type').then((value) {
if (value == '') return;
final tab = int.parse(value);
peerCardUiType.value =
tab == PeerUiType.list.index ? PeerUiType.list : PeerUiType.grid;
});
}();
setPeer();
super.initState();
}
setPeer() {
final index = bind.getLocalFlutterConfig(k: 'peer-tab-index');
if (index == '') return;
_tabIndex.value = int.parse(index);
final uiType = bind.getLocalFlutterConfig(k: 'peer-card-ui-type');
if (uiType == '') return;
peerCardUiType.value = int.parse(uiType) == PeerUiType.list.index
? PeerUiType.list
: PeerUiType.grid;
}
// hard code for now
Future<void> _handleTabSelection(int index) async {
_tabIndex.value = index;
await bind.mainSetLocalOption(
key: 'peer-tab-index', value: index.toString());
await bind.setLocalFlutterConfig(k: 'peer-tab-index', v: index.toString());
switch (index) {
case 0:
bind.mainLoadRecentPeers();
@@ -148,9 +147,8 @@ class _PeerTabPageState extends State<PeerTabPage>
decoration: peerCardUiType.value == type ? activeDeco : null,
child: InkWell(
onTap: () async {
await bind.mainSetLocalOption(
key: 'peer-card-ui-type',
value: type.index.toString());
await bind.setLocalFlutterConfig(
k: 'peer-card-ui-type', v: type.index.toString());
peerCardUiType.value = type;
},
child: Icon(

View File

@@ -56,7 +56,11 @@ var kWindowEdgeSize = Platform.isWindows ? 1.0 : 5.0;
const kWindowBorderWidth = 1.0;
const kDesktopMenuPadding = EdgeInsets.only(left: 12.0, right: 3.0);
const kInvalidValueStr = "InvalidValueStr";
const kInvalidValueStr = 'InvalidValueStr';
// Config key shared by flutter and other ui.
const kCommConfKeyTheme = 'theme';
const kCommConfKeyLang = 'lang';
const kMobilePageConstraints = BoxConstraints(maxWidth: 600);

View File

@@ -5,6 +5,7 @@ import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hbb/common.dart';
import 'package:flutter_hbb/consts.dart';
import 'package:flutter_hbb/desktop/pages/desktop_home_page.dart';
import 'package:flutter_hbb/desktop/pages/desktop_tab_page.dart';
import 'package:flutter_hbb/desktop/widgets/login.dart';
@@ -30,8 +31,8 @@ const double _kListViewBottomMargin = 15;
const double _kTitleFontSize = 20;
const double _kContentFontSize = 15;
const Color _accentColor = MyTheme.accent;
const String _kSettingPageControllerTag = "settingPageController";
const String _kSettingPageIndexTag = "settingPageIndex";
const String _kSettingPageControllerTag = 'settingPageController';
const String _kSettingPageIndexTag = 'settingPageIndex';
class _TabInfo {
late final String label;
@@ -250,19 +251,19 @@ class _GeneralState extends State<_General> {
return _Card(title: 'Theme', children: [
_Radio<String>(context,
value: "light",
value: 'light',
groupValue: current,
label: "Light",
label: 'Light',
onChanged: onChanged),
_Radio<String>(context,
value: "dark",
value: 'dark',
groupValue: current,
label: "Dark",
label: 'Dark',
onChanged: onChanged),
_Radio<String>(context,
value: "system",
value: 'system',
groupValue: current,
label: "Follow System",
label: 'Follow System',
onChanged: onChanged),
]);
}
@@ -286,8 +287,8 @@ class _GeneralState extends State<_General> {
Widget audio(BuildContext context) {
String getDefault() {
if (Platform.isWindows) return "System Sound";
return "";
if (Platform.isWindows) return 'System Sound';
return '';
}
Future<String> getValue() async {
@@ -300,7 +301,7 @@ class _GeneralState extends State<_General> {
}
setDevice(String device) {
if (device == getDefault()) device = "";
if (device == getDefault()) device = '';
bind.mainSetOption(key: 'audio-input', value: device);
}
@@ -353,7 +354,7 @@ class _GeneralState extends State<_General> {
'allow-auto-record-incoming'),
Row(
children: [
Text('${translate('Directory')}:'),
Text('${translate("Directory")}:'),
Expanded(
child: GestureDetector(
onTap: canlaunch ? () => launchUrl(Uri.file(dir)) : null,
@@ -386,26 +387,26 @@ class _GeneralState extends State<_General> {
Widget language() {
return _futureBuilder(future: () async {
String langs = await bind.mainGetLangs();
String lang = await bind.mainGetLocalOption(key: "lang");
return {"langs": langs, "lang": lang};
String lang = bind.mainGetLocalOption(key: kCommConfKeyLang);
return {'langs': langs, 'lang': lang};
}(), hasData: (res) {
Map<String, String> data = res as Map<String, String>;
List<dynamic> langsList = jsonDecode(data["langs"]!);
List<dynamic> langsList = jsonDecode(data['langs']!);
Map<String, String> langsMap = {for (var v in langsList) v[0]: v[1]};
List<String> keys = langsMap.keys.toList();
List<String> values = langsMap.values.toList();
keys.insert(0, "");
values.insert(0, "Default");
String currentKey = data["lang"]!;
keys.insert(0, '');
values.insert(0, 'Default');
String currentKey = data['lang']!;
if (!keys.contains(currentKey)) {
currentKey = "";
currentKey = '';
}
return _ComboBox(
keys: keys,
values: values,
initialKey: currentKey,
onChanged: (key) async {
await bind.mainSetLocalOption(key: "lang", value: key);
await bind.mainSetLocalOption(key: kCommConfKeyLang, value: key);
reloadAllWindows();
bind.mainChangeLanguage(lang: key);
},
@@ -585,9 +586,9 @@ class _SafetyState extends State<_Safety> with AutomaticKeepAliveClientMixin {
kUseBothPasswords,
];
List<String> values = [
translate("Use temporary password"),
translate("Use permanent password"),
translate("Use both passwords"),
translate('Use temporary password'),
translate('Use permanent password'),
translate('Use both passwords'),
];
bool tmpEnabled = model.verificationMethod != kUsePermanentPassword;
bool permEnabled = model.verificationMethod != kUseTemporaryPassword;
@@ -830,12 +831,12 @@ class _NetworkState extends State<_Network> with AutomaticKeepAliveClientMixin {
// Setting page is not modal, oldOptions should only be used when getting options, never when setting.
Map<String, dynamic> oldOptions = jsonDecode(data! as String);
old(String key) {
return (oldOptions[key] ?? "").trim();
return (oldOptions[key] ?? '').trim();
}
RxString idErrMsg = "".obs;
RxString relayErrMsg = "".obs;
RxString apiErrMsg = "".obs;
RxString idErrMsg = ''.obs;
RxString relayErrMsg = ''.obs;
RxString apiErrMsg = ''.obs;
var idController =
TextEditingController(text: old('custom-rendezvous-server'));
var relayController = TextEditingController(text: old('relay-server'));
@@ -864,9 +865,9 @@ class _NetworkState extends State<_Network> with AutomaticKeepAliveClientMixin {
}
if (apiServer.isNotEmpty) {
if (!apiServer.startsWith('http://') ||
!apiServer.startsWith("https://")) {
!apiServer.startsWith('https://')) {
apiErrMsg.value =
"${translate("API Server")}: ${translate("invalid_http")}";
'${translate("API Server")}: ${translate("invalid_http")}';
return false;
}
}
@@ -893,7 +894,7 @@ class _NetworkState extends State<_Network> with AutomaticKeepAliveClientMixin {
import() {
Clipboard.getData(Clipboard.kTextPlain).then((value) {
TextEditingController mytext = TextEditingController();
String? aNullableString = "";
String? aNullableString = '';
aNullableString = value?.text;
mytext.text = aNullableString.toString();
if (mytext.text.isNotEmpty) {
@@ -918,13 +919,13 @@ class _NetworkState extends State<_Network> with AutomaticKeepAliveClientMixin {
}
});
} else {
showToast(translate("Invalid server configuration"));
showToast(translate('Invalid server configuration'));
}
} catch (e) {
showToast(translate("Invalid server configuration"));
showToast(translate('Invalid server configuration'));
}
} else {
showToast(translate("Clipboard is empty"));
showToast(translate('Clipboard is empty'));
}
});
}
@@ -936,7 +937,7 @@ class _NetworkState extends State<_Network> with AutomaticKeepAliveClientMixin {
config['ApiServer'] = apiController.text.trim();
config['Key'] = keyController.text.trim();
Clipboard.setData(ClipboardData(text: jsonEncode(config)));
showToast(translate("Export server configuration successfully"));
showToast(translate('Export server configuration successfully'));
}
bool secure = !enabled;
@@ -962,7 +963,7 @@ class _NetworkState extends State<_Network> with AutomaticKeepAliveClientMixin {
Obx(() => _LabeledTextField(context, 'API Server', apiController,
apiErrMsg.value, enabled, secure)),
_LabeledTextField(
context, 'Key', keyController, "", enabled, secure),
context, 'Key', keyController, '', enabled, secure),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [_Button('Apply', submit, enabled: enabled)],
@@ -1039,28 +1040,28 @@ class _AboutState extends State<_About> {
child: SingleChildScrollView(
controller: scrollController,
physics: NeverScrollableScrollPhysics(),
child: _Card(title: "About RustDesk", children: [
child: _Card(title: 'About RustDesk', children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
height: 8.0,
),
Text("Version: $version").marginSymmetric(vertical: 4.0),
Text('Version: $version').marginSymmetric(vertical: 4.0),
InkWell(
onTap: () {
launchUrlString("https://rustdesk.com/privacy");
launchUrlString('https://rustdesk.com/privacy');
},
child: const Text(
"Privacy Statement",
'Privacy Statement',
style: linkStyle,
).marginSymmetric(vertical: 4.0)),
InkWell(
onTap: () {
launchUrlString("https://rustdesk.com");
launchUrlString('https://rustdesk.com');
},
child: const Text(
"Website",
'Website',
style: linkStyle,
).marginSymmetric(vertical: 4.0)),
Container(
@@ -1074,11 +1075,11 @@ class _AboutState extends State<_About> {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Copyright &copy; 2022 Purslane Ltd.\n$license",
'Copyright &copy; 2022 Purslane Ltd.\n$license',
style: const TextStyle(color: Colors.white),
),
const Text(
"Made with heart in this chaotic world!",
'Made with heart in this chaotic world!',
style: TextStyle(
fontWeight: FontWeight.w800,
color: Colors.white),
@@ -1472,10 +1473,10 @@ class _ComboBox extends StatelessWidget {
void changeSocks5Proxy() async {
var socks = await bind.mainGetSocks();
String proxy = "";
String proxyMsg = "";
String username = "";
String password = "";
String proxy = '';
String proxyMsg = '';
String username = '';
String password = '';
if (socks.length == 3) {
proxy = socks[0];
username = socks[1];
@@ -1489,7 +1490,7 @@ void changeSocks5Proxy() async {
gFFI.dialogManager.show((setState, close) {
submit() async {
setState(() {
proxyMsg = "";
proxyMsg = '';
isInProgress = true;
});
cancel() {
@@ -1517,7 +1518,7 @@ void changeSocks5Proxy() async {
}
return CustomAlertDialog(
title: Text(translate("Socks5 Proxy")),
title: Text(translate('Socks5 Proxy')),
content: ConstrainedBox(
constraints: const BoxConstraints(minWidth: 500),
child: Column(
@@ -1530,7 +1531,7 @@ void changeSocks5Proxy() async {
children: [
ConstrainedBox(
constraints: const BoxConstraints(minWidth: 100),
child: Text("${translate('Hostname')}:")
child: Text('${translate("Hostname")}:')
.marginOnly(bottom: 16.0)),
const SizedBox(
width: 24.0,
@@ -1553,7 +1554,7 @@ void changeSocks5Proxy() async {
children: [
ConstrainedBox(
constraints: const BoxConstraints(minWidth: 100),
child: Text("${translate('Username')}:")
child: Text('${translate("Username")}:')
.marginOnly(bottom: 16.0)),
const SizedBox(
width: 24.0,
@@ -1575,7 +1576,7 @@ void changeSocks5Proxy() async {
children: [
ConstrainedBox(
constraints: const BoxConstraints(minWidth: 100),
child: Text("${translate('Password')}:")
child: Text('${translate("Password")}:')
.marginOnly(bottom: 16.0)),
const SizedBox(
width: 24.0,
@@ -1599,8 +1600,8 @@ void changeSocks5Proxy() async {
),
),
actions: [
TextButton(onPressed: close, child: Text(translate("Cancel"))),
TextButton(onPressed: submit, child: Text(translate("OK"))),
TextButton(onPressed: close, child: Text(translate('Cancel'))),
TextButton(onPressed: submit, child: Text(translate('OK'))),
],
onSubmit: submit,
onCancel: close,

View File

@@ -7,7 +7,6 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hbb/models/chat_model.dart';
import 'package:flutter_hbb/models/state_model.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:rxdart/rxdart.dart' as rxdart;
@@ -28,12 +27,14 @@ class MenubarState {
late RxBool _pin;
MenubarState() {
final s = Get.find<SharedPreferences>().getString(kStoreKey);
if (s == null) {
final s = bind.getLocalFlutterConfig(k: kStoreKey);
if (s.isEmpty) {
_initSet(false, false);
return;
}
try {
final m = jsonDecode(s!);
final m = jsonDecode(s);
if (m == null) {
_initSet(false, false);
} else {
@@ -77,11 +78,8 @@ class MenubarState {
}
save() async {
final success = await Get.find<SharedPreferences>()
.setString(kStoreKey, jsonEncode({'pin': _pin.value}.toString()));
if (!success) {
debugPrint('Failed to save remote menu bar state');
}
bind.setLocalFlutterConfig(
k: kStoreKey, v: jsonEncode({'pin': _pin.value}));
}
}

View File

@@ -15,7 +15,6 @@ import 'package:flutter_hbb/utils/multi_window_manager.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:window_manager/window_manager.dart';
import 'package:bot_toast/bot_toast.dart';
@@ -97,7 +96,6 @@ Future<void> main(List<String> args) async {
Future<void> initEnv(String appType) async {
// global shared preference
await Get.putAsync(() => SharedPreferences.getInstance());
await platformFFI.init(appType);
// global FFI, use this **ONLY** for global configuration
// for convenience, use global FFI on mobile platform

View File

@@ -16,7 +16,6 @@ import 'package:flutter_hbb/models/server_model.dart';
import 'package:flutter_hbb/models/user_model.dart';
import 'package:flutter_hbb/models/state_model.dart';
import 'package:flutter_hbb/utils/multi_window_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tuple/tuple.dart';
import 'package:image/image.dart' as img2;
import 'package:flutter_custom_cursor/flutter_custom_cursor.dart';
@@ -1219,7 +1218,7 @@ class FFI {
Future<void> close() async {
chatModel.close();
if (imageModel.image != null && !isWebDesktop) {
await savePreference(id, cursorModel.x, cursorModel.y, canvasModel.x,
await setCanvasConfig(id, cursorModel.x, cursorModel.y, canvasModel.x,
canvasModel.y, canvasModel.scale, ffiModel.pi.currentDisplay);
}
bind.sessionClose(id: id);
@@ -1267,9 +1266,10 @@ class PeerInfo {
List<Display> displays = [];
}
Future<void> savePreference(String id, double xCursor, double yCursor,
const canvasKey = 'canvas';
Future<void> setCanvasConfig(String id, double xCursor, double yCursor,
double xCanvas, double yCanvas, double scale, int currentDisplay) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final p = <String, dynamic>{};
p['xCursor'] = xCursor;
p['yCursor'] = yCursor;
@@ -1277,25 +1277,27 @@ Future<void> savePreference(String id, double xCursor, double yCursor,
p['yCanvas'] = yCanvas;
p['scale'] = scale;
p['currentDisplay'] = currentDisplay;
prefs.setString('peer$id', json.encode(p));
await bind.sessionSetFlutterConfig(id: id, k: canvasKey, v: jsonEncode(p));
}
Future<Map<String, dynamic>?> getPreference(String id) async {
Future<Map<String, dynamic>?> getCanvasConfig(String id) async {
if (!isWebDesktop) return null;
SharedPreferences prefs = await SharedPreferences.getInstance();
var p = prefs.getString('peer$id');
if (p == null) return null;
Map<String, dynamic> m = json.decode(p);
return m;
var p = await bind.sessionGetFlutterConfig(id: id, k: canvasKey);
if (p == null || p.isEmpty) return null;
try {
Map<String, dynamic> m = json.decode(p);
return m;
} catch (e) {
return null;
}
}
void removePreference(String id) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove('peer$id');
await bind.sessionSetFlutterConfig(id: id, k: canvasKey, v: '');
}
Future<void> initializeCursorAndCanvas(FFI ffi) async {
var p = await getPreference(ffi.id);
var p = await getCanvasConfig(ffi.id);
int currentDisplay = 0;
if (p != null) {
currentDisplay = p['currentDisplay'];

View File

@@ -19,7 +19,7 @@ class UserModel {
void refreshCurrentUser() async {
await getUserName();
final token = await bind.mainGetLocalOption(key: 'access_token');
final token = bind.mainGetLocalOption(key: 'access_token');
if (token == '') return;
final url = await bind.mainGetApiServer();
final body = {
@@ -73,7 +73,7 @@ class UserModel {
if (userName.isNotEmpty) {
return userName.value;
}
final userInfo = await bind.mainGetLocalOption(key: 'user_info');
final userInfo = bind.mainGetLocalOption(key: 'user_info');
if (userInfo.trim().isEmpty) {
return '';
}

View File

@@ -40,7 +40,6 @@ dependencies:
#firebase_analytics: ^9.1.5
package_info_plus: ^1.4.2
url_launcher: ^6.0.9
shared_preferences: ^2.0.6
toggle_switch: ^1.4.0
dash_chat_2: ^0.0.14
draggable_float_widget: ^0.0.2