feat(desktop): add desktop uninstall and legacy LXQt cleanup (#493)

This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-10-10 10:59:32 -04:00
1 parent 79d92111e4
commit 67a9ea2f42
28 files changed
+728 -25

No files matched your search

@@ -101,9 +101,21 @@ object DesktopCatalog {
fun desktopInstalled(context: Context): Boolean = desktopInstalled(LinuxRuntime.rootDir(context))
fun desktopInstalled(root: File): Boolean =
!File(root, DesktopRemoval.PENDING).exists() &&
File(root, "usr/bin/kwin_wayland").isFile &&
FileUtils.readString(File(root, ".droiddeck-pkg-$DESKTOP_ID"))?.trim() == BuildConfig.DESKTOP_KDE_TAG
fun desktopPresent(context: Context): Boolean {
val root = LinuxRuntime.rootDir(context)
return File(root, DesktopRemoval.PENDING).exists() || marker(context, DESKTOP_ID).exists()
}
fun cleanLegacy(context: Context, listener: LinuxRuntimeInstaller.ProgressListener? = null) =
DesktopRemoval.cleanLegacy(context, listener)
fun removeDesktop(context: Context, listener: LinuxRuntimeInstaller.ProgressListener): String? =
DesktopRemoval.remove(context, listener)
/** Downloads, verifies and installs one package. Returns null on success, else a message. */
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
val root = LinuxRuntime.rootDir(context)
@@ -143,7 +155,13 @@ object DesktopCatalog {
if (!LinuxRuntimeInstaller.extract(context, download, root, listener)) return context.getString(R.string.deskpkg_extract_failed)
}
}
if (entry.id == DESKTOP_ID) {
cleanLegacy(context, listener)
val pending = File(root, DesktopRemoval.PENDING)
check(!pending.exists() || pending.delete()) { "Could not finish desktop installation" }
}
FileUtils.writeString(marker(context, entry.id), entry.version)
check(installed(context, entry.id) == entry.version) { "Could not finish package installation" }
return null
} catch (e: Exception) {
Log.e(TAG, "install ${entry.id}", e)
@@ -0,0 +1,97 @@
package com.droiddeck.launcher.runtime
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.nio.file.attribute.BasicFileAttributes
import java.security.MessageDigest
/** Removes only unchanged, recorded package files. Never visits home or follows a symlink. */
internal object DesktopFileRemoval {
data class Entry(val kind: String, val size: Long, val identity: String, val path: String) {
companion object {
fun parse(line: String): Entry {
val parts = line.split('\t', limit = 4)
require(parts.size == 4 && parts[0] in setOf("F", "L")) { "Invalid removal inventory" }
return Entry(parts[0], parts[1].toLong(), parts[2], parts[3])
}
}
}
data class Result(val removed: Int, val bytes: Long, val kept: Int)
fun remove(root: File, entries: Iterable<Entry>, protected: Set<String>, progress: (Int) -> Unit = {}): Result {
var removed = 0
var bytes = 0L
var kept = 0
val buffer = ByteArray(65536)
val total = (entries as? Collection<*>)?.size ?: 0
val directories = mutableSetOf<File>()
for ((index, entry) in entries.withIndex()) {
val file = safeFile(root, entry.path)
if (file == null || entry.path in protected) { kept++; continue }
val attrs = try { Files.readAttributes(file.toPath(), BasicFileAttributes::class.java, NOFOLLOW_LINKS) }
catch (_: java.nio.file.NoSuchFileException) { continue }
val matches = when (entry.kind) {
"L" -> attrs.isSymbolicLink && Files.readSymbolicLink(file.toPath()).toString() == entry.identity
else -> attrs.isRegularFile && attrs.size() == entry.size && sha(file, buffer) == entry.identity
}
if (!matches) { kept++; continue }
Files.delete(file.toPath()) // A failure propagates; the pending marker makes retry possible.
removed++
bytes += if (attrs.isRegularFile) attrs.size() else 0
var parent = file.parentFile
while (parent != root && parent != null) { directories.add(parent); parent = parent.parentFile }
if (index % 200 == 0) progress(if (total > 0) index * 99 / total else -1)
}
// Only now-empty parents of removed files, never a recursive delete of a package directory.
for (dir in directories.sortedByDescending { it.path.length }) {
if (dir.list()?.isEmpty() == true && !dir.delete()) throw IOException("Cannot remove $dir")
}
progress(99)
return Result(removed, bytes, kept)
}
internal fun safeFile(root: File, name: String): File? {
if (Files.isSymbolicLink(root.toPath())) return null
val parts = name.split('/')
if (parts.firstOrNull() !in setOf("usr", "etc") || parts.any { it.isEmpty() || it == "." || it == ".." }) return null
// Even an in-root symlink in a parent can redirect deletion into a user's data.
var parent = root
for (part in parts.dropLast(1)) {
parent = File(parent, part)
if (Files.isSymbolicLink(parent.toPath())) return null
}
return File(root, name)
}
internal fun sha(file: File, buffer: ByteArray = ByteArray(65536)): String {
val digest = MessageDigest.getInstance("SHA-256")
file.inputStream().buffered().use { input ->
while (true) { val n = input.read(buffer); if (n < 0) break; digest.update(buffer, 0, n) }
}
val digits = "0123456789abcdef"
return buildString(64) {
for (byte in digest.digest()) { val b = byte.toInt() and 255; append(digits[b ushr 4]); append(digits[b and 15]) }
}
}
/** The base runtime's pacman database is still present: desktop archives never replace it. */
fun runtimeFiles(root: File): Set<String> = buildSet {
val database = File(root, "var/lib/pacman/local")
if (!database.isDirectory || Files.isSymbolicLink(database.toPath())) throw IOException("Runtime package database missing")
for (pkg in database.listFiles().orEmpty()) {
val files = File(pkg, "files")
if (!pkg.isDirectory || Files.isSymbolicLink(pkg.toPath()) || !files.isFile || Files.isSymbolicLink(files.toPath())) continue
var inFiles = false
files.forEachLine { line ->
when {
line == "%FILES%" -> inFiles = true
line.startsWith('%') -> inFiles = false
inFiles && line.isNotEmpty() && !line.endsWith('/') -> add(line)
}
}
}
if (isEmpty()) throw IOException("Runtime package inventory missing")
}
}
@@ -0,0 +1,77 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.FileUtils
import java.io.File
import java.util.zip.GZIPInputStream
/** Inventories are generated from pinned archives by tools/desktop-kde/removal-manifests.py. */
internal object DesktopRemoval {
const val PENDING = ".droiddeck-desktop-removing"
private const val CLEANING = ".droiddeck-lxqt-cleaning-v1"
private const val CLEANED = ".droiddeck-lxqt-cleaned-v1"
private fun lines(context: Context, name: String) =
GZIPInputStream(context.assets.open("desktop-removal/$name")).bufferedReader().use { it.readLines() }
private fun protected(context: Context, root: File) =
DesktopFileRemoval.runtimeFiles(root) + lines(context, "emulators-keep.txt.gzip")
/** Called before a guest starts or just after KDE extraction; retries after a process death. */
fun cleanLegacy(context: Context, listener: LinuxRuntimeInstaller.ProgressListener? = null) {
val root = LinuxRuntime.rootDir(context)
if (FileUtils.readString(File(root, CLEANED))?.trim() == "1") return
if (!File(root, CLEANING).exists() && !File(root, ".droiddeck-pkg-desktop").exists() && !File(root, "usr/bin/lxqt-session").exists()) return
listener?.onProgress(context.getString(R.string.desktop_cleaning_legacy), -1)
val keep = protected(context, root) + lines(context, "kde-keep.txt.gzip")
val pending = File(root, CLEANING)
FileUtils.writeString(pending, "1")
check(FileUtils.readString(pending)?.trim() == "1") { "Could not reserve LXQt cleanup" }
val result = GZIPInputStream(context.assets.open("desktop-removal/lxqt-r1.tsv.gzip")).bufferedReader().use { reader ->
DesktopFileRemoval.remove(root, reader.lineSequence().map(DesktopFileRemoval.Entry::parse).asIterable(), keep)
}
FileUtils.writeString(File(root, CLEANED), "1")
check(FileUtils.readString(File(root, CLEANED))?.trim() == "1") { "Could not finish LXQt cleanup" }
File(root, ".droiddeck-pkg-desktop").delete()
pending.delete()
Log.i("DesktopRemoval", "LXQt: $result")
}
fun remove(context: Context, listener: LinuxRuntimeInstaller.ProgressListener): String? = try {
val root = LinuxRuntime.rootDir(context)
val pending = File(root, PENDING)
val marker = File(root, ".droiddeck-pkg-${DesktopCatalog.DESKTOP_ID}")
val version = FileUtils.readString(pending)?.trim() ?: FileUtils.readString(marker)?.trim()
val versions = context.assets.open("desktop-removal/versions.txt").bufferedReader().use { it.readLines() }
check(version in versions) { context.getString(R.string.desktop_removal_unknown) }
// Validate all inventories and the runtime database before dropping the installed marker.
val entries = lines(context, "kde-remove.tsv.gzip").map(DesktopFileRemoval.Entry::parse)
val keep = protected(context, root)
cleanLegacy(context, listener)
FileUtils.writeString(pending, version!!)
check(FileUtils.readString(pending)?.trim() == version) { "Could not reserve desktop removal" }
if (marker.exists() && !marker.delete()) error("Could not clear desktop marker")
val removing = context.getString(R.string.desktop_removing)
val result = DesktopFileRemoval.remove(root, entries, keep) { listener.onProgress(removing, it) }
// APK-staged desktop files are matched against the APK too; keep user-modified copies.
for ((asset, path) in com.droiddeck.launcher.session.SessionFiles.DESKTOP_FILES) {
val target = DesktopFileRemoval.safeFile(root, path) ?: continue
if (!isRegularFile(target)) continue
val content = context.assets.open("linuxfs/$asset").use { it.readBytes() }
if (target.length() == content.size.toLong() && target.inputStream().use { it.readBytes() }.contentEquals(content)) {
if (!target.delete()) error("Could not remove $path")
}
}
if (!pending.delete()) error("Could not finish desktop removal")
Log.i("DesktopRemoval", "KDE: $result")
listener.onProgress(context.getString(R.string.desktop_removed), 100)
null
} catch (e: Exception) {
Log.e("DesktopRemoval", "remove", e)
e.message ?: context.getString(R.string.deskpkg_install_failed)
}
private fun isRegularFile(file: File) = java.nio.file.Files.isRegularFile(file.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)
}
@@ -85,6 +85,7 @@ public final class LinuxRuntimeInstaller {
volatile int percent = -1;
volatile boolean ok;
final boolean removal;
boolean maintenance;
Job(boolean removal, String stage) { this.removal = removal; this.stage = stage; }
}
@@ -139,7 +140,7 @@ public final class LinuxRuntimeInstaller {
Job job;
boolean owner;
synchronized (JOB_LOCK) {
if (running != null && running.removal) return false;
if (running != null && (running.removal || running.maintenance)) return false;
owner = running == null;
if (owner) { running = new Job(false, context.getString(R.string.user_apps_starting)); removalError = null; }
job = running;
@@ -171,7 +172,7 @@ public final class LinuxRuntimeInstaller {
/** True while an install is running in this process, whoever started it. */
public static boolean isInstalling() {
synchronized (JOB_LOCK) {
return running != null && !running.removal;
return running != null && !running.removal && !running.maintenance;
}
}
@@ -183,6 +184,53 @@ public final class LinuxRuntimeInstaller {
synchronized (JOB_LOCK) { return running != null && running.removal; }
}
public static boolean isMaintaining() {
synchronized (JOB_LOCK) { return running != null && running.maintenance; }
}
/** Reserve an in-place package operation with the same exclusion/progress as runtime installs. */
public static Maintenance beginMaintenance(Context context, String stage) {
if (com.droiddeck.launcher.session.SessionState.INSTANCE.getRunning()) return null;
com.droiddeck.launcher.session.SessionPhase phase = com.droiddeck.launcher.session.SessionState.INSTANCE.getPhase();
if (phase != com.droiddeck.launcher.session.SessionPhase.IDLE && phase != com.droiddeck.launcher.session.SessionPhase.FAILED) return null;
synchronized (JOB_LOCK) {
if (running != null) return null;
removalError = null;
running = new Job(false, stage);
running.maintenance = true;
return new Maintenance(running);
}
}
public interface MaintenanceWork { String run(ProgressListener listener); }
public static final class Maintenance {
private final Job job;
private final java.util.concurrent.atomic.AtomicBoolean started = new java.util.concurrent.atomic.AtomicBoolean();
private Maintenance(Job job) { this.job = job; }
public boolean run(ProgressListener listener, MaintenanceWork work) {
if (!started.compareAndSet(false, true)) return join(job, listener);
if (listener != null) job.listeners.add(listener);
try {
removalError = work.run((stage, percent) -> {
job.stage = stage;
job.percent = percent;
for (ProgressListener l : job.listeners) l.onProgress(stage, percent);
});
job.ok = removalError == null;
return job.ok;
} catch (Exception e) {
removalError = e.getMessage();
Log.e(TAG, "maintenance", e);
return false;
} finally {
synchronized (JOB_LOCK) { running = null; }
job.done.countDown();
if (listener != null) job.listeners.remove(listener);
}
}
}
public static String removalError() { return removalError; }
public static boolean hasRemovalPending(Context context) {
@@ -30,7 +30,7 @@ class RuntimeInstallService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val removal = intent?.action == ACTION_REMOVE
val release = intent?.let(::releaseFrom)
startForeground(NOTIFICATION_ID, notification(getString(if (removal) R.string.rtinst_removing else R.string.user_apps_starting), -1))
startForeground(NOTIFICATION_ID, notification(getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (removal) R.string.rtinst_removing else R.string.user_apps_starting), -1))
if (release == null && !removal) {
stopSelf(startId)
return START_NOT_STICKY
@@ -68,7 +68,7 @@ class RuntimeInstallService : Service() {
PendingIntent.FLAG_IMMUTABLE)
return Notification.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentTitle(getString(if (LinuxRuntimeInstaller.isRemoving()) R.string.rtinst_title_removing else R.string.rtinst_title_installing))
.setContentTitle(getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (LinuxRuntimeInstaller.isRemoving()) R.string.rtinst_title_removing else R.string.rtinst_title_installing))
.setContentText(stage)
.setProgress(100, percent.coerceIn(0, 100), percent < 0)
.setContentIntent(open)