From b26025cf2172a6168664706571aebbf06be6ca8a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 16:05:31 +0000 Subject: [PATCH 1/3] Android: Apps block in Explore, faster Apps tab, SD card in the drive menu - Explore shows the space a file scan can not see on Android as an Apps block (with the usage access button, then the real size and a link to the Apps tab) plus a System block for the rest - App sizes are read in parallel, kept between runs and loaded at start, so the Apps tab shows a list right away - Internal storage and SD cards or USB drives show up in the drive menu Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AHutN3owoAasdzkZtzcMcD --- .../kotlin/io/ontola/spaceman/MainActivity.kt | 56 +++++- lib/app_model.dart | 123 +++++++++++- lib/drives.dart | 23 ++- lib/main.dart | 21 +- lib/platform.dart | 36 ++++ lib/screens/apps.dart | 142 +++++++------- lib/screens/explorer.dart | 42 ++-- lib/widgets/not_scanned.dart | 181 ++++++++++++++---- lib/widgets/scan_header.dart | 34 ++-- lib/widgets/treemap.dart | 77 ++++---- test/apps_screen_test.dart | 18 +- test/widgets_test.dart | 60 ++++++ 12 files changed, 612 insertions(+), 201 deletions(-) diff --git a/android/app/src/main/kotlin/io/ontola/spaceman/MainActivity.kt b/android/app/src/main/kotlin/io/ontola/spaceman/MainActivity.kt index 705c507..a8f9d72 100644 --- a/android/app/src/main/kotlin/io/ontola/spaceman/MainActivity.kt +++ b/android/app/src/main/kotlin/io/ontola/spaceman/MainActivity.kt @@ -35,6 +35,7 @@ class MainActivity : FlutterActivity() { } "storageRoot" -> result.success(Environment.getExternalStorageDirectory().absolutePath) + "storageVolumes" -> result.success(storageVolumes()) "hasUsageAccess" -> result.success(hasUsageAccess()) "requestUsageAccess" -> { openSettings(Settings.ACTION_USAGE_ACCESS_SETTINGS) @@ -103,6 +104,33 @@ class MainActivity : FlutterActivity() { } } + /// Internal storage and any SD card or USB drive that is mounted, each + /// with the folder it is at and the name Android shows for it. + private fun storageVolumes(): List> { + val sm = getSystemService(StorageManager::class.java) + val found = mutableListOf>() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + for (v in sm.storageVolumes) { + if (v.state != Environment.MEDIA_MOUNTED) continue + val dir = v.directory ?: continue + found.add(volume(dir.absolutePath, v.getDescription(this), v.isPrimary)) + } + } else { + // Older Android has no public path per volume; the app's own + // folder on each one sits at /Android/data/. + for (f in getExternalFilesDirs(null)) { + if (f == null) continue + val path = f.absolutePath.substringBefore("/Android/data/") + val v = sm.getStorageVolume(f) ?: continue + found.add(volume(path, v.getDescription(this), v.isPrimary)) + } + } + return found + } + + private fun volume(path: String, name: String, primary: Boolean) = + mapOf("path" to path, "name" to name, "primary" to primary) + private fun hasUsageAccess(): Boolean { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return false val appOps = getSystemService(AppOpsManager::class.java) @@ -129,7 +157,26 @@ class MainActivity : FlutterActivity() { val stats = getSystemService(StorageStatsManager::class.java) val user = Process.myUserHandle() val uuid = StorageManager.UUID_DEFAULT - val apps = packageManager.getInstalledApplications(0).mapNotNull { info -> + // One query per app, and phones have hundreds: ask in parallel. + val pool = java.util.concurrent.Executors.newFixedThreadPool(8) + val futures = packageManager.getInstalledApplications(0).map { info -> + pool.submit(java.util.concurrent.Callable { appSize(stats, uuid, user, info) }) + } + val apps = futures.mapNotNull { it.get() } + pool.shutdown() + return mapOf( + "apps" to apps, + "total" to stats.getTotalBytes(uuid), + "free" to stats.getFreeBytes(uuid), + ) + } + + private fun appSize( + stats: StorageStatsManager, + uuid: java.util.UUID, + user: android.os.UserHandle, + info: ApplicationInfo, + ): Map? = try { val s = stats.queryStatsForPackage(uuid, info.packageName, user) mapOf( @@ -144,13 +191,6 @@ class MainActivity : FlutterActivity() { } catch (e: Exception) { null } - } - return mapOf( - "apps" to apps, - "total" to stats.getTotalBytes(uuid), - "free" to stats.getFreeBytes(uuid), - ) - } private fun openSettings(action: String, pkg: String? = packageName) { try { diff --git a/lib/app_model.dart b/lib/app_model.dart index 24fddbd..34588c2 100644 --- a/lib/app_model.dart +++ b/lib/app_model.dart @@ -1,8 +1,10 @@ import 'dart:async'; +import 'dart:convert'; import 'dart:io'; import 'dart:math' as math; import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; import 'package:path_provider/path_provider.dart'; import 'drives.dart'; @@ -23,6 +25,22 @@ enum DiskAccess { undecided, } +/// What part of the space the scan does not see a block in Explore stands +/// for. +enum UnscannedKind { + /// Unknown: folders the scan skipped or could not read, the system, ... + unknown, + + /// Android: installed apps and their data, which live outside shared + /// storage. Sized by Android once SpaceMan has usage access. + apps, + + /// Android: what is left besides the apps and the user's files. + system, +} + +typedef UnscannedPart = ({UnscannedKind kind, int size}); + /// App-wide state. The scanned tree itself lives in Rust; this only keeps /// track of what the UI is showing and forwards actions to the core. class AppModel extends ChangeNotifier { @@ -37,8 +55,8 @@ class AppModel extends ChangeNotifier { Drive? get rootDrive => drives.where((d) => d.path == root).firstOrNull; /// Reads the disks again, e.g. when the user opens the drive menu. - void refreshDrives() { - drives = listDrives(); + Future refreshDrives() async { + drives = await loadDrives(); notifyListeners(); } @@ -78,12 +96,87 @@ class AppModel extends ChangeNotifier { } } + /// The tab that is shown: Explore, Clean up, Do not touch, Apps. + int tab = 0; + + void showTab(int i) { + tab = i; + notifyListeners(); + } + + static const appsTab = 3; + + /// Android: whether SpaceMan may read app sizes (usage access), unknown + /// until checked. + bool? usageAccess; + + /// Android: the sizes of installed apps: from the last time, until read + /// again. + AppSizes? apps; + bool loadingApps = false; + String? appsError; + + /// Null until [init] knows where settings go. + File? get _appsFile => + _configured ? File('$_configDir/app_sizes.json') : null; + bool _configured = false; + + /// Reads app sizes from Android, which takes a while with hundreds of + /// apps. Done at start and whenever SpaceMan comes back to the front + /// (usage access may have been granted, apps cleared or uninstalled). + Future loadApps() async { + if (!onAndroid || loadingApps) return; + usageAccess = await hasUsageAccess(); + notifyListeners(); + if (usageAccess != true) return; + loadingApps = true; + notifyListeners(); + try { + apps = await appSizes(); + appsError = null; + try { + await _appsFile?.writeAsString(jsonEncode(appSizesToJson(apps!))); + } on FileSystemException { + // Next start just waits for Android again. + } + } on Exception catch (e) { + appsError = '$e'; + } finally { + loadingApps = false; + notifyListeners(); + } + } + + Future _loadCachedApps() async { + try { + apps = appSizesFromJson( + jsonDecode(await _appsFile!.readAsString()) as Map, + ); + } on Object { + // No earlier result, or an unreadable one: wait for Android. + } + } + + AppLifecycleListener? _lifecycle; + + /// Android, or a test that pretends to be (tests default to Android as + /// the target platform, so only an explicit override counts). + static bool get onAndroid => + Platform.isAndroid || + debugDefaultTargetPlatformOverride == TargetPlatform.android; + /// Loads settings and the cached scan, then refreshes it in the background. Future init() async { _configDir = (await getApplicationSupportDirectory()).path; + _configured = true; final cacheDir = (await getApplicationCacheDirectory()).path; core.configure(configDir: _configDir, cacheDir: cacheDir); protectedPaths = core.protectedPaths(); + if (onAndroid) { + await _loadCachedApps(); + _lifecycle = AppLifecycleListener(onResume: loadApps); + unawaited(loadApps()); + } // Without Full Disk Access, start with a scan that never makes macOS // prompt; the header offers to grant access. Android without access // would only see the app's own files, so explain that first. @@ -98,7 +191,7 @@ class AppModel extends ChangeNotifier { } on FileSystemException { // First launch: the list. } - drives = listDrives(); + drives = await loadDrives(); root = await _initialRoot(); notifyListeners(); @@ -416,7 +509,7 @@ class AppModel extends ChangeNotifier { if (live || rootNode == null) return false; // Small gaps are rounding and metadata, not worth a tile. if (unscanned < unscannedThreshold) return false; - if (Platform.isAndroid) return true; + if (onAndroid) return true; final home = core.homeDir(); if (home == null) return false; // A volume root such as `/` or `C:\` already ends in a separator. @@ -429,8 +522,30 @@ class AppModel extends ChangeNotifier { static const unscannedThreshold = 1024 * 1024 * 1024; + /// The blocks Explore shows for [unscanned]. On Android: the apps (sized + /// by Android once it lets us) and what is left. Elsewhere: one block. + List get unscannedParts { + if (!showsUnscanned) return const []; + final gap = unscanned; + // Apps live on internal storage, not on an SD card. + if (!onAndroid || rootDrive?.main == false) { + return [(kind: UnscannedKind.unknown, size: gap)]; + } + final known = apps; + if (known == null || usageAccess == false) { + return [(kind: UnscannedKind.apps, size: gap)]; + } + final appsTotal = known.apps.fold(0, (s, a) => s + a.total); + final rest = gap - appsTotal; + return [ + (kind: UnscannedKind.apps, size: math.min(appsTotal, gap)), + if (rest >= unscannedThreshold) (kind: UnscannedKind.system, size: rest), + ]; + } + @override void dispose() { + _lifecycle?.dispose(); _scanSub?.cancel(); super.dispose(); } diff --git a/lib/drives.dart b/lib/drives.dart index 0183f9b..33f2df6 100644 --- a/lib/drives.dart +++ b/lib/drives.dart @@ -2,6 +2,7 @@ import 'dart:io'; import 'package:flutter/foundation.dart'; +import 'platform.dart'; import 'src/rust/api/spaceman.dart' as core; /// A disk the user can scan as a whole. @@ -27,8 +28,22 @@ class Drive { @visibleForTesting List Function()? debugDrives; -/// The disks of this computer, the main one first. Empty on phones, where -/// the app scans shared storage instead. +/// The disks of this device, the main one first. On Android: internal +/// storage and any SD card or USB drive. +Future> loadDrives() async { + if (debugDrives != null) return debugDrives!(); + if (!Platform.isAndroid) return listDrives(); + try { + final found = await androidVolumes(); + found.sort((a, b) => (b.$3 ? 1 : 0) - (a.$3 ? 1 : 0)); + return _measure(found); + } on Exception { + return const []; + } +} + +/// The disks of this computer, the main one first. Empty on phones; see +/// [loadDrives]. List listDrives() { if (debugDrives != null) return debugDrives!(); final List<(String, String, bool)> found; @@ -41,6 +56,10 @@ List listDrives() { } else { return const []; } + return _measure(found); +} + +List _measure(List<(String, String, bool)> found) { final drives = []; for (final (path, name, main) in found) { final space = core.diskSpace(path: path); diff --git a/lib/main.dart b/lib/main.dart index 8759603..c75775d 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,5 +1,3 @@ -import 'dart:io'; - import 'package:flutter/material.dart'; import 'package:spaceman/src/rust/frb_generated.dart'; @@ -56,9 +54,8 @@ class HomePage extends StatefulWidget { } class _HomePageState extends State { - int _tab = 0; - - static final _destinations = [ + static List<({IconData icon, IconData active, String label})> + get _destinations => [ ( icon: Icons.folder_open_outlined, active: Icons.folder_open, @@ -71,7 +68,7 @@ class _HomePageState extends State { ), (icon: Icons.lock_outline, active: Icons.lock, label: 'Do not touch'), // Android keeps apps out of reach of the file scan; see AppsScreen. - if (Platform.isAndroid) + if (AppModel.onAndroid) (icon: Icons.apps_outlined, active: Icons.apps, label: 'Apps'), ]; @@ -86,7 +83,7 @@ class _HomePageState extends State { body: SafeArea(child: AccessIntro(model: model)), ); } - final page = switch (_tab) { + final page = switch (model.tab) { 0 => ExplorerScreen(model: model), 1 => CleanupScreen(model: model), 2 => ProtectedScreen(model: model), @@ -107,15 +104,15 @@ class _HomePageState extends State { ScanHeader(model: model, showHelp: !wide), const Divider(height: 1), Expanded(child: page), - if (_tab < 2) SelectionBar(model: model), + if (model.tab < 2) SelectionBar(model: model), ], ); if (!wide) { return Scaffold( body: SafeArea(child: body), bottomNavigationBar: NavigationBar( - selectedIndex: _tab, - onDestinationSelected: (i) => setState(() => _tab = i), + selectedIndex: model.tab, + onDestinationSelected: widget.model.showTab, destinations: [ for (final (i, d) in _destinations.indexed) NavigationDestination( @@ -134,8 +131,8 @@ class _HomePageState extends State { body: Row( children: [ NavigationRail( - selectedIndex: _tab, - onDestinationSelected: (i) => setState(() => _tab = i), + selectedIndex: model.tab, + onDestinationSelected: widget.model.showTab, labelType: NavigationRailLabelType.all, // The logo sits flush at the bottom, out of the way of // the tabs. diff --git a/lib/platform.dart b/lib/platform.dart index 401f72a..59584d8 100644 --- a/lib/platform.dart +++ b/lib/platform.dart @@ -77,6 +77,18 @@ Future requestAndroidStorageAccess() => Future androidStorageRoot() => _storage.invokeMethod('storageRoot'); +/// Internal storage and mounted SD cards or USB drives: folder, the name +/// Android gives it, and whether it is internal storage. +Future> androidVolumes() async { + final list = await _storage.invokeListMethod>( + 'storageVolumes', + ); + return [ + for (final v in list ?? const >[]) + (v['path']! as String, v['name']! as String, v['primary']! as bool), + ]; +} + /// Space used by one installed Android app. class AppSize { AppSize.fromMap(Map m) @@ -101,6 +113,15 @@ class AppSize { final bool system; int get total => app + data; + + Map toMap() => { + 'package': package, + 'label': label, + 'app': app, + 'data': data, + 'cache': cache, + 'system': system, + }; } /// Installed apps and the totals of internal storage. @@ -114,6 +135,21 @@ Future hasUsageAccess() async => Future requestUsageAccess() => _storage.invokeMethod('requestUsageAccess'); +Map appSizesToJson(AppSizes s) => { + 'apps': [for (final a in s.apps) a.toMap()], + 'total': s.total, + 'free': s.free, +}; + +AppSizes appSizesFromJson(Map m) => ( + apps: [ + for (final a in m['apps']! as List) + AppSize.fromMap(a! as Map), + ], + total: m['total'] as int? ?? 0, + free: m['free'] as int? ?? 0, +); + Future appSizes() async { final m = (await _storage.invokeMapMethod('appSizes'))!; return ( diff --git a/lib/screens/apps.dart b/lib/screens/apps.dart index 013ddb4..26abe41 100644 --- a/lib/screens/apps.dart +++ b/lib/screens/apps.dart @@ -18,81 +18,85 @@ class AppsScreen extends StatefulWidget { State createState() => _AppsScreenState(); } -class _AppsScreenState extends State with WidgetsBindingObserver { - bool? _access; - AppSizes? _sizes; - String? _error; +class _AppsScreenState extends State { bool _showSystem = false; - @override - void initState() { - super.initState(); - WidgetsBinding.instance.addObserver(this); - _load(); - } + AppModel get model => widget.model; @override - void dispose() { - WidgetsBinding.instance.removeObserver(this); - super.dispose(); - } + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: model, + builder: (context, _) { + final access = model.usageAccess; + final sizes = model.apps; + if (access == false) return const _UsageAccessIntro(); + if (sizes == null) { + if (model.appsError != null) { + return Center(child: Text(model.appsError!)); + } + return const _Loading(); + } - /// Back from Settings: access may be granted, or an app cleared or - /// uninstalled. - @override - void didChangeAppLifecycleState(AppLifecycleState state) { - if (state == AppLifecycleState.resumed) _load(); + final apps = sizes.apps.where((a) => _showSystem || !a.system).toList() + ..sort((a, b) => b.total.compareTo(a.total)); + final largest = apps.isEmpty ? 1 : apps.first.total; + return RefreshIndicator( + onRefresh: model.loadApps, + child: ListView.builder( + itemCount: apps.length + 1, + itemBuilder: (context, i) { + if (i == 0) { + return _Summary( + sizes: sizes, + files: model.rootNode?.size ?? 0, + refreshing: model.loadingApps, + showSystem: _showSystem, + onShowSystem: (v) => setState(() => _showSystem = v), + ); + } + final app = apps[i - 1]; + return _AppRow(app: app, fraction: app.total / largest); + }, + ), + ); + }, + ); } +} - Future _load() async { - final access = await hasUsageAccess(); - if (!mounted) return; - setState(() => _access = access); - if (!access) return; - try { - final sizes = await appSizes(); - if (!mounted) return; - setState(() { - _sizes = sizes; - _error = null; - }); - } on Exception catch (e) { - if (mounted) setState(() => _error = '$e'); - } - } +/// Android reads the size of every app one by one, which takes a while on +/// the first run; later runs show the last result right away. +class _Loading extends StatelessWidget { + const _Loading(); @override Widget build(BuildContext context) { - final access = _access; - if (access == null) { - return const Center(child: CircularProgressIndicator()); - } - if (!access) return const _UsageAccessIntro(); - if (_error != null) return Center(child: Text(_error!)); - final sizes = _sizes; - if (sizes == null) { - return const Center(child: CircularProgressIndicator()); - } - - final apps = sizes.apps.where((a) => _showSystem || !a.system).toList() - ..sort((a, b) => b.total.compareTo(a.total)); - final largest = apps.isEmpty ? 1 : apps.first.total; - return RefreshIndicator( - onRefresh: _load, - child: ListView.builder( - itemCount: apps.length + 1, - itemBuilder: (context, i) { - if (i == 0) { - return _Summary( - sizes: sizes, - files: widget.model.rootNode?.size ?? 0, - showSystem: _showSystem, - onShowSystem: (v) => setState(() => _showSystem = v), - ); - } - final app = apps[i - 1]; - return _AppRow(app: app, fraction: app.total / largest); - }, + final theme = Theme.of(context); + return Center( + child: Padding( + padding: const EdgeInsets.all(32), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const CircularProgressIndicator(), + const SizedBox(height: 16), + Text( + 'Asking Android how big each app is...', + style: theme.textTheme.titleSmall, + textAlign: TextAlign.center, + ), + const SizedBox(height: 4), + Text( + 'This takes a moment with many apps. Next time the last ' + 'result shows right away.', + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + textAlign: TextAlign.center, + ), + ], + ), ), ); } @@ -103,6 +107,7 @@ class _Summary extends StatelessWidget { const _Summary({ required this.sizes, required this.files, + required this.refreshing, required this.showSystem, required this.onShowSystem, }); @@ -111,6 +116,9 @@ class _Summary extends StatelessWidget { /// Size of the shared storage scan. final int files; + + /// Reading the sizes again; these are from last time. + final bool refreshing; final bool showSystem; final ValueChanged onShowSystem; @@ -135,6 +143,10 @@ class _Summary extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + if (refreshing) ...[ + const LinearProgressIndicator(), + const SizedBox(height: 8), + ], line('Apps and their data', apps), line('Your files (Explore)', files), if (system > 0) line('System and other', system), diff --git a/lib/screens/explorer.dart b/lib/screens/explorer.dart index 76951fe..948264d 100644 --- a/lib/screens/explorer.dart +++ b/lib/screens/explorer.dart @@ -595,21 +595,25 @@ class _ExplorerScreenState extends State final current = crumbs.isEmpty ? model.rootNode! : crumbs.last; // Protected items are out of the way: they live in the Do not touch tab. final items = _items(current.id); - // At the top of the scan, the space it did not see is a row too, in - // its place by size. - final unscanned = current.id == Treemap.rootId && model.showsUnscanned - ? model.unscanned - : 0; - final unscannedAt = unscanned == 0 - ? -1 - : switch (items.indexWhere((n) => n.size < unscanned)) { - -1 => items.length, - final i => i, - }; - final largest = math.max(items.isEmpty ? 1 : items.first.size, unscanned); + // At the top of the scan, the space it did not see gets rows too, in + // their place by size. + final parts = current.id == Treemap.rootId + ? (model.unscannedParts.where((p) => p.size > 0).toList() + ..sort((a, b) => b.size.compareTo(a.size))) + : const []; + // Items and parts merged by size: a part is a record, an item a node. + final rows = [...items]; + for (final p in parts) { + final at = rows.indexWhere((r) => r is NodeView && r.size < p.size); + rows.insert(at == -1 ? rows.length : at, p); + } + final largest = math.max( + items.isEmpty ? 1 : items.first.size, + parts.isEmpty ? 0 : parts.first.size, + ); final list = ListView.builder( key: PageStorageKey(id), - itemCount: items.length + 1 + (unscanned > 0 ? 1 : 0), + itemCount: rows.length + 1, itemBuilder: (context, i) { if (i == 0) { return Padding( @@ -620,11 +624,15 @@ class _ExplorerScreenState extends State ), ); } - if (i - 1 == unscannedAt) { - return UnscannedRow(model: model, fraction: unscanned / largest); + final row = rows[i - 1]; + if (row is UnscannedPart) { + return UnscannedRow( + model: model, + part: row, + fraction: row.size / largest, + ); } - final node = - items[i - 1 - (unscannedAt >= 0 && i - 1 > unscannedAt ? 1 : 0)]; + final node = row as NodeView; final focused = id == model.currentId && node.path == _focusPath; return MouseRegion( onEnter: (_) => _hovered = node, diff --git a/lib/widgets/not_scanned.dart b/lib/widgets/not_scanned.dart index 072fe10..1df5dcf 100644 --- a/lib/widgets/not_scanned.dart +++ b/lib/widgets/not_scanned.dart @@ -167,18 +167,114 @@ class NotScannedDialog extends StatelessWidget { } } -/// The space the scan does not see, as one tile of the treemap: a big -/// question mark, how much it is, and the way to see more. +/// How a block for part of the unscanned space looks and what it does. +class _PartView { + _PartView({ + required this.icon, + required this.title, + required this.size, + required this.summary, + required this.onTap, + this.action, + this.estimate = true, + }); + + final IconData icon; + final String title; + final int size; + final String summary; + final VoidCallback onTap; + + /// The main thing to do about it, such as granting access. + final Widget? action; + + /// The size is the gap in disk use, not measured. + final bool estimate; + + String get sizeText => + estimate ? 'about ${formatBytes(size)}' : formatBytes(size); +} + +_PartView _view(BuildContext context, AppModel model, UnscannedPart part) { + void why() => showNotScanned(context, model); + void seeApps() => model.showTab(AppModel.appsTab); + switch (part.kind) { + case UnscannedKind.unknown: + return _PartView( + icon: Icons.question_mark_rounded, + title: 'Not scanned', + size: part.size, + summary: unscannedSummary(model), + onTap: why, + action: canGrantFullDiskAccess(model) + ? const FullDiskAccessButton(dense: true) + : null, + ); + case UnscannedKind.apps: + final apps = model.apps; + if (model.usageAccess == false) { + return _PartView( + icon: Icons.apps, + title: 'Apps', + size: part.size, + summary: + 'Apps and their data. Android shows how big each one ' + 'is once you allow usage access.', + onTap: seeApps, + action: const FilledButton( + onPressed: requestUsageAccess, + style: ButtonStyle(visualDensity: VisualDensity.compact), + child: Text('Allow usage access'), + ), + ); + } + if (apps == null) { + return _PartView( + icon: Icons.apps, + title: 'Apps', + size: part.size, + summary: 'Asking Android how big each app is...', + onTap: seeApps, + ); + } + return _PartView( + icon: Icons.apps, + title: 'Apps', + size: part.size, + estimate: false, + summary: '${apps.apps.length} apps and their data', + onTap: seeApps, + action: FilledButton.tonal( + onPressed: seeApps, + style: const ButtonStyle(visualDensity: VisualDensity.compact), + child: const Text('See apps'), + ), + ); + case UnscannedKind.system: + return _PartView( + icon: Icons.phone_android, + title: 'System and other', + size: part.size, + summary: 'Android itself and space it keeps aside', + onTap: why, + ); + } +} + +/// Part of the space the scan does not see, as one tile of the treemap: +/// what it is, how big, and the way to see more. class UnscannedTile extends StatelessWidget { - const UnscannedTile({super.key, required this.model}); + const UnscannedTile({super.key, required this.model, required this.part}); final AppModel model; + final UnscannedPart part; @override Widget build(BuildContext context) { final theme = Theme.of(context); final scheme = theme.colorScheme; final muted = scheme.onSurfaceVariant; + final v = _view(context, model, part); return Material( color: scheme.surfaceContainerLow, shape: RoundedRectangleBorder( @@ -187,20 +283,13 @@ class UnscannedTile extends StatelessWidget { ), clipBehavior: Clip.antiAlias, child: InkWell( - onTap: () => showNotScanned(context, model), + onTap: v.onTap, child: LayoutBuilder( builder: (context, c) { - final size = formatBytes(model.unscanned); if (c.maxWidth < 70 || c.maxHeight < 50) { - return Center( - child: Text( - '?', - style: theme.textTheme.titleLarge?.copyWith(color: muted), - ), - ); + return Center(child: Icon(v.icon, size: 20, color: muted)); } final roomy = c.maxWidth >= 220 && c.maxHeight >= 200; - final grant = canGrantFullDiskAccess(model); return Center( child: SingleChildScrollView( physics: const NeverScrollableScrollPhysics(), @@ -208,14 +297,10 @@ class UnscannedTile extends StatelessWidget { child: Column( mainAxisSize: MainAxisSize.min, children: [ - Icon( - Icons.question_mark_rounded, - size: roomy ? 56 : 28, - color: muted, - ), + Icon(v.icon, size: roomy ? 56 : 28, color: muted), const SizedBox(height: 4), Text( - 'Not scanned', + v.title, style: (roomy ? theme.textTheme.titleMedium @@ -224,25 +309,26 @@ class UnscannedTile extends StatelessWidget { overflow: TextOverflow.ellipsis, ), Text( - 'about $size', + v.sizeText, style: theme.textTheme.bodySmall?.copyWith(color: muted), overflow: TextOverflow.ellipsis, ), if (roomy) ...[ const SizedBox(height: 8), Text( - unscannedSummary(model), + v.summary, textAlign: TextAlign.center, style: theme.textTheme.bodySmall?.copyWith( color: muted, ), ), const SizedBox(height: 12), - if (grant) const FullDiskAccessButton(dense: true), - TextButton( - onPressed: () => showNotScanned(context, model), - child: const Text('Why?'), - ), + ?v.action, + if (part.kind == UnscannedKind.unknown) + TextButton( + onPressed: v.onTap, + child: const Text('Why?'), + ), ], ], ), @@ -255,11 +341,17 @@ class UnscannedTile extends StatelessWidget { } } -/// The space the scan does not see, as a row of the Explore list. +/// Part of the space the scan does not see, as a row of the Explore list. class UnscannedRow extends StatelessWidget { - const UnscannedRow({super.key, required this.model, required this.fraction}); + const UnscannedRow({ + super.key, + required this.model, + required this.part, + required this.fraction, + }); final AppModel model; + final UnscannedPart part; /// Size relative to the largest item, for the bar. final double fraction; @@ -267,14 +359,13 @@ class UnscannedRow extends StatelessWidget { @override Widget build(BuildContext context) { final theme = Theme.of(context); + final v = _view(context, model, part); + final narrow = MediaQuery.sizeOf(context).width < 600; return ListTile( - onTap: () => showNotScanned(context, model), - leading: Icon( - Icons.help_outline, - color: theme.colorScheme.onSurfaceVariant, - ), + onTap: v.onTap, + leading: Icon(v.icon, color: theme.colorScheme.onSurfaceVariant), title: Text( - 'Not scanned · ${unscannedSummary(model)}', + narrow ? v.title : '${v.title} · ${v.summary}', overflow: TextOverflow.ellipsis, style: TextStyle(color: theme.colorScheme.onSurfaceVariant), ), @@ -282,28 +373,36 @@ class UnscannedRow extends StatelessWidget { trailing: Row( mainAxisSize: MainAxisSize.min, children: [ - if (canGrantFullDiskAccess(model)) ...[ - const FullDiskAccessButton(dense: true), - const SizedBox(width: 12), - ], + if (v.action != null) ...[v.action!, const SizedBox(width: 12)], SizedBox( - width: 120, + width: narrow ? 72 : 120, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( - '~${formatBytes(model.unscanned)}', + v.estimate ? '~${formatBytes(v.size)}' : formatBytes(v.size), style: theme.textTheme.titleSmall, ), - Text('estimate', style: theme.textTheme.bodySmall), + if (v.estimate) + Text('estimate', style: theme.textTheme.bodySmall), ], ), ), // Lines the size up with the rows that have buttons after it. - SizedBox(width: (canReveal ? 3 : 2) * (leadingGap + leadingSlot)), + if (!narrow) + SizedBox(width: (canReveal ? 3 : 2) * (leadingGap + leadingSlot)), ], ), ); } } + +/// One line about [part] for the status line under the treemap. +String unscannedHint(UnscannedPart part) => switch (part.kind) { + UnscannedKind.unknown => + 'Not scanned: about ${formatBytes(part.size)}. Click to see why.', + UnscannedKind.apps => 'Apps: ${formatBytes(part.size)}. Click to see them.', + UnscannedKind.system => + 'System and other: about ${formatBytes(part.size)}. Click to see why.', +}; diff --git a/lib/widgets/scan_header.dart b/lib/widgets/scan_header.dart index 1d5e02f..ea373f7 100644 --- a/lib/widgets/scan_header.dart +++ b/lib/widgets/scan_header.dart @@ -70,12 +70,14 @@ class ScanHeader extends StatelessWidget { const SizedBox(width: 4), ], Expanded( - child: canPickFolder && model.drives.isNotEmpty + // On phones only once there is a second drive to pick, such + // as an SD card. + child: model.drives.length > (canPickFolder ? 0 : 1) ? Align( alignment: Alignment.centerLeft, child: _DriveMenu( model: model, - onPickFolder: _pickFolder, + onPickFolder: canPickFolder ? _pickFolder : null, ), ) : Text( @@ -157,10 +159,12 @@ class ScanHeader extends StatelessWidget { /// What is scanned, as a dropdown: the drive's name or the folder's path, /// with the other drives and a folder picker in the menu. class _DriveMenu extends StatelessWidget { - const _DriveMenu({required this.model, required this.onPickFolder}); + const _DriveMenu({required this.model, this.onPickFolder}); final AppModel model; - final VoidCallback onPickFolder; + + /// Null where folders can not be picked, as on Android. + final VoidCallback? onPickFolder; @override Widget build(BuildContext context) { @@ -193,12 +197,14 @@ class _DriveMenu extends StatelessWidget { ), ), ), - const Divider(height: 8), - MenuItemButton( - leadingIcon: const Icon(Icons.folder_open_outlined, size: 20), - onPressed: onPickFolder, - child: const Text('Choose folder...'), - ), + if (onPickFolder != null) ...[ + const Divider(height: 8), + MenuItemButton( + leadingIcon: const Icon(Icons.folder_open_outlined, size: 20), + onPressed: onPickFolder, + child: const Text('Choose folder...'), + ), + ], ], builder: (context, controller, _) => InkWell( borderRadius: BorderRadius.circular(8), @@ -239,8 +245,12 @@ class _DriveMenu extends StatelessWidget { ); } - static IconData _driveIcon(Drive d) => - d.main ? Icons.computer_outlined : Icons.storage_outlined; + static IconData _driveIcon(Drive d) => switch ((d.main, AppModel.onAndroid)) { + (true, true) => Icons.smartphone_outlined, + (true, false) => Icons.computer_outlined, + (false, true) => Icons.sd_card_outlined, + (false, false) => Icons.storage_outlined, + }; } /// A small tappable label with an icon, for the status line. diff --git a/lib/widgets/treemap.dart b/lib/widgets/treemap.dart index d4719cf..a2402d6 100644 --- a/lib/widgets/treemap.dart +++ b/lib/widgets/treemap.dart @@ -99,6 +99,8 @@ class TreemapState extends State { model.protectedPaths.length, model.showsUnscanned, model.access, + model.apps, + model.usageAccess, ); if (key != _layoutKey) { _layoutKey = key; @@ -125,9 +127,10 @@ class TreemapState extends State { .where((n) => n.protection != ProtectionState.protected && n.size > 0) .toList(); // At the top of the scan, the space it did not see gets a tile too. - final unscanned = depth == 0 && id == Treemap.rootId && model.showsUnscanned - ? model.unscanned - : 0; + final parts = depth == 0 && id == Treemap.rootId + ? model.unscannedParts.where((p) => p.size > 0).toList() + : const []; + final unscanned = parts.fold(0, (s, p) => s + p.size); if (items.isEmpty && unscanned == 0 || area.width < 4 || area.height < 4) { return const []; } @@ -149,17 +152,19 @@ class TreemapState extends State { restCount++; } } - // Index into shown, or one of the two kinds of extra tile; laid out - // largest first, as squarify wants. - const more = -1, unseen = -2; + // Index into shown, the "more" tile, or -2 - k for unscanned part k; + // laid out largest first, as squarify wants. + const more = -1; final order = [for (var i = 0; i < shown.length; i++) i]; if (rest > 0) order.add(more); - if (unscanned > 0) order.add(unseen); - int sizeOf(int i) => switch (i) { - more => rest, - unseen => unscanned, - _ => shown[i].size, - }; + for (var k = 0; k < parts.length; k++) { + order.add(-2 - k); + } + int sizeOf(int i) => i == more + ? rest + : i < more + ? parts[-2 - i].size + : shown[i].size; order.sort((a, b) => sizeOf(b).compareTo(sizeOf(a))); final rects = squarify([for (final i in order) sizeOf(i).toDouble()], area); @@ -171,10 +176,9 @@ class TreemapState extends State { tiles.add(_Tile(null, r, depth, hue, more: restCount, moreSize: rest)); continue; } - if (i == unseen) { - tiles.add( - _Tile(null, r, depth, hue, moreSize: unscanned, unseen: true), - ); + if (i < more) { + final part = parts[-2 - i]; + tiles.add(_Tile(null, r, depth, hue, moreSize: part.size, part: part)); continue; } final n = shown[i]; @@ -276,25 +280,26 @@ class TreemapState extends State { ), ), ); - final unseen = tiles.where((t) => t.unseen).firstOrNull; - if (unseen == null) return map; - // A widget rather than paint: it has buttons. + final unseen = tiles.where((t) => t.unseen).toList(); + if (unseen.isEmpty) return map; + // Widgets rather than paint: they have buttons. return Stack( children: [ map, - Positioned.fromRect( - rect: unseen.rect.deflate(0.5), - child: MouseRegion( - onEnter: (_) { - setState(() => _hover = unseen); - widget.onHover?.call(null); - }, - onExit: (_) { - if (_hover == unseen) setState(() => _hover = null); - }, - child: UnscannedTile(model: model), + for (final t in unseen) + Positioned.fromRect( + rect: t.rect.deflate(0.5), + child: MouseRegion( + onEnter: (_) { + setState(() => _hover = t); + widget.onHover?.call(null); + }, + onExit: (_) { + if (_hover == t) setState(() => _hover = null); + }, + child: UnscannedTile(model: model, part: t.part!), + ), ), - ), ], ); }, @@ -308,8 +313,7 @@ class TreemapState extends State { _hover == null ? 'Click a folder to open it. Right-click for more.' : _hover!.unseen - ? 'Not scanned: about ${formatBytes(_hover!.moreSize)}. ' - 'Click to see why.' + ? unscannedHint(_hover!.part!) : _hover!.node == null ? '${_hover!.more} smaller items, ${formatBytes(_hover!.moreSize)}' : '${_hover!.node!.path} · ${formatBytes(_hover!.node!.size)}', @@ -332,7 +336,7 @@ class _Tile { this.hue, { this.more = 0, this.moreSize = 0, - this.unseen = false, + this.part, }); /// Null for the tile that merges small items. @@ -343,8 +347,9 @@ class _Tile { final int more; final int moreSize; - /// The space the scan did not see; drawn by [UnscannedTile]. - final bool unseen; + /// Space the scan did not see; drawn by [UnscannedTile]. + final UnscannedPart? part; + bool get unseen => part != null; List<_Tile> children = const []; } diff --git a/test/apps_screen_test.dart b/test/apps_screen_test.dart index 8189350..e1f7d63 100644 --- a/test/apps_screen_test.dart +++ b/test/apps_screen_test.dart @@ -1,3 +1,4 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -55,27 +56,34 @@ void main() { }); }); - Future pump(WidgetTester tester) async { + /// The model loads app sizes itself on Android; [AppModel.init] does + /// that at start and on resume, here the test calls it. + Future pump(WidgetTester tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + final model = AppModel(); await tester.pumpWidget( MaterialApp( - home: Scaffold(body: AppsScreen(model: AppModel())), + home: Scaffold(body: AppsScreen(model: model)), ), ); + await tester.runAsync(model.loadApps); await tester.pumpAndSettle(); + return model; } testWidgets('explains usage access until it is granted', (tester) async { usageAccess = false; - await pump(tester); + final model = await pump(tester); expect(find.text('Most of your space is in apps'), findsOneWidget); await tester.tap(find.text('Allow usage access')); expect(calls.last.method, 'requestUsageAccess'); // Back from Settings with access granted. usageAccess = true; - tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.runAsync(model.loadApps); await tester.pumpAndSettle(); expect(find.text('Big app'), findsOneWidget); + debugDefaultTargetPlatformOverride = null; }); testWidgets('lists apps by size, built-in ones on request', (tester) async { @@ -98,6 +106,7 @@ void main() { await tester.tap(find.text('Small app')); expect(calls.last.method, 'openAppInfo'); expect(calls.last.arguments, {'package': 'com.small'}); + debugDefaultTargetPlatformOverride = null; }); testWidgets('shows errors from Android', (tester) async { @@ -108,5 +117,6 @@ void main() { }); await pump(tester); expect(find.textContaining('denied'), findsOneWidget); + debugDefaultTargetPlatformOverride = null; }); } diff --git a/test/widgets_test.dart b/test/widgets_test.dart index 16ec612..2ba542b 100644 --- a/test/widgets_test.dart +++ b/test/widgets_test.dart @@ -432,6 +432,66 @@ void main() { ); }); + testWidgets('on Android shows apps instead, then links to them', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + var usage = false; + const channel = MethodChannel('spaceman/storage'); + final calls = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( + call, + ) async { + calls.add(call.method); + return switch (call.method) { + 'hasUsageAccess' => usage, + 'appSizes' => { + 'total': 50000000000, + 'free': 30000000000, + 'apps': [ + { + 'package': 'com.big', + 'label': 'Big app', + 'app': 2000000000, + 'data': 13000000000, + 'cache': 0, + 'system': false, + }, + ], + }, + _ => null, + }; + }); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + null, + ), + ); + core.disk = const DiskSpace(total: 50000000000, free: 30000000000); + await start(tester); + // Without usage access: one Apps block that asks for it. + expect(find.byType(UnscannedTile), findsOneWidget); + expect(find.text('Not scanned'), findsNothing); + expect(find.text('Apps'), findsWidgets); + await tester.tap(find.text('Allow usage access')); + expect(calls.last, 'requestUsageAccess'); + + // With it: the apps at their real size, the rest as System. + usage = true; + await tester.runAsync(model.loadApps); + await tester.pumpAndSettle(); + expect(find.byType(UnscannedTile), findsNWidgets(2)); + expect(find.text('System and other'), findsOneWidget); + expect(find.text('15.0 GB'), findsOneWidget); + await tester.tap(find.text('See apps')); + await tester.pumpAndSettle(); + expect(model.tab, AppModel.appsTab); + expect(find.text('Big app'), findsOneWidget); + debugDefaultTargetPlatformOverride = null; + }); + testWidgets('no tile for a folder smaller than home', (tester) async { core.disk = const DiskSpace(total: 50000000000, free: 30000000000); await start(tester); From 7f6cd680d9b80b5eb7509f09401a0e3c4d9a7ae8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 16:08:19 +0000 Subject: [PATCH 2/3] Treemap hint says tap and long-press on Android Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AHutN3owoAasdzkZtzcMcD --- lib/widgets/treemap.dart | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/widgets/treemap.dart b/lib/widgets/treemap.dart index a2402d6..68f0efc 100644 --- a/lib/widgets/treemap.dart +++ b/lib/widgets/treemap.dart @@ -311,7 +311,9 @@ class TreemapState extends State { padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), child: Text( _hover == null - ? 'Click a folder to open it. Right-click for more.' + ? AppModel.onAndroid + ? 'Tap a folder to open it. Long-press for more.' + : 'Click a folder to open it. Right-click for more.' : _hover!.unseen ? unscannedHint(_hover!.part!) : _hover!.node == null From 1ba8395b7a0c2af18698dd6778ac8138852b7d81 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 16:15:05 +0000 Subject: [PATCH 3/3] Android back goes up a folder, and from other tabs back to Explore Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AHutN3owoAasdzkZtzcMcD --- lib/main.dart | 144 +++++++++++++++-------------- lib/screens/explorer.dart | 185 ++++++++++++++++++++------------------ test/widgets_test.dart | 16 ++++ 3 files changed, 188 insertions(+), 157 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index c75775d..6a66537 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -93,88 +93,94 @@ class _HomePageState extends State { ? null : '${model.suggestions.length}'; - // "?" opens the help from anywhere. - return CallbackShortcuts( - bindings: {const CharacterActivator('?'): () => showHelp(context)}, - child: LayoutBuilder( - builder: (context, constraints) { - final wide = constraints.maxWidth >= 720; - final body = Column( - children: [ - ScanHeader(model: model, showHelp: !wide), - const Divider(height: 1), - Expanded(child: page), - if (model.tab < 2) SelectionBar(model: model), - ], - ); - if (!wide) { - return Scaffold( - body: SafeArea(child: body), - bottomNavigationBar: NavigationBar( - selectedIndex: model.tab, - onDestinationSelected: widget.model.showTab, - destinations: [ - for (final (i, d) in _destinations.indexed) - NavigationDestination( - icon: _badge( - _icon(i, d.icon), - i == 1 ? cleanupBadge : null, - ), - selectedIcon: _icon(i, d.active), - label: d.label, - ), - ], - ), - ); - } - return Scaffold( - body: Row( + // Back on another tab returns to Explore first. + return PopScope( + canPop: model.tab == 0, + onPopInvokedWithResult: (didPop, _) { + if (!didPop) model.showTab(0); + }, + child: CallbackShortcuts( + bindings: {const CharacterActivator('?'): () => showHelp(context)}, + child: LayoutBuilder( + builder: (context, constraints) { + final wide = constraints.maxWidth >= 720; + final body = Column( children: [ - NavigationRail( + ScanHeader(model: model, showHelp: !wide), + const Divider(height: 1), + Expanded(child: page), + if (model.tab < 2) SelectionBar(model: model), + ], + ); + if (!wide) { + return Scaffold( + body: SafeArea(child: body), + bottomNavigationBar: NavigationBar( selectedIndex: model.tab, onDestinationSelected: widget.model.showTab, - labelType: NavigationRailLabelType.all, - // The logo sits flush at the bottom, out of the way of - // the tabs. - trailing: Expanded( - child: Column( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - const HelpButton(), - const SizedBox(height: 8), - canOpenUrl - ? Tooltip( - message: 'SpaceMan website', - child: MouseRegion( - cursor: SystemMouseCursors.click, - child: GestureDetector( - onTap: () => openUrl(websiteUrl), - child: const SpaceManLogo(size: 40), - ), - ), - ) - : const SpaceManLogo(size: 40), - ], - ), - ), destinations: [ for (final (i, d) in _destinations.indexed) - NavigationRailDestination( + NavigationDestination( icon: _badge( _icon(i, d.icon), i == 1 ? cleanupBadge : null, ), selectedIcon: _icon(i, d.active), - label: Text(d.label), + label: d.label, ), ], ), - const VerticalDivider(width: 1), - Expanded(child: SafeArea(child: body)), - ], - ), - ); - }, + ); + } + return Scaffold( + body: Row( + children: [ + NavigationRail( + selectedIndex: model.tab, + onDestinationSelected: widget.model.showTab, + labelType: NavigationRailLabelType.all, + // The logo sits flush at the bottom, out of the way of + // the tabs. + trailing: Expanded( + child: Column( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + const HelpButton(), + const SizedBox(height: 8), + canOpenUrl + ? Tooltip( + message: 'SpaceMan website', + child: MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + onTap: () => openUrl(websiteUrl), + child: const SpaceManLogo(size: 40), + ), + ), + ) + : const SpaceManLogo(size: 40), + ], + ), + ), + destinations: [ + for (final (i, d) in _destinations.indexed) + NavigationRailDestination( + icon: _badge( + _icon(i, d.icon), + i == 1 ? cleanupBadge : null, + ), + selectedIcon: _icon(i, d.active), + label: Text(d.label), + ), + ], + ), + const VerticalDivider(width: 1), + Expanded(child: SafeArea(child: body)), + ], + ), + ); + }, + ), ), ); }, diff --git a/lib/screens/explorer.dart b/lib/screens/explorer.dart index 948264d..006950f 100644 --- a/lib/screens/explorer.dart +++ b/lib/screens/explorer.dart @@ -372,100 +372,109 @@ class _ExplorerScreenState extends State ); } final crumbs = model.breadcrumbs(model.currentId); - return CallbackShortcuts( - bindings: { - const SingleActivator(LogicalKeyboardKey.escape): _up, - const SingleActivator(LogicalKeyboardKey.bracketLeft, meta: true): _up, - const SingleActivator(LogicalKeyboardKey.arrowUp, meta: true): _up, - // Explorer's shortcuts on Windows and Linux. - const SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): _up, - const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true): _up, - const SingleActivator(LogicalKeyboardKey.arrowUp): () => - _arrow(AxisDirection.up), - const SingleActivator(LogicalKeyboardKey.arrowDown): () => - _arrow(AxisDirection.down), - const SingleActivator(LogicalKeyboardKey.arrowLeft): () => - _arrow(AxisDirection.left), - const SingleActivator(LogicalKeyboardKey.arrowRight): () => - _arrow(AxisDirection.right), - const SingleActivator(LogicalKeyboardKey.enter): _openFocused, - const SingleActivator(LogicalKeyboardKey.backspace): _toggleRemoval, - const SingleActivator(LogicalKeyboardKey.delete): _toggleRemoval, - // Space works on what the mouse points at, then the focus. - const SingleActivator(LogicalKeyboardKey.space): () => - _toggleRemoval(pointerFirst: true), - const SingleActivator(LogicalKeyboardKey.backspace, meta: true): - _toggleRemoval, + // Android's back button goes up a folder; only at the top it leaves. + return PopScope( + canPop: _parentId == null, + onPopInvokedWithResult: (didPop, _) { + if (!didPop) _up(); }, - child: Focus( - autofocus: true, - child: Listener( - onPointerDown: (e) { - if (e.buttons & kBackMouseButton != 0) _up(); - }, - onPointerSignal: _onPointerSignal, - onPointerPanZoomStart: _onPanZoomStart, - onPointerPanZoomUpdate: _onPanZoomUpdate, - onPointerPanZoomEnd: _onPanZoomEnd, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Row( - children: [ - Expanded( - child: _Breadcrumbs( - model: model, - crumbs: crumbs, - onOpen: _go, - ), - ), - Padding( - padding: const EdgeInsets.only(right: 16), - child: SegmentedButton( - showSelectedIcon: false, - style: const ButtonStyle( - visualDensity: VisualDensity.compact, + child: CallbackShortcuts( + bindings: { + const SingleActivator(LogicalKeyboardKey.escape): _up, + const SingleActivator(LogicalKeyboardKey.bracketLeft, meta: true): + _up, + const SingleActivator(LogicalKeyboardKey.arrowUp, meta: true): _up, + // Explorer's shortcuts on Windows and Linux. + const SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): _up, + const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true): _up, + const SingleActivator(LogicalKeyboardKey.arrowUp): () => + _arrow(AxisDirection.up), + const SingleActivator(LogicalKeyboardKey.arrowDown): () => + _arrow(AxisDirection.down), + const SingleActivator(LogicalKeyboardKey.arrowLeft): () => + _arrow(AxisDirection.left), + const SingleActivator(LogicalKeyboardKey.arrowRight): () => + _arrow(AxisDirection.right), + const SingleActivator(LogicalKeyboardKey.enter): _openFocused, + const SingleActivator(LogicalKeyboardKey.backspace): _toggleRemoval, + const SingleActivator(LogicalKeyboardKey.delete): _toggleRemoval, + // Space works on what the mouse points at, then the focus. + const SingleActivator(LogicalKeyboardKey.space): () => + _toggleRemoval(pointerFirst: true), + const SingleActivator(LogicalKeyboardKey.backspace, meta: true): + _toggleRemoval, + }, + child: Focus( + autofocus: true, + child: Listener( + onPointerDown: (e) { + if (e.buttons & kBackMouseButton != 0) _up(); + }, + onPointerSignal: _onPointerSignal, + onPointerPanZoomStart: _onPanZoomStart, + onPointerPanZoomUpdate: _onPanZoomUpdate, + onPointerPanZoomEnd: _onPanZoomEnd, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded( + child: _Breadcrumbs( + model: model, + crumbs: crumbs, + onOpen: _go, ), - segments: const [ - ButtonSegment( - value: false, - icon: Icon(Icons.view_list, size: 18), - tooltip: 'List', - ), - ButtonSegment( - value: true, - icon: Icon(Icons.dashboard, size: 18), - tooltip: 'Treemap', + ), + Padding( + padding: const EdgeInsets.only(right: 16), + child: SegmentedButton( + showSelectedIcon: false, + style: const ButtonStyle( + visualDensity: VisualDensity.compact, ), - ], - selected: {model.treemap}, - onSelectionChanged: (v) => model.setTreemap(v.single), + segments: const [ + ButtonSegment( + value: false, + icon: Icon(Icons.view_list, size: 18), + tooltip: 'List', + ), + ButtonSegment( + value: true, + icon: Icon(Icons.dashboard, size: 18), + tooltip: 'Treemap', + ), + ], + selected: {model.treemap}, + onSelectionChanged: (v) => model.setTreemap(v.single), + ), + ), + ], + ), + Expanded( + child: GestureDetector( + // Touch screens; the trackpad is handled above. + supportedDevices: const {PointerDeviceKind.touch}, + onHorizontalDragStart: (_) => _beginSwipe(), + onHorizontalDragUpdate: (d) => _moveSwipe(d.primaryDelta!), + onHorizontalDragEnd: (d) => + _endSwipe(d.primaryVelocity ?? 0), + onHorizontalDragCancel: () => _endSwipe(0), + child: LayoutBuilder( + builder: (context, constraints) { + _width = constraints.maxWidth; + return ClipRect(child: _buildLists(context)); + }, ), - ), - ], - ), - Expanded( - child: GestureDetector( - // Touch screens; the trackpad is handled above. - supportedDevices: const {PointerDeviceKind.touch}, - onHorizontalDragStart: (_) => _beginSwipe(), - onHorizontalDragUpdate: (d) => _moveSwipe(d.primaryDelta!), - onHorizontalDragEnd: (d) => _endSwipe(d.primaryVelocity ?? 0), - onHorizontalDragCancel: () => _endSwipe(0), - child: LayoutBuilder( - builder: (context, constraints) { - _width = constraints.maxWidth; - return ClipRect(child: _buildLists(context)); - }, ), ), - ), - const Divider(height: 1), - FolderBar( - model: model, - folder: crumbs.isEmpty ? model.rootNode! : crumbs.last, - ), - ], + const Divider(height: 1), + FolderBar( + model: model, + folder: crumbs.isEmpty ? model.rootNode! : crumbs.last, + ), + ], + ), ), ), ), diff --git a/test/widgets_test.dart b/test/widgets_test.dart index 2ba542b..3ef0248 100644 --- a/test/widgets_test.dart +++ b/test/widgets_test.dart @@ -322,6 +322,22 @@ void main() { expect(model.currentId, 0); }); + testWidgets('back goes up a folder, then to Explore', (tester) async { + await start(tester, list: true); + await tester.tap(find.text('Movies')); + await tester.pumpAndSettle(); + // Android's back button; true means the app handled it and stays. + expect(await tester.binding.handlePopRoute(), isTrue); + await tester.pumpAndSettle(); + expect(model.currentId, 0); + + model.showTab(2); + await tester.pumpAndSettle(); + expect(await tester.binding.handlePopRoute(), isTrue); + await tester.pumpAndSettle(); + expect(model.tab, 0); + }); + testWidgets('pulling the list past its top goes up', (tester) async { await start(tester, list: true); await tester.tap(find.text('Movies'));