From 5c6fa36291c23e2f9e5dd92b377a4e53c76f2a6d Mon Sep 17 00:00:00 2001 From: zarzet <42882290+zarzet@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:57:41 +0700 Subject: [PATCH] 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. --- lib/main.dart | 64 +++++++++++----- .../playback_notification_provider.dart | 10 +-- lib/providers/settings_provider.dart | 63 ++++++++-------- lib/screens/main_shell.dart | 73 ++++++++++++++----- lib/screens/main_shell_startup_prompts.dart | 10 ++- lib/services/link/link_source_presence.dart | 31 ++++---- 6 files changed, 163 insertions(+), 88 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index e94d5325f..b1505e4d7 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -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 _prepareAndroidInstallationState(SharedPreferences prefs) async { +Future _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 _detectInitialSafAccessLoss( - Future<(bool, Object?)>? validation, +/// True when the grant is lost, null when the check gave no answer. +Future _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 Future _initializeAppServices() async { try { - await CoverCacheManager.initialize(); - CoverCacheManager.scheduleMaintenance(); await Future.wait([ + CoverCacheManager.initialize().then( + (_) => CoverCacheManager.scheduleMaintenance(), + ), NotificationService().initialize(), ShareIntentService().initialize(), AudioFileOpenService.instance.initialize(), diff --git a/lib/providers/playback_notification_provider.dart b/lib/providers/playback_notification_provider.dart index e3e12af29..ac72cb9c4 100644 --- a/lib/providers/playback_notification_provider.dart +++ b/lib/providers/playback_notification_provider.dart @@ -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; diff --git a/lib/providers/settings_provider.dart b/lib/providers/settings_provider.dart index 8fa3ae9df..998eb2497 100644 --- a/lib/providers/settings_provider.dart +++ b/lib/providers/settings_provider.dart @@ -40,10 +40,9 @@ final initialSettingsProvider = Provider( (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((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?>((ref) => null); bool hasPersistedAppSettings(SharedPreferences prefs) { final rawSettings = prefs.getString(_settingsKey); @@ -245,9 +244,11 @@ class SettingsNotifier extends Notifier { 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 { 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 _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 _syncExtensionFallbackSettingsToBackend() async { diff --git a/lib/screens/main_shell.dart b/lib/screens/main_shell.dart index 829a270f1..82848ddc5 100644 --- a/lib/screens/main_shell.dart +++ b/lib/screens/main_shell.dart @@ -190,6 +190,10 @@ class _MainShellState extends ConsumerState 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 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 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 ), child: useNavigationRail ? const MiniPlayer() - : ValueListenableBuilder( - 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( + 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 } } +/// 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 navigatorKey; final Widget child; diff --git a/lib/screens/main_shell_startup_prompts.dart b/lib/screens/main_shell_startup_prompts.dart index a3b3df63c..48195e716 100644 --- a/lib/screens/main_shell_startup_prompts.dart +++ b/lib/screens/main_shell_startup_prompts.dart @@ -1,11 +1,14 @@ part of 'main_shell.dart'; extension _MainShellStartupPrompts on _MainShellState { - Future _repairSafAccessIfNeeded({bool knownLost = false}) async { + Future _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; diff --git a/lib/services/link/link_source_presence.dart b/lib/services/link/link_source_presence.dart index dfe1681e1..ea2795e53 100644 --- a/lib/services/link/link_source_presence.dart +++ b/lib/services/link/link_source_presence.dart @@ -113,20 +113,25 @@ class LinkSourcePresence { /// Link. Read for the app's lifetime on phones and on the desktop. final linkSourcePresenceProvider = Provider((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,