Skip to content
93 changes: 93 additions & 0 deletions app/android/app/src/main/kotlin/app/atrium/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,16 +1,38 @@
package app.atrium

import android.content.Intent
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.drawable.Icon
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.provider.OpenableColumns
import io.flutter.FlutterInjector
import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

// FlutterFragmentActivity (not FlutterActivity) is required by local_auth so
// the BiometricPrompt can attach to a FragmentActivity host.
class MainActivity : FlutterFragmentActivity() {
companion object {
// Publishing shortcuts decodes icons and can take Android a while, so
// it runs off the main thread. One thread for the whole process keeps
// updates in the order sent, even across a recreated activity, so an
// older list can never land after a newer one.
private val shortcutExecutor: ExecutorService by lazy { Executors.newSingleThreadExecutor() }
}

private val CHANNEL = "app.atrium/launcher"
private val SHARE_CHANNEL = "app.atrium/share"

Expand All @@ -24,6 +46,8 @@ class MainActivity : FlutterFragmentActivity() {

private var shareChannel: MethodChannel? = null

private val mainHandler = Handler(Looper.getMainLooper())

// The intent Atrium was launched with, held until Dart asks for it. Dart
// is not running yet when a cold start arrives, so it cannot be pushed.
private var pendingShareIntent: Intent? = null
Expand Down Expand Up @@ -79,12 +103,81 @@ class MainActivity : FlutterFragmentActivity() {
} else {
result.error("INVALID_ARGUMENT", "URL is required", null)
}
} else if (call.method == "setShortcuts") {
val shortcuts = call.argument<List<Map<String, String>>>("shortcuts")
if (shortcuts == null) {
result.error("INVALID_ARGUMENT", "shortcuts is required", null)
} else {
shortcutExecutor.execute {
val applied = runCatching { setShortcuts(shortcuts) }.getOrDefault(false)
mainHandler.post { result.success(applied) }
}
}
} else {
result.notImplemented()
}
}
}

/// Replaces Atrium's launcher shortcuts (long-press on the icon, and
/// launcher search) with [shortcuts]. Each opens an atrium:// link, so a
/// tap takes the same path as any other Atrium link. An empty list clears
/// them. False below Android 7.1, which has no launcher shortcuts, and
/// when Android refuses the update (it rate limits apps in the background).
private fun setShortcuts(shortcuts: List<Map<String, String>>): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1) return false
val manager = getSystemService(ShortcutManager::class.java) ?: return false
val infos = shortcuts.mapIndexedNotNull { index, entry ->
val id = entry["id"] ?: return@mapIndexedNotNull null
// Android rejects an empty label, which would fail the whole list.
val name = entry["name"]?.takeIf { it.isNotEmpty() } ?: return@mapIndexedNotNull null
val link = entry["link"] ?: return@mapIndexedNotNull null
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link))
.setClass(this, MainActivity::class.java)
ShortcutInfo.Builder(this, id)
.setShortLabel(name)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
.setLongLabel("Open $name")
.setRank(index)
.setIntent(intent)
.setIcon(shortcutIcon(entry["icon"]))
.build()
}
return manager.setDynamicShortcuts(infos)
}

/// The service's bundled icon, or Atrium's own when the service has none
/// or it cannot be read.
private fun shortcutIcon(assetPath: String?): Icon {
val bitmap = assetPath?.let { path ->
runCatching {
val key = FlutterInjector.instance().flutterLoader().getLookupKeyForAsset(path)
assets.open(key).use { BitmapFactory.decodeStream(it) }
}.getOrNull()
} ?: return Icon.createWithResource(this, R.mipmap.ic_launcher)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
return Icon.createWithBitmap(bitmap)
}
return Icon.createWithAdaptiveBitmap(adaptiveBitmap(bitmap))
}

