| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339 |
- import 'dart:async';
- import 'package:flutter/foundation.dart';
- import '../../data/models/app_entry.dart';
- import '../../data/models/slot_assignment.dart';
- import '../../data/models/slot_type.dart';
- import '../../data/repositories/settings_repository.dart';
- import '../../data/services/native_bridge.dart';
- /// Owns installed apps, shortcut assignments and the default-home state.
- class LauncherController extends ChangeNotifier {
- LauncherController(this._platform, this._settings);
- final LauncherPlatform _platform;
- final SettingsRepository _settings;
- static const maxHomeButtons = 16;
- final Map<SlotType, SlotAssignment> _slots = {};
- final Map<SlotType, bool> _slotEnabled = {};
- final List<SlotAssignment> _pinnedApps = [];
- bool _jellyfinConfigured = false;
- List<AppEntry> _apps = const [];
- bool _appsLoaded = false;
- bool _loadingApps = false;
- Object? _appsError;
- DateTime? _lastAppsLoad;
- bool _defaultHome = false;
- bool _defaultHomeKnown = false;
- Timer? _stateTimer;
- bool _disposed = false;
- List<AppEntry> get apps => _apps;
- bool get isLoadingApps => _loadingApps;
- bool get appsLoaded => _appsLoaded;
- Object? get appsError => _appsError;
- bool get isDefaultHome => _defaultHome;
- bool get defaultHomeKnown => _defaultHomeKnown;
- SlotAssignment? assignmentFor(SlotType slot) => _slots[slot];
- bool get jellyfinConfigured => _jellyfinConfigured;
- bool isSlotEnabled(SlotType slot) {
- if (slot == SlotType.jellyfin && !_jellyfinConfigured) return false;
- return _slotEnabled[slot] ?? (slot != SlotType.jellyfin);
- }
- /// Called by the Jellyfin controller sync. A missing/invalid pairing turns
- /// the Jellyfin Home button off and clears the preference, so the 16-button
- /// count cannot reserve an invisible slot.
- Future<void> setJellyfinConfigured(bool configured) async {
- if (_jellyfinConfigured == configured) return;
- _jellyfinConfigured = configured;
- if (!configured && (_slotEnabled[SlotType.jellyfin] ?? false)) {
- _slotEnabled[SlotType.jellyfin] = false;
- await _settings.setSlotEnabled(SlotType.jellyfin, false);
- }
- _notify();
- }
- /// All apps is always present. Settings lives in the top-right status area,
- /// so the fixed slots (while enabled) and each pinned app fill the cap.
- int get homeButtonCount =>
- 1 + SlotType.values.where(isSlotEnabled).length + _pinnedApps.length;
- int get enabledSlotCount => SlotType.values.where(isSlotEnabled).length;
- List<SlotAssignment> get pinnedApps => List.unmodifiable(_pinnedApps);
- bool isPinned(SlotAssignment assignment) => _pinnedApps.contains(assignment);
- bool get homeRoleHintShown => _settings.homeRoleHintShown;
- DateTime? get firstLaunchAt => _settings.firstLaunchAt;
- Future<void> markHomeRoleHintShown() {
- return _settings.setHomeRoleHintShown(true);
- }
- AppEntry? appForAssignment(SlotAssignment assignment) {
- for (final app in _apps) {
- if (app.matches(assignment)) return app;
- }
- return null;
- }
- /// Loads persisted choices synchronously, then refreshes platform state in
- /// the background so the first frame is not blocked by package enumeration.
- void initialize() {
- for (final slot in SlotType.values) {
- _slotEnabled[slot] = _settings.slotEnabled(slot);
- if (!slot.isAppSlot) continue;
- final assignment = _settings.slot(slot);
- if (assignment != null) _slots[slot] = assignment;
- }
- _pinnedApps.addAll(_settings.pinnedApps);
- final loadedCount = homeButtonCount;
- var trimmed = false;
- while (homeButtonCount > maxHomeButtons && _pinnedApps.isNotEmpty) {
- _pinnedApps.removeLast();
- trimmed = true;
- }
- if (trimmed || loadedCount != homeButtonCount) {
- unawaited(_settings.setPinnedApps(_pinnedApps));
- }
- _notify();
- unawaited(refreshDefaultHome());
- unawaited(loadApps());
- }
- Future<void> loadApps({bool force = false}) async {
- if (_loadingApps) return;
- if (_appsLoaded && !force) return;
- _loadingApps = true;
- _appsError = null;
- _notify();
- try {
- final loaded = await _platform.listApps();
- _apps = List<AppEntry>.unmodifiable(loaded);
- _appsLoaded = true;
- _lastAppsLoad = DateTime.now();
- await _validateAssignments();
- } catch (error) {
- _appsError = error;
- } finally {
- _loadingApps = false;
- _notify();
- }
- }
- /// Called when the launcher returns to the foreground. The package list is
- /// refreshed at most once a minute unless [forceApps] is set.
- Future<void> refresh({bool forceApps = false}) async {
- await refreshDefaultHome();
- final last = _lastAppsLoad;
- if (forceApps ||
- last == null ||
- DateTime.now().difference(last).inSeconds > 60) {
- await loadApps(force: true);
- }
- }
- Future<void> _validateAssignments() async {
- final installed = _apps
- .map((app) => '${app.packageName}/${app.activityName}')
- .toSet();
- final missing = <SlotType>[];
- _slots.forEach((slot, assignment) {
- if (!installed.contains(
- '${assignment.packageName}/${assignment.activityName}',
- )) {
- missing.add(slot);
- }
- });
- for (final slot in missing) {
- _slots.remove(slot);
- await _settings.clearSlot(slot);
- }
- final missingPinned = _pinnedApps
- .where(
- (assignment) => !installed.contains(
- '${assignment.packageName}/${assignment.activityName}',
- ),
- )
- .toList(growable: false);
- if (missingPinned.isNotEmpty) {
- _pinnedApps.removeWhere(missingPinned.contains);
- await _settings.setPinnedApps(_pinnedApps);
- }
- }
- Future<void> assign(SlotType slot, AppEntry app) async {
- if (!slot.isAppSlot) return;
- final assignment = app.toAssignment();
- _slots[slot] = assignment;
- await _settings.setSlot(slot, assignment);
- _notify();
- }
- Future<void> clearSlot(SlotType slot) async {
- if (!slot.isAppSlot) return;
- _slots.remove(slot);
- await _settings.clearSlot(slot);
- _notify();
- }
- /// Hides or shows a predefined home button. Disabled slots keep their app
- /// assignment, so re-enabling restores the same shortcut.
- Future<String?> setSlotEnabled(SlotType slot, bool enabled) async {
- if (slot == SlotType.jellyfin && !_jellyfinConfigured) {
- return 'Pair Jellyfin in Settings first.';
- }
- if (isSlotEnabled(slot) == enabled) return null;
- if (enabled && homeButtonCount >= maxHomeButtons) {
- return 'Home screen is full ($maxHomeButtons buttons). '
- 'Remove an app or turn off another button first.';
- }
- _slotEnabled[slot] = enabled;
- await _settings.setSlotEnabled(slot, enabled);
- _notify();
- return null;
- }
- /// Pins an app from All Apps to the home screen. Returns an error message
- /// when the app is already present or the 16-button limit is reached.
- Future<String?> addPinnedApp(AppEntry app) async {
- final assignment = app.toAssignment();
- final alreadyPinned = _pinnedApps.contains(assignment);
- final alreadyInVisibleSlot = SlotType.values.any(
- (slot) => isSlotEnabled(slot) && _slots[slot] == assignment,
- );
- if (alreadyPinned || alreadyInVisibleSlot) {
- return '${app.label} is already on the Home screen.';
- }
- if (homeButtonCount >= maxHomeButtons) {
- return 'Home screen is full ($maxHomeButtons buttons). '
- 'Remove a button first.';
- }
- _pinnedApps.add(assignment);
- await _settings.setPinnedApps(_pinnedApps);
- _notify();
- return null;
- }
- Future<void> removePinnedApp(SlotAssignment assignment) async {
- if (!_pinnedApps.remove(assignment)) return;
- await _settings.setPinnedApps(_pinnedApps);
- _notify();
- }
- Future<void> renamePinnedApp(SlotAssignment assignment, String label) async {
- final trimmed = label.trim();
- if (trimmed.isEmpty) return;
- final index = _pinnedApps.indexOf(assignment);
- if (index < 0) return;
- final current = _pinnedApps[index];
- _pinnedApps[index] = SlotAssignment(
- packageName: current.packageName,
- activityName: current.activityName,
- label: trimmed,
- iconAsset: current.iconAsset,
- );
- await _settings.setPinnedApps(_pinnedApps);
- _notify();
- }
- Future<void> setPinnedIcon(
- SlotAssignment assignment,
- String? iconAsset,
- ) async {
- final index = _pinnedApps.indexOf(assignment);
- if (index < 0) return;
- final current = _pinnedApps[index];
- _pinnedApps[index] = SlotAssignment(
- packageName: current.packageName,
- activityName: current.activityName,
- label: current.label,
- iconAsset: iconAsset,
- );
- await _settings.setPinnedApps(_pinnedApps);
- _notify();
- }
- Future<String?> launchSlot(SlotType slot) async {
- if (!slot.isAppSlot) return null;
- final assignment = _slots[slot];
- if (assignment == null) return null;
- return launchAssignment(assignment);
- }
- Future<String?> launchAssignment(SlotAssignment assignment) async {
- try {
- await _platform.launchApp(
- packageName: assignment.packageName,
- activityName: assignment.activityName,
- );
- return null;
- } on LauncherPlatformException catch (error) {
- return error.message;
- } catch (_) {
- return 'Could not open ${assignment.label.isEmpty ? 'this app' : assignment.label}.';
- }
- }
- Future<String?> launchAppEntry(AppEntry app) async {
- try {
- await _platform.launchApp(
- packageName: app.packageName,
- activityName: app.activityName,
- );
- return null;
- } on LauncherPlatformException catch (error) {
- return error.message;
- } catch (_) {
- return 'Could not open ${app.label}.';
- }
- }
- Future<void> refreshDefaultHome() async {
- try {
- _defaultHome = await _platform.isDefaultHome();
- } catch (_) {
- _defaultHome = false;
- }
- _defaultHomeKnown = true;
- _notify();
- }
- Future<bool> requestDefaultHome() async {
- final launched = await _platform.requestDefaultHome();
- if (launched) {
- // The system dialog will pause us; refresh again after it closes.
- _stateTimer?.cancel();
- _stateTimer = Timer(const Duration(seconds: 2), () {
- unawaited(refreshDefaultHome());
- });
- }
- return launched;
- }
- void _notify() {
- if (!_disposed) notifyListeners();
- }
- @override
- void dispose() {
- _disposed = true;
- _stateTimer?.cancel();
- super.dispose();
- }
- }
|