Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 48 additions & 8 deletions android/app/src/main/kotlin/io/ontola/spaceman/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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<Map<String, Any>> {
val sm = getSystemService(StorageManager::class.java)
val found = mutableListOf<Map<String, Any>>()
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 <volume>/Android/data/<package>.
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)
Expand All @@ -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<String, Any>? =
try {
val s = stats.queryStatsForPackage(uuid, info.packageName, user)
mapOf(
Expand All @@ -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 {
Expand Down
123 changes: 119 additions & 4 deletions lib/app_model.dart
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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 {
Expand All @@ -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<void> refreshDrives() async {
drives = await loadDrives();
notifyListeners();
}

Expand Down Expand Up @@ -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<void> 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<void> _loadCachedApps() async {
try {
apps = appSizesFromJson(
jsonDecode(await _appsFile!.readAsString()) as Map<String, Object?>,
);
} 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<void> 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.
Expand All @@ -98,7 +191,7 @@ class AppModel extends ChangeNotifier {
} on FileSystemException {
// First launch: the list.
}
drives = listDrives();
drives = await loadDrives();
root = await _initialRoot();
notifyListeners();

Expand Down Expand Up @@ -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.
Expand All @@ -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<UnscannedPart> 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<int>(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();
}
Expand Down
23 changes: 21 additions & 2 deletions lib/drives.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -27,8 +28,22 @@ class Drive {
@visibleForTesting
List<Drive> 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<List<Drive>> 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<Drive> listDrives() {
if (debugDrives != null) return debugDrives!();
final List<(String, String, bool)> found;
Expand All @@ -41,6 +56,10 @@ List<Drive> listDrives() {
} else {
return const [];
}
return _measure(found);
}

List<Drive> _measure(List<(String, String, bool)> found) {
final drives = <Drive>[];
for (final (path, name, main) in found) {
final space = core.diskSpace(path: path);
Expand Down
Loading
Loading