launcher_controller.dart 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import 'dart:async';
  2. import 'package:flutter/foundation.dart';
  3. import '../../data/models/app_entry.dart';
  4. import '../../data/models/slot_assignment.dart';
  5. import '../../data/models/slot_type.dart';
  6. import '../../data/repositories/settings_repository.dart';
  7. import '../../data/services/native_bridge.dart';
  8. /// Owns installed apps, shortcut assignments and the default-home state.
  9. class LauncherController extends ChangeNotifier {
  10. LauncherController(this._platform, this._settings);
  11. final LauncherPlatform _platform;
  12. final SettingsRepository _settings;
  13. static const maxHomeButtons = 16;
  14. final Map<SlotType, SlotAssignment> _slots = {};
  15. final Map<SlotType, bool> _slotEnabled = {};
  16. final List<SlotAssignment> _pinnedApps = [];
  17. bool _jellyfinConfigured = false;
  18. List<AppEntry> _apps = const [];
  19. bool _appsLoaded = false;
  20. bool _loadingApps = false;
  21. Object? _appsError;
  22. DateTime? _lastAppsLoad;
  23. bool _defaultHome = false;
  24. bool _defaultHomeKnown = false;
  25. Timer? _stateTimer;
  26. bool _disposed = false;
  27. List<AppEntry> get apps => _apps;
  28. bool get isLoadingApps => _loadingApps;
  29. bool get appsLoaded => _appsLoaded;
  30. Object? get appsError => _appsError;
  31. bool get isDefaultHome => _defaultHome;
  32. bool get defaultHomeKnown => _defaultHomeKnown;
  33. SlotAssignment? assignmentFor(SlotType slot) => _slots[slot];
  34. bool get jellyfinConfigured => _jellyfinConfigured;
  35. bool isSlotEnabled(SlotType slot) {
  36. if (slot == SlotType.jellyfin && !_jellyfinConfigured) return false;
  37. return _slotEnabled[slot] ?? (slot != SlotType.jellyfin);
  38. }
  39. /// Called by the Jellyfin controller sync. A missing/invalid pairing turns
  40. /// the Jellyfin Home button off and clears the preference, so the 16-button
  41. /// count cannot reserve an invisible slot.
  42. Future<void> setJellyfinConfigured(bool configured) async {
  43. if (_jellyfinConfigured == configured) return;
  44. _jellyfinConfigured = configured;
  45. if (!configured && (_slotEnabled[SlotType.jellyfin] ?? false)) {
  46. _slotEnabled[SlotType.jellyfin] = false;
  47. await _settings.setSlotEnabled(SlotType.jellyfin, false);
  48. }
  49. _notify();
  50. }
  51. /// All apps is always present. Settings lives in the top-right status area,
  52. /// so the fixed slots (while enabled) and each pinned app fill the cap.
  53. int get homeButtonCount =>
  54. 1 + SlotType.values.where(isSlotEnabled).length + _pinnedApps.length;
  55. int get enabledSlotCount => SlotType.values.where(isSlotEnabled).length;
  56. List<SlotAssignment> get pinnedApps => List.unmodifiable(_pinnedApps);
  57. bool isPinned(SlotAssignment assignment) => _pinnedApps.contains(assignment);
  58. bool get homeRoleHintShown => _settings.homeRoleHintShown;
  59. DateTime? get firstLaunchAt => _settings.firstLaunchAt;
  60. Future<void> markHomeRoleHintShown() {
  61. return _settings.setHomeRoleHintShown(true);
  62. }
  63. AppEntry? appForAssignment(SlotAssignment assignment) {
  64. for (final app in _apps) {
  65. if (app.matches(assignment)) return app;
  66. }
  67. return null;
  68. }
  69. /// Loads persisted choices synchronously, then refreshes platform state in
  70. /// the background so the first frame is not blocked by package enumeration.
  71. void initialize() {
  72. for (final slot in SlotType.values) {
  73. _slotEnabled[slot] = _settings.slotEnabled(slot);
  74. if (!slot.isAppSlot) continue;
  75. final assignment = _settings.slot(slot);
  76. if (assignment != null) _slots[slot] = assignment;
  77. }
  78. _pinnedApps.addAll(_settings.pinnedApps);
  79. final loadedCount = homeButtonCount;
  80. var trimmed = false;
  81. while (homeButtonCount > maxHomeButtons && _pinnedApps.isNotEmpty) {
  82. _pinnedApps.removeLast();
  83. trimmed = true;
  84. }
  85. if (trimmed || loadedCount != homeButtonCount) {
  86. unawaited(_settings.setPinnedApps(_pinnedApps));
  87. }
  88. _notify();
  89. unawaited(refreshDefaultHome());
  90. unawaited(loadApps());
  91. }
  92. Future<void> loadApps({bool force = false}) async {
  93. if (_loadingApps) return;
  94. if (_appsLoaded && !force) return;
  95. _loadingApps = true;
  96. _appsError = null;
  97. _notify();
  98. try {
  99. final loaded = await _platform.listApps();
  100. _apps = List<AppEntry>.unmodifiable(loaded);
  101. _appsLoaded = true;
  102. _lastAppsLoad = DateTime.now();
  103. await _validateAssignments();
  104. } catch (error) {
  105. _appsError = error;
  106. } finally {
  107. _loadingApps = false;
  108. _notify();
  109. }
  110. }
  111. /// Called when the launcher returns to the foreground. The package list is
  112. /// refreshed at most once a minute unless [forceApps] is set.
  113. Future<void> refresh({bool forceApps = false}) async {
  114. await refreshDefaultHome();
  115. final last = _lastAppsLoad;
  116. if (forceApps ||
  117. last == null ||
  118. DateTime.now().difference(last).inSeconds > 60) {
  119. await loadApps(force: true);
  120. }
  121. }
  122. Future<void> _validateAssignments() async {
  123. final installed = _apps
  124. .map((app) => '${app.packageName}/${app.activityName}')
  125. .toSet();
  126. final missing = <SlotType>[];
  127. _slots.forEach((slot, assignment) {
  128. if (!installed.contains(
  129. '${assignment.packageName}/${assignment.activityName}',
  130. )) {
  131. missing.add(slot);
  132. }
  133. });
  134. for (final slot in missing) {
  135. _slots.remove(slot);
  136. await _settings.clearSlot(slot);
  137. }
  138. final missingPinned = _pinnedApps
  139. .where(
  140. (assignment) => !installed.contains(
  141. '${assignment.packageName}/${assignment.activityName}',
  142. ),
  143. )
  144. .toList(growable: false);
  145. if (missingPinned.isNotEmpty) {
  146. _pinnedApps.removeWhere(missingPinned.contains);
  147. await _settings.setPinnedApps(_pinnedApps);
  148. }
  149. }
  150. Future<void> assign(SlotType slot, AppEntry app) async {
  151. if (!slot.isAppSlot) return;
  152. final assignment = app.toAssignment();
  153. _slots[slot] = assignment;
  154. await _settings.setSlot(slot, assignment);
  155. _notify();
  156. }
  157. Future<void> clearSlot(SlotType slot) async {
  158. if (!slot.isAppSlot) return;
  159. _slots.remove(slot);
  160. await _settings.clearSlot(slot);
  161. _notify();
  162. }
  163. /// Hides or shows a predefined home button. Disabled slots keep their app
  164. /// assignment, so re-enabling restores the same shortcut.
  165. Future<String?> setSlotEnabled(SlotType slot, bool enabled) async {
  166. if (slot == SlotType.jellyfin && !_jellyfinConfigured) {
  167. return 'Pair Jellyfin in Settings first.';
  168. }
  169. if (isSlotEnabled(slot) == enabled) return null;
  170. if (enabled && homeButtonCount >= maxHomeButtons) {
  171. return 'Home screen is full ($maxHomeButtons buttons). '
  172. 'Remove an app or turn off another button first.';
  173. }
  174. _slotEnabled[slot] = enabled;
  175. await _settings.setSlotEnabled(slot, enabled);
  176. _notify();
  177. return null;
  178. }
  179. /// Pins an app from All Apps to the home screen. Returns an error message
  180. /// when the app is already present or the 16-button limit is reached.
  181. Future<String?> addPinnedApp(AppEntry app) async {
  182. final assignment = app.toAssignment();
  183. final alreadyPinned = _pinnedApps.contains(assignment);
  184. final alreadyInVisibleSlot = SlotType.values.any(
  185. (slot) => isSlotEnabled(slot) && _slots[slot] == assignment,
  186. );
  187. if (alreadyPinned || alreadyInVisibleSlot) {
  188. return '${app.label} is already on the Home screen.';
  189. }
  190. if (homeButtonCount >= maxHomeButtons) {
  191. return 'Home screen is full ($maxHomeButtons buttons). '
  192. 'Remove a button first.';
  193. }
  194. _pinnedApps.add(assignment);
  195. await _settings.setPinnedApps(_pinnedApps);
  196. _notify();
  197. return null;
  198. }
  199. Future<void> removePinnedApp(SlotAssignment assignment) async {
  200. if (!_pinnedApps.remove(assignment)) return;
  201. await _settings.setPinnedApps(_pinnedApps);
  202. _notify();
  203. }
  204. Future<void> renamePinnedApp(SlotAssignment assignment, String label) async {
  205. final trimmed = label.trim();
  206. if (trimmed.isEmpty) return;
  207. final index = _pinnedApps.indexOf(assignment);
  208. if (index < 0) return;
  209. final current = _pinnedApps[index];
  210. _pinnedApps[index] = SlotAssignment(
  211. packageName: current.packageName,
  212. activityName: current.activityName,
  213. label: trimmed,
  214. iconAsset: current.iconAsset,
  215. );
  216. await _settings.setPinnedApps(_pinnedApps);
  217. _notify();
  218. }
  219. Future<void> setPinnedIcon(
  220. SlotAssignment assignment,
  221. String? iconAsset,
  222. ) async {
  223. final index = _pinnedApps.indexOf(assignment);
  224. if (index < 0) return;
  225. final current = _pinnedApps[index];
  226. _pinnedApps[index] = SlotAssignment(
  227. packageName: current.packageName,
  228. activityName: current.activityName,
  229. label: current.label,
  230. iconAsset: iconAsset,
  231. );
  232. await _settings.setPinnedApps(_pinnedApps);
  233. _notify();
  234. }
  235. Future<String?> launchSlot(SlotType slot) async {
  236. if (!slot.isAppSlot) return null;
  237. final assignment = _slots[slot];
  238. if (assignment == null) return null;
  239. return launchAssignment(assignment);
  240. }
  241. Future<String?> launchAssignment(SlotAssignment assignment) async {
  242. try {
  243. await _platform.launchApp(
  244. packageName: assignment.packageName,
  245. activityName: assignment.activityName,
  246. );
  247. return null;
  248. } on LauncherPlatformException catch (error) {
  249. return error.message;
  250. } catch (_) {
  251. return 'Could not open ${assignment.label.isEmpty ? 'this app' : assignment.label}.';
  252. }
  253. }
  254. Future<String?> launchAppEntry(AppEntry app) async {
  255. try {
  256. await _platform.launchApp(
  257. packageName: app.packageName,
  258. activityName: app.activityName,
  259. );
  260. return null;
  261. } on LauncherPlatformException catch (error) {
  262. return error.message;
  263. } catch (_) {
  264. return 'Could not open ${app.label}.';
  265. }
  266. }
  267. Future<void> refreshDefaultHome() async {
  268. try {
  269. _defaultHome = await _platform.isDefaultHome();
  270. } catch (_) {
  271. _defaultHome = false;
  272. }
  273. _defaultHomeKnown = true;
  274. _notify();
  275. }
  276. Future<bool> requestDefaultHome() async {
  277. final launched = await _platform.requestDefaultHome();
  278. if (launched) {
  279. // The system dialog will pause us; refresh again after it closes.
  280. _stateTimer?.cancel();
  281. _stateTimer = Timer(const Duration(seconds: 2), () {
  282. unawaited(refreshDefaultHome());
  283. });
  284. }
  285. return launched;
  286. }
  287. void _notify() {
  288. if (!_disposed) notifyListeners();
  289. }
  290. @override
  291. void dispose() {
  292. _disposed = true;
  293. _stateTimer?.cancel();
  294. super.dispose();
  295. }
  296. }