git.iko.soy/opencode-android
on 2794fda help sign in
58 lines 2.4 kB history raw
1package soy.iko.opencode.platform
3import android.content.Context
4import android.content.Intent
5import android.net.Uri
6import androidx.core.content.pm.ShortcutInfoCompat
7import androidx.core.content.pm.ShortcutManagerCompat
8import androidx.core.graphics.drawable.IconCompat
9import soy.iko.opencode.MainActivity
10import soy.iko.opencode.R
11import soy.iko.opencode.data.repo.RecentSession
13/**
14 * Maintains the app's dynamic launcher shortcuts (long-press the icon): "New session" and
15 * "Resume last". Rebuilt whenever the recent-session list changes so "Resume last" points at
16 * the most recent conversation via the existing `opencode://session/{id}` deep link.
17 */
18object AppShortcuts {
20 private const val ID_NEW = "new_session"
21 private const val ID_RESUME = "resume_last"
22 private val idRegex = Regex("[^A-Za-z0-9_-]")
24 fun update(context: Context, lastSession: RecentSession?) {
25 val ctx = context.applicationContext
26 val shortcuts = mutableListOf<ShortcutInfoCompat>()
28 shortcuts += ShortcutInfoCompat.Builder(ctx, ID_NEW)
29 .setShortLabel(ctx.getString(R.string.shortcut_new_short))
30 .setLongLabel(ctx.getString(R.string.shortcut_new_long))
31 .setIcon(IconCompat.createWithResource(ctx, R.drawable.ic_launcher_foreground))
32 .setIntent(
33 Intent(ctx, MainActivity::class.java).apply { action = MainActivity.ACTION_NEW_SESSION },
34 )
35 .build()
37 if (lastSession != null) {
38 val safeId = idRegex.replace(lastSession.id, "")
39 if (safeId.isNotEmpty()) {
40 shortcuts += ShortcutInfoCompat.Builder(ctx, ID_RESUME)
41 .setShortLabel(ctx.getString(R.string.shortcut_resume_short))
42 .setLongLabel(
43 lastSession.title.ifBlank { ctx.getString(R.string.shortcut_resume_long) }.take(40),
44 )
45 .setIcon(IconCompat.createWithResource(ctx, R.drawable.ic_launcher_foreground))
46 .setIntent(
47 Intent(ctx, MainActivity::class.java).apply {
48 action = Intent.ACTION_VIEW
49 data = Uri.parse("opencode://session/$safeId")
50 },
51 )
52 .build()
53 }
54 }
56 runCatching { ShortcutManagerCompat.setDynamicShortcuts(ctx, shortcuts) }
57 }