launcher_controller.dart 9.2 KB

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