diff --git a/lib/desktop/init.dart b/lib/desktop/init.dart index 9a78868e9..7f29ab95a 100755 --- a/lib/desktop/init.dart +++ b/lib/desktop/init.dart @@ -27,6 +27,8 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:local_notifier/local_notifier.dart'; import 'package:logging/logging.dart'; import 'package:material_symbols_icons/symbols.dart'; +import 'package:path/path.dart' as path; +import 'package:path_provider/path_provider.dart'; import 'package:screen_retriever/screen_retriever.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:window_manager/window_manager.dart'; @@ -125,7 +127,26 @@ Future initialize(List argv) async { _initLogging(args); await windowManager.ensureInitialized(); - final prefs = await SharedPreferences.getInstance(); + SharedPreferences prefs; + try { + prefs = await SharedPreferences.getInstance(); + } catch (error) { + Directory appSupportDirectory = await getApplicationSupportDirectory(); + String appDataPath = + path.join(appSupportDirectory.path, 'shared_preferences.json'); + _log.warning( + 'Failed to load the preferences file at $appDataPath. Attempting to repair it.'); + await _repairPreferences(appDataPath); + + try { + prefs = await SharedPreferences.getInstance(); + } catch (error) { + _log.warning( + 'Failed to repair the preferences file. Deleting the file and proceeding with a fresh configuration.'); + await File(appDataPath).delete(); + prefs = await SharedPreferences.getInstance(); + } + } final windowManagerHelper = WindowManagerHelper.withPreferences(prefs); final isHidden = _getIsHidden(args, prefs); @@ -413,3 +434,13 @@ class _HelperWaiterState extends ConsumerState<_HelperWaiter> { } } } + +Future _repairPreferences(String appDataPath) async { + List contents = await File(appDataPath).readAsBytes(); + var contentsGrowable = List.from(contents); // Make the list growable + + // Remove any NUL characters + contentsGrowable.removeWhere((item) => item == 0); + + await File(appDataPath).writeAsBytes(contentsGrowable); +}