mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 20:36:04 +00:00
Feature adding custom Linux applications (#130)
* Add your own apps to the Desktop page An Add tile on Desktop takes a .sh script, an AppImage, a GitHub repo (newest ARM64 AppImage release) or a Flatpak ID, with an optional name and icon. Script folders are linked into the session, or copied when they hold Linux programs (shared storage is noexec); folders outside internal storage are bound at their own path. Each app's page opens it under gamescope, edits its name and icon (with icons suggested from its GitHub repo), checks a GitHub app for a newer release and updates it in place, or removes it. Replaces the beta AppImages section. * Put Add at the end of the installable emulators Installed emulators and added apps keep the top section, shown once there is one. Add closes the installable grid, or the installed one when nothing is left to install. * Import DwarFS AppImages and their SVG icons uruntime images built with sharun keep one program under several names as hard links, which Android denies apps, so dwarfsextract aborted. The extraction runs with proot's link2symlink, and each linked name becomes a file of its own afterwards; their AppDir is followed through the squashfs-root link. An image's icon is a PNG of at least 128 px from the name its entry gives, else its SVG (drawn with AndroidSVG), else the largest PNG, else .DirIcon. * Give AppImages the session's pads sharun images start the app through their own ld.so, patched not to read /etc/ld.so.preload, and drop LD_PRELOAD unless allowed, so the app never loaded libfakeinput and saw no controller. The launcher now hands the preload list over in LD_PRELOAD with SHARUN_ALLOW_LD_PRELOAD set. Pad defaults also put Player 1 on the controller for yuzu-family emulators, once, while it is still on the keyboard. * Redesign the Add and Edit app dialogs Source and appearance sit in two panels side by side, with a live preview of the Desktop tile. A disabled primary button keeps an outline so it still reads as a button.
This commit is contained in:
1 parent
d506394f87
commit
e31801df35
22 files changed
+1589
-265
No files matched your search
@@ -1,7 +1,9 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import android.os.StatFs
|
||||
import android.system.Os
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import java.io.File
|
||||
@@ -21,6 +23,7 @@ object AppImageManager {
|
||||
const val LAUNCHER = "/usr/local/bin/bannerlator-appimage-run"
|
||||
private const val ELF_AARCH64 = 183
|
||||
private const val ELF_X86_64 = 62
|
||||
private const val SHARP_ICON = 128
|
||||
|
||||
class Item(val id: String, val name: String, val icon: File?, val comment: String?) {
|
||||
val guestDir: String get() = "$GUEST_DIR/$id"
|
||||
@@ -74,8 +77,15 @@ object AppImageManager {
|
||||
return id
|
||||
}
|
||||
|
||||
/** Imports [file]; null on success, else what went wrong. [onProgress] gets a stage line. */
|
||||
fun import(context: Context, file: File, onProgress: (String) -> Unit): String? {
|
||||
fun dir(context: Context, id: String) = File(root(context), id)
|
||||
|
||||
/**
|
||||
* Imports [file]; null on success, else what went wrong. [name] and [icon] replace the image's own;
|
||||
* each of [meta] is written as a file beside them.
|
||||
*/
|
||||
fun import(
|
||||
context: Context, file: File, name: String?, icon: File?, meta: Map<String, String> = emptyMap(), onProgress: (String) -> Unit,
|
||||
): String? {
|
||||
if (!LinuxRuntime.isInstalled(context)) return "Install the Linux runtime first"
|
||||
problem(file)?.let { return it }
|
||||
val base = root(context).apply { mkdirs() }
|
||||
@@ -83,9 +93,45 @@ object AppImageManager {
|
||||
if (StatFs(base.path).availableBytes < file.length() * 3) {
|
||||
return "Not enough free space: importing needs about ${FileUtils.sizeToString(file.length() * 3)}"
|
||||
}
|
||||
val id = idFor(file.name, base.list()?.toSet() ?: emptySet())
|
||||
val dir = File(base, id)
|
||||
val dir = File(base, idFor(name ?: file.name, base.list()?.toSet() ?: emptySet()))
|
||||
try {
|
||||
extract(context, dir, file, onProgress)?.let { FileUtils.delete(dir); return it }
|
||||
describe(dir, file)
|
||||
if (name != null) FileUtils.writeString(File(dir, "name"), name)
|
||||
if (icon != null && !UserApps.saveIcon(icon, File(dir, "icon.png"))) Log.w(TAG, "icon ${icon.path} could not be read")
|
||||
meta.forEach { (k, v) -> FileUtils.writeString(File(dir, k), v) }
|
||||
writeMenuEntry(context, dir)
|
||||
return null
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "import ${file.name}", e)
|
||||
FileUtils.delete(dir)
|
||||
return e.message ?: "Import failed"
|
||||
}
|
||||
}
|
||||
|
||||
/** Swaps the program of imported [id] for [file], keeping its name and icon; the old one stays if this fails. */
|
||||
fun replace(context: Context, id: String, file: File, meta: Map<String, String>, onProgress: (String) -> Unit): String? {
|
||||
problem(file)?.let { return it }
|
||||
val dir = dir(context, id)
|
||||
if (!File(dir, "app").isDirectory) return "That AppImage is gone"
|
||||
if (StatFs(dir.path).availableBytes < file.length() * 3) {
|
||||
return "Not enough free space: updating needs about ${FileUtils.sizeToString(file.length() * 3)}"
|
||||
}
|
||||
return try {
|
||||
extract(context, dir, file, onProgress) ?: run {
|
||||
meta.forEach { (k, v) -> FileUtils.writeString(File(dir, k), v) }
|
||||
null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "replace $id", e)
|
||||
e.message ?: "Update failed"
|
||||
}
|
||||
}
|
||||
|
||||
/** Extracts [file] to [dir]/app, replacing what is there only once the extraction has worked. */
|
||||
private fun extract(context: Context, dir: File, file: File, onProgress: (String) -> Unit): String? {
|
||||
val image = File(dir, "image.AppImage")
|
||||
val links = File(dir, ".links").apply { mkdirs() }
|
||||
try {
|
||||
dir.mkdirs()
|
||||
// Copied in, not run where it lies: shared storage is mounted noexec, and proot's loader
|
||||
@@ -94,27 +140,41 @@ object AppImageManager {
|
||||
file.inputStream().use { input -> image.outputStream().use { FileUtils.copy(input, it) } }
|
||||
image.setExecutable(true, false)
|
||||
onProgress("Extracting ${file.name}")
|
||||
val guestDir = "$GUEST_DIR/$id"
|
||||
val out = StringBuilder()
|
||||
// uruntime's DwarFS images unpack into AppDir with squashfs-root a link to it, and keep
|
||||
// one program under several names as hard links (sharun), which Android denies apps.
|
||||
val status = GuestCommand.run(context, listOf(
|
||||
"/bin/bash", "-c",
|
||||
"cd \"$1\" && ./image.AppImage --appimage-extract >/dev/null && mv squashfs-root app",
|
||||
"extract", guestDir,
|
||||
), logName = "appimage-import") { line -> if (out.length < 2000) out.appendLine(line) }
|
||||
"cd \"$1\" && rm -rf squashfs-root AppDir && ./image.AppImage --appimage-extract >/dev/null && " +
|
||||
"rm -rf app && mv \"$(readlink -f squashfs-root)\" app && rm -f squashfs-root",
|
||||
"extract", "$GUEST_DIR/${dir.name}",
|
||||
), logName = "appimage-import", linkDir = links) { line -> if (out.length < 2000) out.appendLine(line) }
|
||||
if (status != 0 || !File(dir, "app").isDirectory) {
|
||||
FileUtils.delete(dir)
|
||||
listOf("squashfs-root", "AppDir").forEach { FileUtils.delete(File(dir, it)) }
|
||||
return "The AppImage could not be extracted" + (out.lines().lastOrNull { it.isNotBlank() }?.let { ": $it" } ?: "")
|
||||
}
|
||||
image.delete()
|
||||
describe(dir, file)
|
||||
writeMenuEntry(context, dir)
|
||||
copyLinkedFiles(File(dir, "app"), links)
|
||||
return null
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "import ${file.name}", e)
|
||||
FileUtils.delete(dir)
|
||||
return e.message ?: "Import failed"
|
||||
} finally {
|
||||
image.delete()
|
||||
FileUtils.delete(links)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Each name proot's link2symlink left for a hard link becomes a file of its own: a program run
|
||||
* through a link would see the shared file's name, and sharun picks what to start by its own.
|
||||
*/
|
||||
private fun copyLinkedFiles(app: File, links: File) {
|
||||
val roots = setOf(links.path + "/", links.canonicalPath + "/")
|
||||
app.walkTopDown().onEnter { !Files.isLink(it) }.forEach { f ->
|
||||
if (!Files.isLink(f)) return@forEach
|
||||
val target = runCatching { Os.readlink(f.path) }.getOrNull() ?: return@forEach
|
||||
if (roots.none { target.startsWith(it) }) return@forEach
|
||||
val data = f.toPath().toRealPath()
|
||||
java.nio.file.Files.delete(f.toPath())
|
||||
java.nio.file.Files.copy(data, f.toPath())
|
||||
if (java.nio.file.Files.isExecutable(data)) f.setExecutable(true, false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,14 +188,32 @@ object AppImageManager {
|
||||
FileUtils.writeString(File(dir, "name"), name)
|
||||
key("Comment")?.let { FileUtils.writeString(File(dir, "comment"), it) }
|
||||
key("Categories")?.let { FileUtils.writeString(File(dir, "categories"), it) }
|
||||
// The icon the entry names, beside it or anywhere in the image's icon theme, else .DirIcon.
|
||||
val iconName = key("Icon")
|
||||
val candidates = listOfNotNull(
|
||||
iconName?.let { File(app, "$it.png") },
|
||||
iconName?.let { n -> app.walkTopDown().maxDepth(8).filter { it.isFile && it.name == "$n.png" }.maxByOrNull { it.length() } },
|
||||
File(app, ".DirIcon"),
|
||||
)
|
||||
candidates.firstOrNull { it.isFile && isPng(it) }?.copyTo(File(dir, "icon.png"), overwrite = true)
|
||||
restoreIcon(dir)
|
||||
}
|
||||
|
||||
/**
|
||||
* The image's own icon as [dir]'s: of the files its entry names, beside it or anywhere in its
|
||||
* icon theme, a PNG of at least [SHARP_ICON] px, else the SVG, else the largest PNG; .DirIcon
|
||||
* without any.
|
||||
*/
|
||||
internal fun restoreIcon(dir: File) {
|
||||
val app = File(dir, "app")
|
||||
val entry = app.listFiles { f -> f.isFile && f.name.endsWith(".desktop") }?.firstOrNull()
|
||||
val iconName = entry?.let { FileUtils.readString(it) }?.let { desktopKey(it, "Icon") }
|
||||
val named = iconName?.let { n ->
|
||||
app.walkTopDown().maxDepth(8).filter { it.isFile && (it.name == "$n.png" || it.name == "$n.svg") }.toList()
|
||||
}.orEmpty()
|
||||
val png = named.filter(::isPng).maxByOrNull(::pngSide)
|
||||
val svg = named.firstOrNull { it.name.endsWith(".svg") }
|
||||
val pick = png?.takeIf { pngSide(it) >= SHARP_ICON } ?: svg ?: png ?: File(app, ".DirIcon").takeIf { it.isFile }
|
||||
val icon = File(dir, "icon.png")
|
||||
if (pick == null || !UserApps.saveIcon(pick, icon)) icon.delete()
|
||||
}
|
||||
|
||||
private fun pngSide(f: File): Int {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(f.path, bounds)
|
||||
return minOf(bounds.outWidth, bounds.outHeight)
|
||||
}
|
||||
|
||||
private fun isPng(f: File): Boolean = try {
|
||||
@@ -159,7 +237,7 @@ object AppImageManager {
|
||||
File(LinuxRuntime.rootDir(context), "usr/local/share/applications/droiddeck-appimage-$id.desktop")
|
||||
|
||||
/** The Linux desktop's menu entry: the desktop's own Exec rules (and droiddeck-gpu) apply to it. */
|
||||
private fun writeMenuEntry(context: Context, dir: File) {
|
||||
internal fun writeMenuEntry(context: Context, dir: File) {
|
||||
val id = dir.name
|
||||
val name = FileUtils.readString(File(dir, "name"))?.trim() ?: id
|
||||
val categories = FileUtils.readString(File(dir, "categories"))?.trim()?.takeIf { it.isNotEmpty() } ?: "Utility;"
|
||||
|
||||
@@ -89,7 +89,7 @@ object FlatpakManager {
|
||||
/** Runs [argv] in the runtime, its output also in Download/DroidDeck/flatpak-<verb>.log. */
|
||||
private fun runGuest(context: Context, argv: List<String>, fakeRoot: Boolean, onLine: (String) -> Unit): Int {
|
||||
val name = "flatpak-" + (argv.getOrNull(2)?.takeIf { argv.getOrNull(1) == HELPER } ?: "setup")
|
||||
return GuestCommand.run(context, argv, fakeRoot, name, onLine)
|
||||
return GuestCommand.run(context, argv, fakeRoot, name, onLine = onLine)
|
||||
}
|
||||
|
||||
private inline fun <T> exclusive(what: String, block: () -> T): T? {
|
||||
|
||||
@@ -18,10 +18,11 @@ object GuestCommand {
|
||||
* Runs [argv] and hands each output line to [onLine]; returns the exit status. [fakeRoot] is
|
||||
* for the package tools, which refuse any uid but 0. With [logName], everything the command
|
||||
* says also goes to Download/DroidDeck/tools/<logName>.log beside the session logs, so a problem can
|
||||
* be handed over like a session's.
|
||||
* be handed over like a session's. With [linkDir], hard links (which Android denies apps)
|
||||
* become symlinks to files proot keeps there (its link2symlink).
|
||||
*/
|
||||
fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null,
|
||||
onLine: (String) -> Unit): Int {
|
||||
linkDir: File? = null, onLine: (String) -> Unit): Int {
|
||||
val log = logName?.let {
|
||||
try {
|
||||
File(File(LinuxRuntime.debugLogDir(), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
|
||||
@@ -29,13 +30,13 @@ object GuestCommand {
|
||||
}
|
||||
log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
|
||||
try {
|
||||
return runLogged(context, argv, fakeRoot) { line -> log?.println(line); log?.flush(); onLine(line) }
|
||||
return runLogged(context, argv, fakeRoot, linkDir) { line -> log?.println(line); log?.flush(); onLine(line) }
|
||||
} finally {
|
||||
log?.close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, onLine: (String) -> Unit): Int {
|
||||
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, onLine: (String) -> Unit): Int {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
LinuxRuntime.writeAccounts(context)
|
||||
SessionFiles.stage(context, root)
|
||||
@@ -43,6 +44,7 @@ object GuestCommand {
|
||||
LinuxNetworkLinkComponent(context, root).publish()
|
||||
val runtimeDir = File(context.filesDir, ".flatpak-rt").apply { mkdirs() }
|
||||
val cmd = LinuxRuntime.prootPrefix(context, root, "/root", fakeRoot)
|
||||
if (linkDir != null) cmd.add(1, "--link2symlink")
|
||||
LinuxRuntime.binds(context, null, runtimeDir, Environment.getExternalStorageDirectory(), null)
|
||||
.forEach { cmd.add("-b"); cmd.add(it) }
|
||||
cmd += listOf(
|
||||
@@ -56,6 +58,7 @@ object GuestCommand {
|
||||
builder.environment().apply {
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
||||
put("PROOT_TMP_DIR", context.cacheDir.path)
|
||||
if (linkDir != null) put("PROOT_L2S_DIR", linkDir.path)
|
||||
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,422 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Canvas
|
||||
import android.net.Uri
|
||||
import android.os.Environment
|
||||
import android.os.StatFs
|
||||
import android.system.Os
|
||||
import android.util.Log
|
||||
import com.caverock.androidsvg.SVG
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.store.FlathubApi
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
|
||||
/**
|
||||
* The apps a user adds to the Desktop page: shell scripts, AppImages (from storage or a GitHub
|
||||
* release) and Flatpak apps. Each opens full screen under gamescope, like an emulator.
|
||||
*
|
||||
* A script lives at /opt/droiddeck-apps/<id>: its folder at `files`, the script's name in `entry`.
|
||||
* The folder is linked where it lies; shared storage is mounted noexec, so a folder holding Linux
|
||||
* programs is copied in instead. A linked folder outside internal storage is bound into the
|
||||
* session at its own path ([binds]), so the link resolves inside the guest.
|
||||
*/
|
||||
object UserApps {
|
||||
private const val TAG = "UserApps"
|
||||
const val GUEST_DIR = "/opt/droiddeck-apps"
|
||||
const val SCRIPT_LAUNCHER = "/usr/local/bin/bannerlator-script-run"
|
||||
private const val FLATPAK_OVERRIDES = ".flatpak"
|
||||
private const val ICON_SIZE = 256
|
||||
private const val ELF_SCAN_LIMIT = 4000
|
||||
private const val ICON_SUGGESTIONS = 7
|
||||
private const val ICON_FILE_LIMIT = 2L shl 20
|
||||
private val ICON_TYPES = setOf("png", "jpg", "jpeg", "webp")
|
||||
private val IGNORED_DIRS = Regex("(^|/)(node_modules|vendor|third[_-]?party|external|tests?|docs?/screenshots)/", RegexOption.IGNORE_CASE)
|
||||
private const val GITHUB_REPO = "github-repo"
|
||||
private const val GITHUB_TAG = "github-tag"
|
||||
private const val GITHUB_PUBLISHED = "github-published"
|
||||
|
||||
enum class Kind { SCRIPT, APPIMAGE, FLATPAK }
|
||||
|
||||
/**
|
||||
* [copied]: a script whose folder was copied in rather than linked. [repo]: the GitHub repository
|
||||
* an AppImage came from, [version] the release it is.
|
||||
*/
|
||||
class App(
|
||||
val key: String, val kind: Kind, val name: String, val icon: Any?, val detail: String?,
|
||||
val program: String, val args: List<String>, val copied: Boolean = false,
|
||||
val repo: String? = null, val version: String? = null,
|
||||
)
|
||||
|
||||
class Release(val tag: String, val published: String, val asset: String, val url: String)
|
||||
|
||||
sealed class UpdateCheck {
|
||||
class Current(val tag: String) : UpdateCheck()
|
||||
class Available(val release: Release) : UpdateCheck()
|
||||
class Failed(val message: String) : UpdateCheck()
|
||||
}
|
||||
|
||||
sealed class Source {
|
||||
class Script(val file: File) : Source()
|
||||
class AppImage(val file: File) : Source()
|
||||
class GitHub(val repo: String) : Source()
|
||||
class Flatpak(val id: String) : Source()
|
||||
}
|
||||
|
||||
/** [icon]: a picked file's path or a suggested icon's URL. */
|
||||
class Request(val source: Source, val name: String?, val icon: String?)
|
||||
|
||||
/** How a script's folder reaches the session: linked in place, or copied in ([bytes] to copy). */
|
||||
class ScriptPlan(val folder: File, val copy: Boolean, val bytes: Long)
|
||||
|
||||
private fun root(context: Context) = File(LinuxRuntime.rootDir(context), GUEST_DIR.substring(1))
|
||||
|
||||
private fun overrides(context: Context, flatpakId: String) = File(root(context), "$FLATPAK_OVERRIDES/$flatpakId")
|
||||
|
||||
private fun menuEntry(context: Context, id: String) =
|
||||
File(LinuxRuntime.rootDir(context), "usr/local/share/applications/droiddeck-app-$id.desktop")
|
||||
|
||||
fun list(context: Context): List<App> {
|
||||
val scripts = root(context).listFiles()?.filter { File(it, "entry").isFile }?.map { dir ->
|
||||
App(
|
||||
"script:${dir.name}", Kind.SCRIPT, readName(dir) ?: dir.name, File(dir, "icon.png").takeIf { it.isFile },
|
||||
FileUtils.readString(File(dir, "source"))?.trim(), SCRIPT_LAUNCHER, listOf("$GUEST_DIR/${dir.name}"),
|
||||
copied = !java.nio.file.Files.isSymbolicLink(File(dir, "files").toPath()),
|
||||
)
|
||||
}.orEmpty()
|
||||
val images = AppImageManager.list(context).map { item ->
|
||||
val dir = AppImageManager.dir(context, item.id)
|
||||
App(
|
||||
"appimage:${item.id}", Kind.APPIMAGE, item.name, item.icon, item.comment, AppImageManager.LAUNCHER, listOf(item.guestDir),
|
||||
repo = FileUtils.readString(File(dir, GITHUB_REPO))?.trim(), version = FileUtils.readString(File(dir, GITHUB_TAG))?.trim(),
|
||||
)
|
||||
}
|
||||
val flatpaks = FlatpakManager.installedApps(context).map { app ->
|
||||
val custom = overrides(context, app.id)
|
||||
App(
|
||||
"flatpak:${app.id}", Kind.FLATPAK, readName(custom) ?: app.name,
|
||||
File(custom, "icon.png").takeIf { it.isFile } ?: app.icon ?: FlathubApi.iconUrl(app.id),
|
||||
app.summary, FlatpakManager.LAUNCHER, listOf(app.id),
|
||||
)
|
||||
}
|
||||
return (scripts + images + flatpaks).sortedBy { it.name.lowercase() }
|
||||
}
|
||||
|
||||
private fun readName(dir: File) = FileUtils.readString(File(dir, "name"))?.trim()?.takeIf { it.isNotEmpty() }
|
||||
|
||||
/** Adds [request]; null on success, else what went wrong. */
|
||||
fun add(context: Context, request: Request, onProgress: (String, Int) -> Unit): String? {
|
||||
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
||||
val name = request.name?.trim()?.takeIf { it.isNotEmpty() }
|
||||
return withIcon(context, request.icon) { icon ->
|
||||
when (val s = request.source) {
|
||||
is Source.Script -> addScript(context, s.file, name, icon, onProgress)
|
||||
is Source.AppImage -> AppImageManager.import(context, s.file, name, icon) { onProgress(it, -1) }
|
||||
is Source.GitHub -> addFromGitHub(context, s.repo, name, icon, onProgress)
|
||||
is Source.Flatpak -> addFlatpak(context, s.id, name, icon, onProgress)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** [icon] as a file for [use]: a path as it is, a URL downloaded for the while. */
|
||||
private inline fun <T> withIcon(context: Context, icon: String?, use: (File?) -> T): T {
|
||||
if (icon == null || !icon.startsWith("https://")) return use(icon?.let(::File))
|
||||
val download = File(context.cacheDir, "icon-${System.nanoTime()}")
|
||||
try {
|
||||
return use(download.takeIf { Downloader.downloadFile(icon, it, false) { } })
|
||||
} finally {
|
||||
download.delete()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renames [app] and sets its icon: [icon] a path or URL, "" for its default, null to keep it.
|
||||
* The Linux desktop's menu entry follows.
|
||||
*/
|
||||
fun edit(context: Context, app: App, name: String, icon: String?): String? {
|
||||
val id = app.key.substringAfter(':')
|
||||
if (id.isEmpty() || '/' in id || id.startsWith(".")) return null
|
||||
val dir = when (app.kind) {
|
||||
Kind.SCRIPT -> File(root(context), id)
|
||||
Kind.APPIMAGE -> AppImageManager.dir(context, id)
|
||||
Kind.FLATPAK -> overrides(context, id)
|
||||
}.apply { mkdirs() }
|
||||
FileUtils.writeString(File(dir, "name"), name.trim())
|
||||
val target = File(dir, "icon.png")
|
||||
when {
|
||||
icon == null -> {}
|
||||
icon.isEmpty() -> if (app.kind == Kind.APPIMAGE) AppImageManager.restoreIcon(dir) else target.delete()
|
||||
else -> withIcon(context, icon) { file -> if (file == null || !saveIcon(file, target)) return context.getString(R.string.user_apps_icon_failed) }
|
||||
}
|
||||
when (app.kind) {
|
||||
Kind.SCRIPT -> writeScriptEntry(context, dir)
|
||||
Kind.APPIMAGE -> AppImageManager.writeMenuEntry(context, dir)
|
||||
Kind.FLATPAK -> {}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
fun remove(context: Context, app: App, onProgress: (String, Int) -> Unit): String? {
|
||||
val id = app.key.substringAfter(':')
|
||||
if (id.isEmpty() || '/' in id || id.startsWith(".")) return null
|
||||
return when (app.kind) {
|
||||
Kind.SCRIPT -> {
|
||||
val dir = File(root(context), id)
|
||||
// The link goes, never the folder it points to.
|
||||
File(dir, "files").delete()
|
||||
FileUtils.delete(dir)
|
||||
menuEntry(context, id).delete()
|
||||
null
|
||||
}
|
||||
Kind.APPIMAGE -> { AppImageManager.remove(context, id); null }
|
||||
Kind.FLATPAK -> FlatpakManager.uninstall(context, id, onProgress).also {
|
||||
if (it == null) FileUtils.delete(overrides(context, id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Folders linked from outside internal storage, bound into a session at their own paths. */
|
||||
fun binds(context: Context): List<String> {
|
||||
val internal = Environment.getExternalStorageDirectory().canonicalPath
|
||||
return root(context).listFiles().orEmpty().mapNotNull { dir ->
|
||||
val target = runCatching { Os.readlink(File(dir, "files").path) }.getOrNull() ?: return@mapNotNull null
|
||||
target.takeIf { !it.startsWith("$internal/") && File(it).isDirectory }
|
||||
}.distinct()
|
||||
}
|
||||
|
||||
fun planScript(script: File): ScriptPlan {
|
||||
val folder = script.canonicalFile.parentFile ?: script.parentFile!!
|
||||
var scanned = 0
|
||||
val copy = folder.walkTopDown().maxDepth(4).filter { it.isFile }.takeWhile { scanned++ < ELF_SCAN_LIMIT }.any(::isElf)
|
||||
val bytes = if (copy) folder.walkTopDown().filter { it.isFile }.sumOf { it.length() } else 0L
|
||||
return ScriptPlan(folder, copy, bytes)
|
||||
}
|
||||
|
||||
private fun isElf(f: File): Boolean = try {
|
||||
RandomAccessFile(f, "r").use { val b = ByteArray(4); it.read(b) == 4 && b[0] == 0x7f.toByte() && b[1] == 'E'.code.toByte() && b[2] == 'L'.code.toByte() && b[3] == 'F'.code.toByte() }
|
||||
} catch (e: Exception) { false }
|
||||
|
||||
private fun addScript(context: Context, script: File, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
|
||||
if (!script.isFile) return context.getString(R.string.user_apps_file_gone)
|
||||
val plan = planScript(script)
|
||||
val base = root(context).apply { mkdirs() }
|
||||
if (plan.copy && StatFs(base.path).availableBytes < plan.bytes + (64L shl 20)) {
|
||||
return context.getString(R.string.user_apps_no_space, FileUtils.sizeToString(plan.bytes))
|
||||
}
|
||||
val title = name ?: script.nameWithoutExtension
|
||||
val id = AppImageManager.idFor(title, base.list()?.toSet() ?: emptySet())
|
||||
val dir = File(base, id)
|
||||
try {
|
||||
dir.mkdirs()
|
||||
val files = File(dir, "files")
|
||||
if (plan.copy) {
|
||||
onProgress(context.getString(R.string.user_apps_copying, plan.folder.name), -1)
|
||||
copyTree(plan.folder, files)
|
||||
} else {
|
||||
Os.symlink(plan.folder.path, files.path)
|
||||
}
|
||||
FileUtils.writeString(File(dir, "entry"), script.name)
|
||||
FileUtils.writeString(File(dir, "name"), title)
|
||||
FileUtils.writeString(File(dir, "source"), script.canonicalPath)
|
||||
if (icon != null && !saveIcon(icon, File(dir, "icon.png"))) Log.w(TAG, "icon ${icon.path} could not be read")
|
||||
writeScriptEntry(context, dir)
|
||||
return null
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "script ${script.path}", e)
|
||||
File(dir, "files").takeIf { !plan.copy }?.delete()
|
||||
FileUtils.delete(dir)
|
||||
return e.message ?: context.getString(R.string.user_apps_failed)
|
||||
}
|
||||
}
|
||||
|
||||
private fun writeScriptEntry(context: Context, dir: File) {
|
||||
val id = dir.name
|
||||
val icon = if (File(dir, "icon.png").isFile) "$GUEST_DIR/$id/icon.png" else "utilities-terminal"
|
||||
FileUtils.writeString(menuEntry(context, id),
|
||||
"[Desktop Entry]\nType=Application\nName=${readName(dir) ?: id}\nExec=$SCRIPT_LAUNCHER $GUEST_DIR/$id\nIcon=$icon\n" +
|
||||
"Terminal=false\nCategories=Game;\nX-DroidDeck-App=$id\n")
|
||||
}
|
||||
|
||||
/** Copies [from] into [to], keeping Linux programs and scripts executable. */
|
||||
private fun copyTree(from: File, to: File) {
|
||||
from.walkTopDown().forEach { src ->
|
||||
val dst = File(to, src.relativeTo(from).path)
|
||||
if (src.isDirectory) dst.mkdirs()
|
||||
else {
|
||||
src.inputStream().use { input -> dst.outputStream().use { FileUtils.copy(input, it) } }
|
||||
if (isElf(dst) || dst.extension == "sh") dst.setExecutable(true, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** [source] (PNG, JPEG, WebP or SVG) as the app's icon: a PNG no larger than [ICON_SIZE] on a side. */
|
||||
internal fun saveIcon(source: File, target: File): Boolean {
|
||||
val bitmap = (if (isSvg(source)) renderSvg(source) else decodeScaled(source)) ?: return false
|
||||
return try {
|
||||
target.parentFile?.mkdirs()
|
||||
target.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "icon ${source.path}", e); false
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun decodeScaled(source: File): Bitmap? {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(source.path, bounds)
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
|
||||
var sample = 1
|
||||
while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= ICON_SIZE) sample *= 2
|
||||
val decoded = BitmapFactory.decodeFile(source.path, BitmapFactory.Options().apply { inSampleSize = sample }) ?: return null
|
||||
val scale = ICON_SIZE.toFloat() / maxOf(decoded.width, decoded.height)
|
||||
if (scale >= 1f) return decoded
|
||||
val scaled = Bitmap.createScaledBitmap(decoded, (decoded.width * scale).toInt().coerceAtLeast(1), (decoded.height * scale).toInt().coerceAtLeast(1), true)
|
||||
if (scaled !== decoded) decoded.recycle()
|
||||
return scaled
|
||||
}
|
||||
|
||||
private fun isSvg(f: File): Boolean = try {
|
||||
f.inputStream().use { val head = ByteArray(1024); val n = it.read(head); n > 0 && String(head, 0, n).contains("<svg") }
|
||||
} catch (e: Exception) { false }
|
||||
|
||||
/** An SVG drawn at [ICON_SIZE], centred in its own proportions. */
|
||||
private fun renderSvg(source: File): Bitmap? = try {
|
||||
val svg = source.inputStream().use { SVG.getFromInputStream(it) }
|
||||
if (svg.documentViewBox == null && svg.documentWidth > 0 && svg.documentHeight > 0) {
|
||||
svg.setDocumentViewBox(0f, 0f, svg.documentWidth, svg.documentHeight)
|
||||
}
|
||||
svg.setDocumentWidth("100%")
|
||||
svg.setDocumentHeight("100%")
|
||||
Bitmap.createBitmap(ICON_SIZE, ICON_SIZE, Bitmap.Config.ARGB_8888).also { svg.renderToCanvas(Canvas(it)) }
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "svg ${source.path}", e); null
|
||||
}
|
||||
|
||||
/** "owner/repo" from what was typed: any link into the repository, its clone address, or the short form. */
|
||||
fun githubRepo(input: String): String? {
|
||||
val t = input.trim()
|
||||
val m = Regex("^(?:https?://)?(?:www\\.)?github\\.com[/:]([\\w.-]+)/([\\w.-]+)", RegexOption.IGNORE_CASE).find(t)
|
||||
?: Regex("^git@github\\.com:([\\w.-]+)/([\\w.-]+)", RegexOption.IGNORE_CASE).find(t)
|
||||
?: Regex("^([\\w.-]+)/([\\w.-]+)/?$").find(t) ?: return null
|
||||
val repo = m.groupValues[2].removeSuffix(".git")
|
||||
return if (repo.isEmpty() || repo == "." || repo == "..") null else "${m.groupValues[1]}/$repo"
|
||||
}
|
||||
|
||||
/** The ARM64 AppImage among a release's files: named for aarch64/arm64, else for no other CPU. */
|
||||
internal fun pickAsset(names: List<String>): String? {
|
||||
val images = names.filter { it.endsWith(".appimage", ignoreCase = true) }
|
||||
return images.firstOrNull { Regex("aarch64|arm64", RegexOption.IGNORE_CASE).containsMatchIn(it) }
|
||||
?: images.firstOrNull { !Regex("x86_64|x86-64|amd64|x64|i[36]86|armhf|armv7", RegexOption.IGNORE_CASE).containsMatchIn(it) }
|
||||
}
|
||||
|
||||
/** The newest release of [repo] with an ARM64 AppImage, preferring full releases; else what went wrong. */
|
||||
private fun latestRelease(context: Context, repo: String): Pair<Release?, String?> {
|
||||
val body = Downloader.downloadString("https://api.github.com/repos/$repo/releases?per_page=15")
|
||||
val releases = body?.let { runCatching { JSONArray(it) }.getOrNull() }
|
||||
?: return null to context.getString(R.string.user_apps_github_unreachable, repo)
|
||||
val candidates = (0 until releases.length()).mapNotNull { i ->
|
||||
val r = releases.getJSONObject(i)
|
||||
if (r.optBoolean("draft")) return@mapNotNull null
|
||||
val assets = r.optJSONArray("assets") ?: return@mapNotNull null
|
||||
val byName = (0 until assets.length()).associate { j -> assets.getJSONObject(j).let { it.getString("name") to it.getString("browser_download_url") } }
|
||||
pickAsset(byName.keys.toList())?.let { asset ->
|
||||
r.optBoolean("prerelease") to Release(r.optString("tag_name", asset), r.optString("published_at"), asset, byName.getValue(asset))
|
||||
}
|
||||
}
|
||||
val pick = (candidates.firstOrNull { !it.first } ?: candidates.firstOrNull())?.second
|
||||
return pick to if (pick == null) context.getString(R.string.user_apps_github_no_appimage, repo) else null
|
||||
}
|
||||
|
||||
/** Downloads [release] and hands it to [use]; null on success, else what went wrong. */
|
||||
private fun withDownload(context: Context, release: Release, onProgress: (String, Int) -> Unit, use: (File) -> String?): String? {
|
||||
val download = File(context.cacheDir, "github-${release.asset}")
|
||||
try {
|
||||
val label = context.getString(R.string.user_apps_downloading, release.asset)
|
||||
val ok = Downloader.downloadFile(release.url, download, false) { f -> onProgress(label, if (f < 0) -1 else Math.round(f * 100f)) }
|
||||
return if (ok) use(download) else context.getString(R.string.user_apps_download_failed)
|
||||
} finally {
|
||||
download.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun githubMeta(repo: String, release: Release) =
|
||||
mapOf(GITHUB_REPO to repo, GITHUB_TAG to release.tag, GITHUB_PUBLISHED to release.published)
|
||||
|
||||
private fun addFromGitHub(context: Context, repo: String, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
|
||||
onProgress(context.getString(R.string.user_apps_github_checking, repo), -1)
|
||||
val (release, problem) = latestRelease(context, repo)
|
||||
if (release == null) return problem
|
||||
return withDownload(context, release, onProgress) { file ->
|
||||
AppImageManager.import(context, file, name ?: repo.substringAfter('/'), icon, githubMeta(repo, release)) { onProgress(it, -1) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Images in [repo] that look like its icon, best first, then its owner's picture: links to show
|
||||
* as suggestions and to download once one is picked.
|
||||
*/
|
||||
fun githubIcons(repo: String): List<String> {
|
||||
val info = Downloader.downloadString("https://api.github.com/repos/$repo")?.let { runCatching { JSONObject(it) }.getOrNull() } ?: return emptyList()
|
||||
val branch = info.optString("default_branch").ifEmpty { return emptyList() }
|
||||
val avatar = info.optJSONObject("owner")?.optString("avatar_url")?.takeIf { it.startsWith("https://") }
|
||||
val tree = Downloader.downloadString("https://api.github.com/repos/$repo/git/trees/${Uri.encode(branch)}?recursive=1")
|
||||
?.let { runCatching { JSONObject(it).optJSONArray("tree") }.getOrNull() }
|
||||
val project = repo.substringAfter('/').lowercase().replace(Regex("[^a-z0-9]"), "")
|
||||
val images = (0 until (tree?.length() ?: 0)).mapNotNull { i ->
|
||||
val entry = tree!!.getJSONObject(i)
|
||||
val path = entry.optString("path")
|
||||
val size = entry.optLong("size")
|
||||
val file = path.substringAfterLast('/').lowercase()
|
||||
val stem = file.substringBeforeLast('.').replace(Regex("[^a-z0-9]"), "")
|
||||
if (entry.optString("type") != "blob" || size !in 512..ICON_FILE_LIMIT || file.substringAfterLast('.') !in ICON_TYPES) return@mapNotNull null
|
||||
if (IGNORED_DIRS.containsMatchIn(path)) return@mapNotNull null
|
||||
val score = listOf("icon" in stem, "logo" in stem, project.isNotEmpty() && project in stem, "icon" in path.lowercase()).count { it }
|
||||
if (score == 0) null else Triple(path, score, size)
|
||||
}.sortedWith(compareByDescending<Triple<String, Int, Long>> { it.second }.thenByDescending { it.third })
|
||||
val urls = images.take(ICON_SUGGESTIONS).map { (path, _, _) ->
|
||||
"https://raw.githubusercontent.com/$repo/${Uri.encode(branch)}/" + path.split('/').joinToString("/") { Uri.encode(it) }
|
||||
}
|
||||
return urls + listOfNotNull(avatar)
|
||||
}
|
||||
|
||||
/** Whether [app], added from GitHub, has a newer release than the one it is. */
|
||||
fun checkUpdate(context: Context, app: App): UpdateCheck {
|
||||
val repo = app.repo ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed))
|
||||
val (release, problem) = latestRelease(context, repo)
|
||||
if (release == null) return UpdateCheck.Failed(problem ?: context.getString(R.string.user_apps_update_failed))
|
||||
val published = FileUtils.readString(File(AppImageManager.dir(context, app.key.substringAfter(':')), GITHUB_PUBLISHED))?.trim().orEmpty()
|
||||
// Releases are compared by date, so a newest one without an ARM64 build never reads as a downgrade.
|
||||
val newer = if (published.isNotEmpty() && release.published.isNotEmpty()) release.published > published else release.tag != app.version
|
||||
return if (newer) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
|
||||
}
|
||||
|
||||
fun update(context: Context, app: App, release: Release, onProgress: (String, Int) -> Unit): String? {
|
||||
val repo = app.repo ?: return context.getString(R.string.user_apps_update_failed)
|
||||
return withDownload(context, release, onProgress) { file ->
|
||||
AppImageManager.replace(context, app.key.substringAfter(':'), file, githubMeta(repo, release)) { onProgress(it, -1) }
|
||||
}
|
||||
}
|
||||
|
||||
/** A Flathub app ID from what was typed: the ID itself or its Flathub page. */
|
||||
fun flatpakId(input: String): String? {
|
||||
val t = input.trim().removeSuffix("/").substringAfterLast('/')
|
||||
return t.takeIf { Regex("^[A-Za-z][\\w-]*(\\.[A-Za-z0-9_][\\w-]*){2,}$").matches(it) }
|
||||
}
|
||||
|
||||
private fun addFlatpak(context: Context, id: String, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
|
||||
if (!FlatpakManager.ready(context)) FlatpakManager.setup(context, onProgress)?.let { return it }
|
||||
FlatpakManager.install(context, id, onProgress)?.let { return it }
|
||||
val custom = overrides(context, id)
|
||||
if (name != null) FileUtils.writeString(File(custom.apply { mkdirs() }, "name"), name)
|
||||
if (icon != null && !saveIcon(icon, File(custom, "icon.png"))) Log.w(TAG, "icon ${icon.path} could not be read")
|
||||
return null
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user