launcher_controller.dart 9.3 KB

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