perf(startup): overlap launch work and defer the storage check

The desktop log setup and the Android install marker read now run beside
the preferences load. The access check of the saved download folder no
longer holds the first frame: the shell waits for it after that frame,
and asks again only when the check gave no answer (a timeout or a
channel error). The wait for wallpaper colours is skipped where no theme
uses them (Mornye, or dynamic colour off), the cover cache starts beside
the other services, and the settings reach the backend in parallel.

The Link source presence no longer creates the Library provider on the
first frame, and the playback notification reads the collections only
once there is a song. The storage migration prompt asks whether it was
shown before it asks for the device details. The Mornye bottom bar hears
only whether the keyboard is open, not every frame of its animation.
This commit is contained in:
zarzet committed 2026-11-21 21:57:41 +07:00
1 parent 5be1786d8a
commit 5c6fa36291
6 files changed
+163 -88

No files matched your search

+45 -19
View File
@@ -102,6 +102,10 @@ void main() {
// The preferences plugin answers without an Activity, so on Android
// the load overlaps the Activity's creation.
final preferences = SharedPreferences.getInstance();
// Desktop: log files and the unclean-exit marker, awaited before the
// error hooks below start writing to them.
final desktopDiagnostics = DesktopDiagnostics.initialize();
Future<(InstallationState?, Object?)>? installMarker;
if (Platform.isAndroid) {
// A media service can start the engine before MainActivity registers
// the backend and platform channels. Calls made earlier would fail or
@@ -112,6 +116,12 @@ void main() {
unawaited(_startBackgroundPlayback());
}
await waitForActivityAttachment(binding);
// Overlap the install marker IPC with preferences and orientation.
installMarker = PlatformBridge.ensureInstallMarker()
.then<(InstallationState?, Object?)>(
(state) => (state, null),
onError: (Object error) => (null, error),
);
// Android 15 and later enforce this; older versions stop the app
// above the navigation bar, so no screen could reach the bottom edge.
unawaited(SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge));
@@ -121,9 +131,6 @@ void main() {
final dynamicColors = DynamicColors.request();
// Awaited before runApp, which reports a failure once.
final orientation = _initializeOrientation()..ignore();
// Desktop: log files and the unclean-exit marker, before the error
// hooks below start writing to them.
await DesktopDiagnostics.initialize();
if (isDesktopPlatform) MediaKitPlaybackDeck.releaseOutputsOnExit();
LicenseRegistry.addLicense(() async* {
yield LicenseEntryWithLineBreaks(
@@ -182,6 +189,7 @@ void main() {
});
_startupBenchmark?.observeFirstFrame();
await desktopDiagnostics;
final previousOnError = FlutterError.onError;
FlutterError.onError = (details) {
previousOnError?.call(details);
@@ -204,22 +212,28 @@ void main() {
// The SAF check overlaps the install marker read. An installation
// reset rewrites the settings, so its result is then replaced.
var safValidation = _startSafTreeValidation(bootstrapSettings);
if (await _prepareAndroidInstallationState(prefs)) {
if (await _prepareAndroidInstallationState(
prefs,
installMarker: installMarker,
)) {
bootstrapSettings = loadBootstrapSettings(prefs);
safValidation = _startSafTreeValidation(bootstrapSettings);
}
musicPlayerRuntime.configure(bootstrapSettings);
if (isDesktopPlatform) restoreDesktopSidebar(prefs);
final bootstrapTheme = loadBootstrapThemeSettings(prefs);
final initialSafAccessLost = await _detectInitialSafAccessLoss(
safValidation,
);
final initialSafValidation = safValidation == null
? null
: _detectInitialSafAccessLoss(safValidation);
final runtimeProfile = await _resolveRuntimeProfile(prefs);
_configureImageCache(runtimeProfile);
await orientation;
// Usually answered by now. The first frame then has the final theme,
// with no fade from the seed colors; a late answer still applies.
await dynamicColors.settle(const Duration(milliseconds: 100));
// Usually answered by now, so the first frame has the final theme. Only
// a Material theme with dynamic color uses the answer.
if (bootstrapTheme.style != AppThemeStyle.mornye &&
bootstrapTheme.useDynamicColor) {
await dynamicColors.settle(const Duration(milliseconds: 100));
}
runApp(
ProviderScope(
@@ -236,8 +250,8 @@ void main() {
!Platform.isAndroid || runtimeProfile.enableBackdropBlur,
),
initialSettingsProvider.overrideWithValue(bootstrapSettings),
initialSafAccessLostProvider.overrideWithValue(
initialSafAccessLost,
initialSafValidationProvider.overrideWithValue(
initialSafValidation,
),
initialThemeSettingsProvider.overrideWithValue(bootstrapTheme),
initialDynamicColorsProvider.overrideWithValue(dynamicColors),
@@ -438,13 +452,23 @@ const _runtimeProfileTierKey = 'runtime_profile_tier_v1';
/// Returns whether a restored-installation reset started, which may have
/// rewritten the stored settings.
Future<bool> _prepareAndroidInstallationState(SharedPreferences prefs) async {
Future<bool> _prepareAndroidInstallationState(
SharedPreferences prefs, {
Future<(InstallationState?, Object?)>? installMarker,
}) async {
if (!Platform.isAndroid) return false;
var resetStarted = false;
try {
final hasPersistedSettings = hasPersistedAppSettings(prefs);
final installState = await PlatformBridge.ensureInstallMarker();
final InstallationState installState;
if (installMarker != null) {
final (state, error) = await installMarker;
if (error != null) throw error;
installState = state!;
} else {
installState = await PlatformBridge.ensureInstallMarker();
}
final shouldReset = shouldResetRestoredInstallation(
hasPersistedSettings: hasPersistedSettings,
installState: installState,
@@ -486,15 +510,16 @@ Future<(bool, Object?)>? _startSafTreeValidation(AppSettings settings) {
);
}
Future<bool> _detectInitialSafAccessLoss(
Future<(bool, Object?)>? validation,
/// True when the grant is lost, null when the check gave no answer.
Future<bool?> _detectInitialSafAccessLoss(
Future<(bool, Object?)> validation,
) async {
if (validation == null) return false;
final (accessible, error) = await validation;
if (error != null) {
// A transient bridge failure must not trap the user at launch. Download
// preflight validates strictly again before any write starts.
_log.w('Failed to validate SAF access during startup: $error');
return null;
}
return !accessible;
}
@@ -871,9 +896,10 @@ class _EagerInitializationState extends ConsumerState<EagerInitialization>
Future<void> _initializeAppServices() async {
try {
await CoverCacheManager.initialize();
CoverCacheManager.scheduleMaintenance();
await Future.wait([
CoverCacheManager.initialize().then(
(_) => CoverCacheManager.scheduleMaintenance(),
),
NotificationService().initialize(),
ShareIntentService().initialize(),
AudioFileOpenService.instance.initialize(),
@@ -26,11 +26,11 @@ final playbackNotificationProvider = Provider.autoDispose
final track = item == null
? null
: ref.watch(playerCollectionTrackProvider(item)).value;
final loved = ref.watch(
libraryCollectionsProvider.select(
(state) => track != null && state.isLoved(track),
),
);
final loved =
track != null &&
ref.watch(
libraryCollectionsProvider.select((state) => state.isLoved(track)),
);
// Publishing playback state inside a provider build would synchronously
// modify the stream provider this binding is observing.
var active = true;
+33 -30
View File
@@ -40,10 +40,9 @@ final initialSettingsProvider = Provider<AppSettings>(
(ref) => const AppSettings(),
);
/// Set during bootstrap when the saved Android SAF tree no longer has a valid
/// persisted grant. MainShell consumes this once to block downloads until the
/// user explicitly repairs or changes the destination.
final initialSafAccessLostProvider = Provider<bool>((ref) => false);
/// The startup check of the saved Android SAF tree: true when its grant is
/// lost, null when it gave no answer. MainShell consumes this once.
final initialSafValidationProvider = Provider<Future<bool?>?>((ref) => null);
bool hasPersistedAppSettings(SharedPreferences prefs) {
final rawSettings = prefs.getString(_settingsKey);
@@ -245,9 +244,11 @@ class SettingsNotifier extends Notifier<AppSettings> {
LogBuffer.loggingEnabled = state.enableLogging;
await syncLyricsSettingsToBackend();
await _syncNetworkCompatibilitySettingsToBackend();
await _syncExtensionFallbackSettingsToBackend();
await Future.wait([
syncLyricsSettingsToBackend(),
_syncNetworkCompatibilitySettingsToBackend(),
_syncExtensionFallbackSettingsToBackend(),
]);
}
void _syncLyricsSettingsToBackend() {
@@ -258,35 +259,37 @@ class SettingsNotifier extends Notifier<AppSettings> {
final snapshot = settings ?? state;
if (!PlatformBridge.supportsCoreBackend) return;
try {
await PlatformBridge.setLyricsProviders(snapshot.lyricsProviders);
} catch (e) {
_log.w('Failed to sync lyrics providers to backend: $e');
}
try {
await PlatformBridge.setLyricsFetchOptions(snapshot.lyricsFetchOptions);
} catch (e) {
_log.w('Failed to sync lyrics fetch options to backend: $e');
}
await Future.wait([
PlatformBridge.setLyricsProviders(snapshot.lyricsProviders).catchError((
Object e,
) {
_log.w('Failed to sync lyrics providers to backend: $e');
}),
PlatformBridge.setLyricsFetchOptions(
snapshot.lyricsFetchOptions,
).catchError((Object e) {
_log.w('Failed to sync lyrics fetch options to backend: $e');
}),
]);
}
Future<void> _syncNetworkCompatibilitySettingsToBackend() async {
if (!PlatformBridge.supportsCoreBackend) return;
final compatibilityMode = state.networkCompatibilityMode;
await PlatformBridge.setNetworkCompatibilityOptions(
allowHttp: compatibilityMode,
insecureTls: false,
).catchError((Object e) {
_log.w('Failed to sync network compatibility options to backend: $e');
});
await PlatformBridge.setAllowPrivateNetwork(
state.allowLocalNetwork,
).catchError((Object e) {
_log.w('Failed to sync allow local network option to backend: $e');
});
await Future.wait([
PlatformBridge.setNetworkCompatibilityOptions(
allowHttp: compatibilityMode,
insecureTls: false,
).catchError((Object e) {
_log.w('Failed to sync network compatibility options to backend: $e');
}),
PlatformBridge.setAllowPrivateNetwork(state.allowLocalNetwork).catchError(
(Object e) {
_log.w('Failed to sync allow local network option to backend: $e');
},
),
]);
}
Future<void> _syncExtensionFallbackSettingsToBackend() async {
+55 -18
View File
@@ -190,6 +190,10 @@ class _MainShellState extends ConsumerState<MainShell>
late final _libraryDepthObserver = _PageDepthObserver(
onRoot: () => desktopSidebarLink.value = null,
);
late final Listenable _chromeSurfaceListenable = Listenable.merge([
ShellNavigationService.chromeBrightness,
ShellNavigationService.chromeSurface,
]);
/// The style the current tab index was chosen under.
bool? _indexStyleMornye;
@@ -301,8 +305,12 @@ class _MainShellState extends ConsumerState<MainShell>
showRepoTab: false,
);
WidgetsBinding.instance.addPostFrameCallback((_) async {
// Null when the startup check gave no answer: it is then asked again.
final safLost = await ref.read(initialSafValidationProvider);
if (!mounted) return;
await _repairSafAccessIfNeeded(
knownLost: ref.read(initialSafAccessLostProvider),
knownLost: safLost ?? false,
alreadyChecked: safLost != null,
);
_initialSafRepairComplete = true;
if (!mounted) return;
@@ -1425,11 +1433,9 @@ class _MainShellState extends ConsumerState<MainShell>
bottomNavigationBar: Builder(
builder: (context) {
if (context.isMornye) {
final mornyeBlurEnabled = ref.watch(mornyeBlurEnabledProvider);
return ListenableBuilder(
listenable: Listenable.merge([
ShellNavigationService.chromeBrightness,
ShellNavigationService.chromeSurface,
]),
listenable: _chromeSurfaceListenable,
builder: (context, child) => Theme(
data: ShellNavigationService.chromeBrightness.value == null
? Theme.of(context)
@@ -1455,19 +1461,23 @@ class _MainShellState extends ConsumerState<MainShell>
),
child: useNavigationRail
? const MiniPlayer()
: ValueListenableBuilder<bool>(
valueListenable: _mornyeChrome,
builder: (context, collapsed, _) => MornyeBottomBar(
collapsed:
canMinimizeChrome &&
collapsed &&
MediaQuery.viewInsetsOf(context).bottom == 0,
destinations: destinations,
selectedIndex: selectedDestination,
onSelected: _onNavTap,
onHome: () => _onNavTap(0),
onSearch: ShellNavigationService.requestSearch,
blurEnabled: ref.watch(mornyeBlurEnabledProvider),
: _KeyboardOpenProvider(
child: ValueListenableBuilder<bool>(
valueListenable: _mornyeChrome,
builder: (context, collapsed, _) =>
MornyeBottomBar(
collapsed:
canMinimizeChrome &&
collapsed &&
!_KeyboardOpenScope.of(context),
destinations: destinations,
selectedIndex: selectedDestination,
onSelected: _onNavTap,
onHome: () => _onNavTap(0),
onSearch:
ShellNavigationService.requestSearch,
blurEnabled: mornyeBlurEnabled,
),
),
),
),
@@ -1535,6 +1545,33 @@ class _MainShellState extends ConsumerState<MainShell>
}
}
/// Tells the Mornye bottom bar only whether the keyboard is open, so the
/// frames of the keyboard's own animation do not rebuild the bar.
class _KeyboardOpenProvider extends StatelessWidget {
const _KeyboardOpenProvider({required this.child});
final Widget child;
@override
Widget build(BuildContext context) => _KeyboardOpenScope(
open: MediaQuery.viewInsetsOf(context).bottom > 0,
child: child,
);
}
class _KeyboardOpenScope extends InheritedWidget {
const _KeyboardOpenScope({required this.open, required super.child});
final bool open;
static bool of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<_KeyboardOpenScope>()!.open;
@override
bool updateShouldNotify(_KeyboardOpenScope oldWidget) =>
open != oldWidget.open;
}
class _TabNavigator extends StatefulWidget {
final GlobalKey<NavigatorState> navigatorKey;
final Widget child;
+7 -3
View File
@@ -1,11 +1,14 @@
part of 'main_shell.dart';
extension _MainShellStartupPrompts on _MainShellState {
Future<void> _repairSafAccessIfNeeded({bool knownLost = false}) async {
Future<void> _repairSafAccessIfNeeded({
bool knownLost = false,
bool alreadyChecked = false,
}) async {
if (!Platform.isAndroid || _safRepairDialogVisible) return;
var accessLost = knownLost;
if (!accessLost) {
if (!accessLost && !alreadyChecked) {
final settings = ref.read(settingsProvider);
if (settings.storageMode != 'saf' || settings.downloadTreeUri.isEmpty) {
return;
@@ -149,11 +152,12 @@ extension _MainShellStartupPrompts on _MainShellState {
if (settings.storageMode == 'saf') return;
if (settings.downloadDirectory.isEmpty) return;
if (await _safMigrationPromptStore.wasShown()) return;
final deviceInfo = DeviceInfoPlugin();
final androidInfo = await deviceInfo.androidInfo;
if (androidInfo.version.sdkInt < 29) return;
if (await _safMigrationPromptStore.wasShown()) return;
await _safMigrationPromptStore.markShown();
if (!mounted) return;
+18 -13
View File
@@ -113,20 +113,25 @@ class LinkSourcePresence {
/// Link. Read for the app's lifetime on phones and on the desktop.
final linkSourcePresenceProvider = Provider<LinkSourcePresence>((ref) {
late final LinkSourcePresence presence;
presence = LinkSourcePresence(
onChanged: () {
// Not inside a provider build, which must not change other providers.
unawaited(
Future(() {
if (!ref.mounted) return null;
return ref
.read(localLibraryProvider.notifier)
.setNetworkSourceAvailability(presence.availability);
}),
);
},
);
void pushAvailability() {
// Not inside a provider build, which must not change other providers.
unawaited(
Future(() {
// Avoid eagerly instantiating LocalLibraryNotifier on Frame 1 before
// its deferred warmup or first Library tab visit.
if (!ref.mounted || !ref.read(localLibraryProvider.exists)) return null;
return ref
.read(localLibraryProvider.notifier)
.setNetworkSourceAvailability(presence.availability);
}),
);
}
presence = LinkSourcePresence(onChanged: pushAvailability);
ref.onDispose(presence.dispose);
ref.listen(localLibraryProvider.exists, (_, exists) {
if (exists) pushAvailability();
});
ref.listen(
settingsProvider.select((settings) => settings.linkHideDisconnectedSongs),
(_, hide) => presence.enabled = hide,