import 'dart:convert' show json; import 'package:file/file.dart'; import 'package:file/local.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as path; import 'base.dart'; import '../globals.dart'; final _log = Logger("WindowsConfig"); class WindowsConfig implements Config { WindowsConfig(); FileSystem fs = const LocalFileSystem(); Map? _cachedPreferences; File? _filePath; Future filePath() async { if (_filePath != null) return _filePath; final String? exe = await platformPath.getCurrentExe(); if (exe == null) return null; final dir = path.dirname(exe); final name = path.basenameWithoutExtension(exe); return _filePath = fs.file(path.join(dir, "$name.json")); } Future> reload() async { Map preferences = {}; final File? localDataFile = await filePath(); if (localDataFile != null && localDataFile.existsSync()) { final String stringMap = localDataFile.readAsStringSync(); if (stringMap.isNotEmpty) { final Object? data = json.decode(stringMap); if (data is Map) { preferences = data.cast(); } } } _cachedPreferences = preferences; return preferences; } Future> _readPreferences() async { return _cachedPreferences ?? await reload(); } Future _writePreferences(Map preferences) async { try { final File? localDataFile = await filePath(); if (localDataFile == null) { _log.warning('Unable to determine where to write preferences.'); return false; } if (!localDataFile.existsSync()) { localDataFile.createSync(recursive: true); } final String stringMap = json.encode(preferences); localDataFile.writeAsStringSync(stringMap); } catch (e) { _log.severe('Error saving preferences to disk: ', e); return false; } return true; } @override Future clear() async { final Map preferences = await _readPreferences(); preferences.clear(); return _writePreferences(preferences); } Future setValue(String key, Object value) async { final Map preferences = await _readPreferences(); preferences[key] = value; return _writePreferences(preferences); } @override bool containsKey(String key) { return _cachedPreferences?.containsKey(key) ?? false; } @override Object? get(String key) => _cachedPreferences?[key]; @override String? getString(String key) => _cachedPreferences?[key] as String?; @override Future setString(String key, String value) { return setValue(key, value); } @override int? getInt(String key) => _cachedPreferences?[key] as int?; @override Future setInt(String key, int value) { return setValue(key, value); } @override bool? getBool(String key) => _cachedPreferences?[key] as bool?; @override Future setBool(String key, bool value) { return setValue(key, value); } }