Skip to content

Commit

Permalink
Attempt to repair/restore a broken preferences file
Browse files Browse the repository at this point in the history
  • Loading branch information
fdennis committed Dec 6, 2024
1 parent 623ba4a commit f50a994
Showing 1 changed file with 42 additions and 1 deletion.
43 changes: 42 additions & 1 deletion lib/desktop/init.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ 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:path_provider_linux/path_provider_linux.dart';
import 'package:path_provider_windows/path_provider_windows.dart';
import 'package:screen_retriever/screen_retriever.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:window_manager/window_manager.dart';
Expand Down Expand Up @@ -125,7 +129,34 @@ Future<Widget> initialize(List<String> argv) async {
_initLogging(args);

await windowManager.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
SharedPreferences prefs;
try {
prefs = await SharedPreferences.getInstance();
} catch (error) {
// Attempt to repair the broken preferences file
String? directory;
if (Platform.isWindows) {
PathProviderWindows pathProvider = PathProviderWindows();
directory = await pathProvider.getApplicationSupportPath();
} else if (Platform.isLinux) {
PathProviderLinux pathProvider = PathProviderLinux();
directory = await pathProvider.getApplicationSupportPath();
}
if (directory == null) {
throw FormatException("Unable to find correct directory");
}
String appDataPath = path.join(directory, 'shared_preferences.json');
List<int> repairedPreferences = await _repairPreferences(appDataPath);
await File(appDataPath).writeAsBytes(repairedPreferences);

try {
prefs = await SharedPreferences.getInstance();
} catch (error) {
// Unable to repair the preferences file, therefore delete it
await File(appDataPath).delete();
prefs = await SharedPreferences.getInstance();
}
}
final windowManagerHelper = WindowManagerHelper.withPreferences(prefs);
final isHidden = _getIsHidden(args, prefs);

Expand Down Expand Up @@ -413,3 +444,13 @@ class _HelperWaiterState extends ConsumerState<_HelperWaiter> {
}
}
}

Future<List<int>> _repairPreferences(String appDataPath) async {
List<int> contents = await File(appDataPath).readAsBytes();
var contentsGrowable = new List<int>.from(contents); // Make the list growable

// Remove any NUL characters
contentsGrowable.removeWhere((item) => item == 0);

return contentsGrowable;
}

0 comments on commit f50a994

Please sign in to comment.