/// Centres [logo] on a white square sized for an adaptive icon. The
/// launcher masks the outer edge into its own shape, so the logo sits
/// inside the square that fits the smallest (circular) mask.
private fun adaptiveBitmap(logo: Bitmap): Bitmap {
val size = 432
val inner = size * 46 / 108
val out = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
val canvas = Canvas(out)
canvas.drawColor(Color.WHITE)
val scale = minOf(inner.toFloat() / logo.width, inner.toFloat() / logo.height)
val w = (logo.width * scale).toInt()
val h = (logo.height * scale).toInt()
val left = (size - w) / 2
val top = (size - h) / 2
canvas.drawBitmap(logo, null, Rect(left, top, left + w, top + h), Paint(Paint.FILTER_BITMAP_FLAG))
return out
}

// Reached when Atrium is already running (launchMode is singleTop), so
// Dart is live and the payload can be pushed straight across.
override fun onNewIntent(intent: Intent) {
Expand Down
5 changes: 5 additions & 0 deletions app/lib/app.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import 'src/custom_theme_providers.dart';
import 'src/launcher_shortcuts/launcher_shortcuts_publisher.dart';
import 'src/preferences.dart';
import 'src/router.dart';
import 'src/share_intake/torrent_share_listener.dart';
Expand Down Expand Up @@ -57,6 +58,10 @@ class AtriumApp extends ConsumerWidget {
// profile changes after this widget is built.
syncGlobalHeaders(ref.read(activeProfileProvider));

// Keeps the long-press shortcuts on Atrium's launcher icon in step with
// the active profile's services.
ref.watch(launcherShortcutsSyncProvider);

final ThemeSource themeSource =
ref.watch(preferencesProvider.select((Preferences p) => p.themeSource));
final (ColorScheme customLight, ColorScheme customDark) =
Expand Down
97 changes: 97 additions & 0 deletions app/lib/src/launcher_shortcuts/launcher_shortcuts.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import 'dart:convert';

import 'package:core_models/core_models.dart';
import 'package:core_profile/core_profile.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../preferences.dart';

/// How many services get a launcher shortcut. Most launchers show about four
/// on a long-press, so a longer list would mostly go unseen.
const int maxLauncherShortcuts = 4;

/// The `atrium://` link a shortcut opens: the instance's service screen,
/// picked by name, through the same path as any other Atrium link.
String shortcutLink(Instance instance) => Uri(
scheme: 'atrium',
host: instance.kind.name.toLowerCase(),
queryParameters: <String, String>{'instance': instance.name},
).toString();

/// The instances that get a shortcut, in sidebar order.
///
/// [chosenIds] is null until the user edits the list, and then the first
/// [maxLauncherShortcuts] services stand in, so shortcuts work with no setup.
/// Once chosen, an empty list means none, and IDs of deleted instances drop
/// out.
List<Instance> shortcutInstances(
List<Instance> instances,
List<String>? chosenIds,
) {
final Iterable<Instance> picked = chosenIds == null
? instances
: instances.where((Instance i) => chosenIds.contains(i.id));
return picked.take(maxLauncherShortcuts).toList(growable: false);
}

/// The services a profile's user ticked for launcher shortcuts, or null when
/// they never edited the list. Kept per profile in the settings box.
class LauncherShortcutChoiceController extends Notifier<List<String>?> {
LauncherShortcutChoiceController(this.profileId);

final String profileId;

String get _key => 'launcherShortcuts.$profileId';

@override
List<String>? build() {
final String? raw = ref.read(settingsBoxProvider).get(_key);
if (raw == null) {
return null;
}
try {
final Object? decoded = jsonDecode(raw);
if (decoded is List) {
return decoded.whereType<String>().toList(growable: false);
}
} on FormatException {
// Falls through to the default below.
}
return null;
}

/// Shows [ids] at once, so a second tap made while this one is still
/// saving starts from it, then saves. A failed save puts the earlier
/// choice back, unless a later one has replaced it.
Future<void> setChosen(List<String> ids) async {
final List<String>? previous = state;
final List<String> next = List<String>.unmodifiable(ids);
state = next;
try {
await ref.read(settingsBoxProvider).put(_key, jsonEncode(next));
} catch (_) {
if (identical(state, next)) {
state = previous;
}
rethrow;
}
}
}

final launcherShortcutChoiceProvider = NotifierProvider.family<
LauncherShortcutChoiceController, List<String>?, String>(
LauncherShortcutChoiceController.new,
);

/// The active profile's services that get a launcher shortcut.
final Provider<List<Instance>> launcherShortcutInstancesProvider =
Provider<List<Instance>>((Ref ref) {
final Profile? profile = ref.watch(activeProfileProvider);
if (profile == null) {
return const <Instance>[];
}
return shortcutInstances(
profile.instances,
ref.watch(launcherShortcutChoiceProvider(profile.id)),
);
});
93 changes: 93 additions & 0 deletions app/lib/src/launcher_shortcuts/launcher_shortcuts_publisher.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import 'package:collection/collection.dart';
import 'package:core_models/core_models.dart';
import 'package:core_profile/core_profile.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'launcher_shortcuts.dart';

/// Hands the launcher shortcut list to Android, which shows it on a
/// long-press of Atrium's icon and in launcher search.
class LauncherShortcutsPublisher {
LauncherShortcutsPublisher([
this._channel = const MethodChannel('app.atrium/launcher'),
]);

final MethodChannel _channel;

/// What Android was last given. Android limits how often an app may change
/// its shortcuts, so an unchanged list is not sent again.
List<Map<String, String>>? _sent;

Future<void> publish(List<Instance> instances) async {
if (defaultTargetPlatform != TargetPlatform.android) {
return;
}
final List<Map<String, String>> shortcuts = <Map<String, String>>[
for (final Instance i in instances)
<String, String>{
'id': i.id,
'name': i.name,
'link': shortcutLink(i),
'icon': 'assets/service_icons/${i.kind.name}.png',
},
];
if (const DeepCollectionEquality().equals(shortcuts, _sent)) {
return;
}
_sent = shortcuts;
try {
final bool? applied = await _channel.invokeMethod<bool>(
'setShortcuts',
<String, Object>{'shortcuts': shortcuts},
);
// Android can refuse (rate limited while in the background) or fail.
// Forget the list so the same one is tried again, unless a newer
// publish has already replaced it.
if (applied != true && identical(_sent, shortcuts)) {
_sent = null;
}
} on MissingPluginException {
_sent = null;
} on PlatformException {
// Not sent, so the next change, or the next launch, tries again.
_sent = null;
}
}
}

final Provider<LauncherShortcutsPublisher> launcherShortcutsPublisherProvider =
Provider<LauncherShortcutsPublisher>(
(Ref ref) => LauncherShortcutsPublisher(),
);

/// The shortcut list to publish, or null while the profiles are still
/// loading (at launch, while secure storage is read) or failed to load.
/// Publishing then would clear the shortcuts until the profiles arrive, or
/// for good if they never do.
final Provider<List<Instance>?> _publishableShortcutsProvider =
Provider<List<Instance>?>((Ref ref) {
if (!ref.watch(profileListProvider).hasValue) {
return null;
}
return ref.watch(launcherShortcutInstancesProvider);
});

/// Publishes the active profile's shortcut list once the profiles have
/// loaded, and again whenever it changes: a profile switch, a service added,
/// renamed, reordered or deleted, or a new choice in Settings. Watched once
/// at the app root.
final Provider<void> launcherShortcutsSyncProvider = Provider<void>((Ref ref) {
final LauncherShortcutsPublisher publisher =
ref.watch(launcherShortcutsPublisherProvider);
ref.listen<List<Instance>?>(
_publishableShortcutsProvider,
(_, List<Instance>? next) {
if (next != null) {
publisher.publish(next);
}
},
fireImmediately: true,
);
});
Loading
Loading