Skip to content

Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.

Add optional Office engine core: LOKit binding, isolated :office service, installers

Chethan6169386fc94e218
diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro
index 9f9c54a..8281ef7 100644
--- a/app/proguard-rules.pro
+++ b/app/proguard-rules.pro
@@ -45,3 +45,8 @@
-keepclassmembers class * {
@android.webkit.JavascriptInterface <methods>;
}
+
+# ── Optional Office engine (LibreOfficeKit JNI) ──
+# liblo-native-code.so binds to these by name: Java_org_libreoffice_kit_* natives, the
+# "handle" ByteBuffer fields and the messageRetrieved* callbacks. Nothing may be renamed.
+-keep class org.libreoffice.kit.** { *; }
diff --git a/app/src/foss/AndroidManifest.xml b/app/src/foss/AndroidManifest.xml
new file mode 100644
index 0000000..8311763
--- /dev/null
+++ b/app/src/foss/AndroidManifest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ foss flavor only. The single network use in the whole app: downloading the optional Office
+ engine (powered by LibreOffice) when the user asks for it in Settings. The archive is pinned by
+ size + SHA-256 (OfficeEngineManifest). Documents never leave the device; every WebView still
+ blocks network loads (DocxWebRenderer, HtmlToPdfConverter).
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools">
+
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
+
+ <!--
+ largeHeap: the engine archive is xz-compressed with a 256 MiB dictionary, which the pure-Java
+ decoder must hold in the Java heap while unpacking.
+ -->
+ <application android:largeHeap="true">
+ <service
+ android:name="androidx.work.impl.foreground.SystemForegroundService"
+ android:foregroundServiceType="dataSync"
+ tools:node="merge" />
+ </application>
+</manifest>
diff --git a/app/src/foss/java/com/chethan616/clearpdf/office/OfficeEngineDownloadWorker.kt b/app/src/foss/java/com/chethan616/clearpdf/office/OfficeEngineDownloadWorker.kt
new file mode 100644
index 0000000..df9e35c
--- /dev/null
+++ b/app/src/foss/java/com/chethan616/clearpdf/office/OfficeEngineDownloadWorker.kt
@@ -0,0 +1,214 @@
+package com.chethan616.clearpdf.office
+
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.content.Context
+import android.content.pm.ServiceInfo
+import android.os.Build
+import androidx.core.app.NotificationCompat
+import androidx.work.CoroutineWorker
+import androidx.work.ForegroundInfo
+import androidx.work.WorkManager
+import androidx.work.WorkerParameters
+import androidx.work.workDataOf
+import com.chethan616.clearpdf.R
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ensureActive
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.withContext
+import org.tukaani.xz.XZInputStream
+import java.io.BufferedInputStream
+import java.io.File
+import java.io.FileOutputStream
+import java.io.IOException
+import java.net.HttpURLConnection
+import java.net.URL
+import java.security.MessageDigest
+import kotlin.coroutines.coroutineContext
+
+/**
+ * foss flavor: downloads, verifies and installs the Office engine.
+ *
+ * 1. Resumable download (HTTP Range) into office-engine/download/<sha256>.part. The bytes already
+ * on disk are re-hashed first so the streaming SHA-256 covers the whole file.
+ * 2. The download is accepted only if its size and SHA-256 match [OfficeEngineManifest].
+ * 3. tar.xz is unpacked into office-engine/staging (zip-slip checked), then
+ * [OfficeEngineStore.commit] swaps it in atomically. The previous engine is removed only
+ * after that succeeds.
+ *
+ * Runs as a foreground dataSync worker with a Cancel action. The partial download survives
+ * cancellation and failure, so retrying resumes where it stopped.
+ */
+class OfficeEngineDownloadWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
+
+ companion object {
+ const val UNIQUE_NAME = "office-engine-install"
+ const val KEY_PHASE = "phase"
+ const val KEY_DONE = "done"
+ const val KEY_TOTAL = "total"
+ const val KEY_ERROR = "error"
+ const val PHASE_DOWNLOAD = "download"
+ const val PHASE_INSTALL = "install"
+
+ private const val CHANNEL_ID = "office_engine"
+ private const val NOTIFICATION_ID = 0x0FF1CE
+ private const val BUFFER = 1 shl 16
+
+ /** xz dictionary of these bundles is 256 MiB; decoding needs about that much heap. */
+ private const val XZ_MEMORY_LIMIT_KIB = 300 * 1024
+ }
+
+ private val notificationManager =
+ context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
+
+ override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
+ val bundle = OfficeEngineManifest.bundleForDevice()
+ ?: return@withContext Result.failure(workDataOf(KEY_ERROR to "This device is not supported"))
+ try {
+ setForeground(foregroundInfo(0, bundle.sizeBytes, indeterminate = true, installing = false))
+ val archive = download(bundle)
+ setProgress(workDataOf(KEY_PHASE to PHASE_INSTALL))
+ setForeground(foregroundInfo(0, 0, indeterminate = true, installing = true))
+ install(archive, bundle.abi)
+ archive.delete()
+ Result.success()
+ } catch (e: kotlinx.coroutines.CancellationException) {
+ throw e
+ } catch (e: OutOfMemoryError) {
+ OfficeEngineStore.stagingDir(applicationContext).deleteRecursively()
+ Result.failure(workDataOf(KEY_ERROR to "Not enough memory to unpack the engine on this device"))
+ } catch (e: Exception) {
+ OfficeEngineStore.stagingDir(applicationContext).deleteRecursively()
+ Result.failure(workDataOf(KEY_ERROR to (e.message ?: e.javaClass.simpleName)))
+ }
+ }
+
+ private suspend fun download(bundle: OfficeEngineManifest.Bundle): File {
+ val dir = OfficeEngineStore.downloadDir(applicationContext).apply { mkdirs() }
+ // Drop parts of other versions/ABIs.
+ dir.listFiles()?.filter { !it.name.startsWith(bundle.sha256) }?.forEach { it.delete() }
+ val part = File(dir, "${bundle.sha256}.part")
+ val digest = MessageDigest.getInstance("SHA-256")
+
+ if (part.length() > bundle.sizeBytes) part.delete()
+ var have = part.length()
+ if (have > 0) part.inputStream().use { input -> hashInto(digest, input) }
+
+ if (have < bundle.sizeBytes) {
+ val conn = URL(bundle.url).openConnection() as HttpURLConnection
+ conn.instanceFollowRedirects = true
+ conn.connectTimeout = 20_000
+ conn.readTimeout = 60_000
+ if (have > 0) conn.setRequestProperty("Range", "bytes=$have-")
+ try {
+ val code = conn.responseCode
+ val append = when (code) {
+ HttpURLConnection.HTTP_PARTIAL -> true
+ HttpURLConnection.HTTP_OK -> false
+ else -> throw IOException("Download failed (HTTP $code)")
+ }
+ if (!append) {
+ // Server ignored the range: start over.
+ have = 0
+ digest.reset()
+ }
+ BufferedInputStream(conn.inputStream, BUFFER).use { input ->
+ FileOutputStream(part, append).use { out ->
+ val buf = ByteArray(BUFFER)
+ var lastReport = 0L
+ while (true) {
+ coroutineContext.ensureActive()
+ val n = input.read(buf)
+ if (n < 0) break
+ out.write(buf, 0, n)
+ digest.update(buf, 0, n)
+ have += n
+ if (have > bundle.sizeBytes) throw IOException("Download is larger than expected")
+ if (have - lastReport >= 512 * 1024 || have == bundle.sizeBytes) {
+ lastReport = have
+ setProgress(workDataOf(KEY_PHASE to PHASE_DOWNLOAD, KEY_DONE to have, KEY_TOTAL to bundle.sizeBytes))
+ notificationManager.notify(
+ NOTIFICATION_ID,
+ notification(have, bundle.sizeBytes, indeterminate = false, installing = false)
+ )
+ }
+ }
+ }
+ }
+ } finally {
+ conn.disconnect()
+ }
+ }
+
+ val sha = digest.digest().joinToString("") { "%02x".format(it) }
+ if (have != bundle.sizeBytes || sha != bundle.sha256) {
+ part.delete()
+ throw IOException("Download verification failed (checksum mismatch)")
+ }
+ return part
+ }
+
+ private suspend fun install(archive: File, abi: String) {
+ val context = applicationContext
+ if (Runtime.getRuntime().maxMemory() < 290L * 1024 * 1024) {
+ throw IOException("Not enough memory to unpack the engine on this device")
+ }
+ val staging = OfficeEngineStore.resetStaging(context)
+ val job = coroutineContext
+ val files = XZInputStream(BufferedInputStream(archive.inputStream(), BUFFER), XZ_MEMORY_LIMIT_KIB).use { xz ->
+ EngineArchiveLayout.extractTar(xz, staging, abi) { !job.isActive }
+ }
+ if (files == 0) throw IOException("Engine archive is empty")
+ OfficeEngineClient.stopEngineProcess(context)
+ OfficeEngineStore.commit(context, staging, abi)
+ OfficeEngineClient.clearCache(context)
+ }
+
+ private fun hashInto(digest: MessageDigest, input: java.io.InputStream) {
+ val buf = ByteArray(BUFFER)
+ while (true) {
+ val n = input.read(buf)
+ if (n < 0) break
+ digest.update(buf, 0, n)
+ }
+ }
+
+ private fun foregroundInfo(done: Long, total: Long, indeterminate: Boolean, installing: Boolean): ForegroundInfo {
+ val notification = notification(done, total, indeterminate, installing)
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ ForegroundInfo(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
+ } else {
+ ForegroundInfo(NOTIFICATION_ID, notification)
+ }
+ }
+
+ private fun notification(done: Long, total: Long, indeterminate: Boolean, installing: Boolean): android.app.Notification {
+ val context = applicationContext
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ notificationManager.createNotificationChannel(
+ NotificationChannel(
+ CHANNEL_ID,
+ context.getString(R.string.office_engine_notification_channel),
+ NotificationManager.IMPORTANCE_LOW
+ )
+ )
+ }
+ val cancel = WorkManager.getInstance(context).createCancelPendingIntent(id)
+ val max = 1000
+ val progress = if (total > 0) ((done * max) / total).toInt() else 0
+ return NotificationCompat.Builder(context, CHANNEL_ID)
+ .setSmallIcon(android.R.drawable.stat_sys_download)
+ .setContentTitle(context.getString(R.string.office_engine_title))
+ .setContentText(
+ context.getString(
+ if (installing) R.string.office_engine_installing else R.string.office_engine_downloading
+ )
+ )
+ .setOnlyAlertOnce(true)
+ .setOngoing(true)
+ .setSilent(true)
+ .setProgress(max, progress, indeterminate)
+ .addAction(0, context.getString(R.string.office_engine_cancel), cancel)
+ .build()
+ }
+}
diff --git a/app/src/foss/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt b/app/src/foss/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt
new file mode 100644
index 0000000..2bc58e6
--- /dev/null
+++ b/app/src/foss/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt
@@ -0,0 +1,102 @@
+package com.chethan616.clearpdf.office
+
+import android.content.Context
+import androidx.work.Constraints
+import androidx.work.ExistingWorkPolicy
+import androidx.work.NetworkType
+import androidx.work.OneTimeWorkRequestBuilder
+import androidx.work.WorkInfo
+import androidx.work.WorkManager
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.launch
+
+/** foss flavor: the engine is downloaded from the pinned release by [OfficeEngineDownloadWorker]. */
+internal object OfficeEngineFlavor {
+ fun createInstaller(context: Context): OfficeEngineInstaller = DownloadOfficeEngineInstaller(context)
+}
+
+private class DownloadOfficeEngineInstaller(private val context: Context) : OfficeEngineInstaller {
+
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private val workManager = WorkManager.getInstance(context)
+ private val _state = MutableStateFlow(OfficeEngine.installedState(context))
+ override val state: StateFlow<OfficeEngineState> = _state.asStateFlow()
+ override val usesNotification: Boolean = true
+
+ /** Only surface a FAILED work result for installs started in this process's lifetime. */
+ @Volatile private var startedHere = false
+
+ init {
+ scope.launch {
+ workManager.getWorkInfosForUniqueWorkFlow(OfficeEngineDownloadWorker.UNIQUE_NAME).collect { infos ->
+ _state.value = map(infos.firstOrNull())
+ }
+ }
+ }
+
+ private fun map(info: WorkInfo?): OfficeEngineState {
+ if (!OfficeEngine.isSupported()) return OfficeEngineState.Unsupported
+ return when (info?.state) {
+ WorkInfo.State.ENQUEUED, WorkInfo.State.BLOCKED ->
+ OfficeEngineState.Downloading(0, OfficeEngineManifest.APPROX_DOWNLOAD_BYTES, waitingForNetwork = true)
+ WorkInfo.State.RUNNING -> {
+ val p = info.progress
+ if (p.getString(OfficeEngineDownloadWorker.KEY_PHASE) == OfficeEngineDownloadWorker.PHASE_INSTALL) {
+ OfficeEngineState.Installing
+ } else {
+ OfficeEngineState.Downloading(
+ p.getLong(OfficeEngineDownloadWorker.KEY_DONE, 0),
+ p.getLong(OfficeEngineDownloadWorker.KEY_TOTAL, OfficeEngineManifest.APPROX_DOWNLOAD_BYTES)
+ )
+ }
+ }
+ WorkInfo.State.FAILED -> if (startedHere) {
+ OfficeEngineState.Failed(
+ info.outputData.getString(OfficeEngineDownloadWorker.KEY_ERROR) ?: "Download failed"
+ )
+ } else {
+ OfficeEngine.installedState(context)
+ }
+ else -> OfficeEngine.installedState(context)
+ }
+ }
+
+ override fun install() {
+ if (!OfficeEngine.isSupported()) return
+ startedHere = true
+ val request = OneTimeWorkRequestBuilder<OfficeEngineDownloadWorker>()
+ .setConstraints(
+ Constraints.Builder()
+ .setRequiredNetworkType(NetworkType.CONNECTED)
+ .setRequiresStorageNotLow(true)
+ .build()
+ )
+ .build()
+ workManager.enqueueUniqueWork(OfficeEngineDownloadWorker.UNIQUE_NAME, ExistingWorkPolicy.KEEP, request)
+ }
+
+ override fun cancel() {
+ workManager.cancelUniqueWork(OfficeEngineDownloadWorker.UNIQUE_NAME)
+ }
+
+ override fun uninstall() {
+ workManager.cancelUniqueWork(OfficeEngineDownloadWorker.UNIQUE_NAME)
+ scope.launch {
+ OfficeEngine.removeInstalledEngine(context)
+ workManager.pruneWork()
+ _state.value = OfficeEngine.installedState(context)
+ }
+ }
+
+ override fun refresh() {
+ scope.launch {
+ val info = workManager.getWorkInfosForUniqueWork(OfficeEngineDownloadWorker.UNIQUE_NAME).get().firstOrNull()
+ _state.value = map(info)
+ }
+ }
+}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 029aede..5e26c0e 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -4,8 +4,9 @@
<!-- Camera permission for document scanning -->
<uses-permission android:name="android.permission.CAMERA" />
- <!-- Network access was used ONLY by the Web-to-PDF tool. That tool is disabled for this
- privacy-focused (fully offline) release, so no network permissions are declared.
+ <!-- No network permissions here: the play flavor is fully offline (the optional Office engine
+ arrives through Play Feature Delivery). Only the foss flavor adds INTERNET, solely to
+ download that engine on request - see src/foss/AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> -->
<!-- Legacy read access for older providers on Android 12L and below. -->
@@ -145,6 +146,22 @@
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
+
+ <!-- Optional Office engine (powered by LibreOffice), isolated in its own process so a
+ native crash or runaway document can never take down the app. -->
+ <service
+ android:name=".office.OfficeEngineService"
+ android:exported="false"
+ android:process=":office" />
+
+ <!-- WebViews only ever render local content; opt out of Safe Browsing lookups and
+ WebView usage metrics so nothing is sent even in builds that hold INTERNET. -->
+ <meta-data
+ android:name="android.webkit.WebView.EnableSafeBrowsing"
+ android:value="false" />
+ <meta-data
+ android:name="android.webkit.WebView.MetricsOptOut"
+ android:value="true" />
</application>
</manifest>
diff --git a/app/src/main/java/com/chethan616/clearpdf/office/EngineArchiveLayout.kt b/app/src/main/java/com/chethan616/clearpdf/office/EngineArchiveLayout.kt
new file mode 100644
index 0000000..e4eecc3
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/office/EngineArchiveLayout.kt
@@ -0,0 +1,106 @@
+package com.chethan616.clearpdf.office
+
+import java.io.File
+import java.io.IOException
+import java.io.InputStream
+import java.io.OutputStream
+
+/**
+ * Where each entry of an engine bundle lands inside an engine directory. Both installers use it:
+ *
+ * `<abi>/lib*.so` -> `lib/` (LO_LIB_DIR = $APP_DATA_DIR/lib)
+ * `program/…`, `share/…` -> same path (bootstrap rc files, registry, UI configs)
+ * `unpack/…` -> engine root (etc/fonts, user/fonts, program/sofficerc, types)
+ *
+ * Any other ABI directory or unknown entry is ignored. Every destination is checked to stay
+ * inside the engine directory (zip-slip).
+ */
+internal object EngineArchiveLayout {
+
+ fun destinationFor(root: File, abi: String, entryName: String): File? {
+ val rel = entryName.replace('\\', '/').trimStart('.', '/')
+ if (rel.isEmpty() || rel.endsWith("/")) return null
+ val mapped = when {
+ rel.startsWith("$abi/") -> "lib/" + rel.removePrefix("$abi/")
+ rel.startsWith("program/") || rel.startsWith("share/") -> rel
+ rel.startsWith("unpack/") -> rel.removePrefix("unpack/")
+ else -> return null
+ }
+ val target = File(root, mapped)
+ val rootPath = root.canonicalPath + File.separator
+ if (!target.canonicalPath.startsWith(rootPath)) throw IOException("Unsafe archive entry: $entryName")
+ return target
+ }
+
+ /**
+ * Streams a (decompressed) ustar/GNU tar archive into [root]. Supports regular files and GNU
+ * long names, which is all the engine bundles use. Returns the number of files written.
+ */
+ fun extractTar(input: InputStream, root: File, abi: String, isCancelled: () -> Boolean = { false }): Int {
+ val header = ByteArray(512)
+ var longName: String? = null
+ var files = 0
+ while (readFully(input, header) && header.any { it.toInt() != 0 }) {
+ if (isCancelled()) throw java.util.concurrent.CancellationException()
+ val name = longName ?: cString(header, 0, 100)
+ longName = null
+ val size = cString(header, 124, 12).trim().ifEmpty { "0" }.toLong(8)
+ val type = header[156].toInt().toChar()
+ val padded = (size + 511) / 512 * 512
+ if (type == 'L') {
+ val bytes = ByteArray(size.toInt())
+ if (!readFully(input, bytes)) throw IOException("Truncated archive")
+ skip(input, padded - size)
+ longName = String(bytes, Charsets.UTF_8).trimEnd('\u0000')
+ continue
+ }
+ val target = if (type == '0' || type == '\u0000') destinationFor(root, abi, name) else null
+ if (target == null) {
+ skip(input, padded)
+ continue
+ }
+ target.parentFile?.mkdirs()
+ target.outputStream().use { copyExactly(input, it, size) }
+ skip(input, padded - size)
+ files++
+ }
+ return files
+ }
+
+ private fun cString(b: ByteArray, off: Int, len: Int): String {
+ var end = off
+ while (end < off + len && b[end].toInt() != 0) end++
+ return String(b, off, end - off, Charsets.UTF_8)
+ }
+
+ private fun readFully(input: InputStream, buf: ByteArray): Boolean {
+ var read = 0
+ while (read < buf.size) {
+ val n = input.read(buf, read, buf.size - read)
+ if (n < 0) return false
+ read += n
+ }
+ return true
+ }
+
+ private fun copyExactly(input: InputStream, out: OutputStream, size: Long) {
+ val buf = ByteArray(1 shl 16)
+ var left = size
+ while (left > 0) {
+ val n = input.read(buf, 0, minOf(buf.size.toLong(), left).toInt())
+ if (n < 0) throw IOException("Truncated archive")
+ out.write(buf, 0, n)
+ left -= n
+ }
+ }
+
+ private fun skip(input: InputStream, count: Long) {
+ var left = count
+ val buf = ByteArray(8192)
+ while (left > 0) {
+ val n = input.read(buf, 0, minOf(buf.size.toLong(), left).toInt())
+ if (n < 0) throw IOException("Truncated archive")
+ left -= n
+ }
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngine.kt b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngine.kt
new file mode 100644
index 0000000..0a97c43
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngine.kt
@@ -0,0 +1,83 @@
+package com.chethan616.clearpdf.office
+
+import android.content.Context
+import android.net.Uri
+import java.io.File
+
+/**
+ * Entry point for the optional Office engine (powered by LibreOffice): preferences, the
+ * per-flavor installer, and the conversion hook used by UniversalDocumentConverter.
+ */
+object OfficeEngine {
+
+ private const val PREFS = "office_engine"
+ private const val KEY_USE_FOR_OFFICE = "use_for_office_files"
+ private const val KEY_HINT_DISMISSED = "hint_dismissed"
+
+ /** Formats LibreOffice converts better than the built-in renderers. */
+ private val OFFICE_EXTENSIONS = setOf(
+ "doc", "docx", "docm", "dot", "dotx", "odt", "ott", "rtf",
+ "xls", "xlsx", "xlsm", "ods", "ots",
+ "ppt", "pptx", "pptm", "pps", "ppsx", "odp", "otp", "odg"
+ )
+
+ @Volatile
+ private var installerInstance: OfficeEngineInstaller? = null
+
+ fun installer(context: Context): OfficeEngineInstaller =
+ installerInstance ?: synchronized(this) {
+ installerInstance ?: OfficeEngineFlavor.createInstaller(context.applicationContext).also { installerInstance = it }
+ }
+
+ fun isSupported(): Boolean = OfficeEngineManifest.bundleForDevice() != null
+
+ fun isOfficeFile(fileName: String): Boolean =
+ fileName.substringAfterLast('.', "").lowercase() in OFFICE_EXTENSIONS
+
+ private fun prefs(context: Context) = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
+
+ fun useForOfficeFiles(context: Context): Boolean = prefs(context).getBoolean(KEY_USE_FOR_OFFICE, true)
+
+ fun setUseForOfficeFiles(context: Context, enabled: Boolean) {
+ prefs(context).edit().putBoolean(KEY_USE_FOR_OFFICE, enabled).apply()
+ }
+
+ fun isActive(context: Context): Boolean = useForOfficeFiles(context) && OfficeEngineStore.isInstalled(context)
+
+ /**
+ * Converts through the engine when it is installed and enabled; null means "use the built-in
+ * renderers" (engine absent, disabled, or it failed — failures are silent by design).
+ */
+ fun tryConvert(context: Context, source: Uri, fileName: String): File? {
+ if (!isOfficeFile(fileName) || !isActive(context)) return null
+ return OfficeEngineClient.convertBlocking(context, source, fileName).pdf
+ }
+
+ /** Whether to show the one-time "Improve fidelity with the Office engine" hint. */
+ fun shouldOfferHint(context: Context, fileName: String): Boolean =
+ isOfficeFile(fileName) && isSupported() && !OfficeEngineStore.isInstalled(context) &&
+ !prefs(context).getBoolean(KEY_HINT_DISMISSED, false)
+
+ fun dismissHint(context: Context) {
+ prefs(context).edit().putBoolean(KEY_HINT_DISMISSED, true).apply()
+ }
+
+ /** Uninstall helper shared by both installers: stop the engine process, then drop files. */
+ internal fun removeInstalledEngine(context: Context) {
+ OfficeEngineClient.stopEngineProcess(context)
+ OfficeEngineStore.delete(context)
+ OfficeEngineClient.clearCache(context)
+ }
+
+ internal fun installedState(context: Context): OfficeEngineState {
+ if (!isSupported()) return OfficeEngineState.Unsupported
+ OfficeEngineStore.installedDir(context) ?: return OfficeEngineState.NotInstalled
+ val installed = OfficeEngineStore.installedVersion(context)
+ val current = installed == OfficeEngineManifest.VERSION
+ return OfficeEngineState.Installed(
+ version = if (current) OfficeEngineManifest.DISPLAY_VERSION else installed.orEmpty().substringAfterLast('-'),
+ sizeBytes = OfficeEngineStore.sizeOnDisk(context),
+ updateAvailable = !current
+ )
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineClient.kt b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineClient.kt
new file mode 100644
index 0000000..ab98f30
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineClient.kt
@@ -0,0 +1,209 @@
+package com.chethan616.clearpdf.office
+
+import android.app.ActivityManager
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.content.ServiceConnection
+import android.net.Uri
+import android.os.Bundle
+import android.os.Handler
+import android.os.IBinder
+import android.os.Looper
+import android.os.Message
+import android.os.Messenger
+import android.os.Process
+import android.util.Log
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.runInterruptible
+import java.io.File
+import java.security.MessageDigest
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
+import java.util.concurrent.atomic.AtomicReference
+
+/**
+ * Main-process side of the Office engine: converts a document to PDF through
+ * [OfficeEngineService] in `:office`, with a timeout, cancellation and a result cache.
+ *
+ * Every failure (engine missing, timeout, native crash, unreadable file, wrong password) returns a
+ * [Result] without a file — callers fall back to the built-in renderers. Conversions are
+ * serialised: LibreOfficeKit handles one document at a time.
+ */
+object OfficeEngineClient {
+
+ private const val TAG = "OfficeEngineClient"
+ const val DEFAULT_TIMEOUT_MS = 90_000L
+ private const val BIND_TIMEOUT_MS = 10_000L
+ private const val CACHE_LIMIT_BYTES = 150L * 1024 * 1024
+
+ data class Result(val pdf: File?, val error: String? = null, val needsPassword: Boolean = false)
+
+ private val lock = Any()
+
+ /** Coroutine-friendly: cancelling the caller interrupts the wait and kills `:office`. */
+ suspend fun convert(
+ context: Context,
+ source: Uri,
+ fileName: String,
+ password: String? = null,
+ timeoutMs: Long = DEFAULT_TIMEOUT_MS
+ ): Result = runInterruptible(Dispatchers.IO) { convertBlocking(context, source, fileName, password, timeoutMs) }
+
+ /**
+ * Blocking conversion; call from a background thread. [fileName] supplies the extension that
+ * LibreOffice uses for format detection. Thread interruption cancels the conversion.
+ */
+ fun convertBlocking(
+ context: Context,
+ source: Uri,
+ fileName: String,
+ password: String? = null,
+ timeoutMs: Long = DEFAULT_TIMEOUT_MS
+ ): Result {
+ if (Looper.myLooper() == Looper.getMainLooper()) return Result(null, "Called on the main thread")
+ val app = context.applicationContext
+ if (!OfficeEngineStore.isInstalled(app)) return Result(null, "Office engine is not installed")
+ val ext = fileName.substringAfterLast('.', "").lowercase().filter { it.isLetterOrDigit() }.take(8)
+ if (ext.isEmpty()) return Result(null, "Unknown file type")
+
+ val inDir = File(app.cacheDir, "office-in").apply { mkdirs() }
+ val cacheDir = File(app.cacheDir, "office-pdf").apply { mkdirs() }
+ val input = File(inDir, "in-${System.nanoTime()}.$ext")
+ try {
+ val digest = MessageDigest.getInstance("SHA-256")
+ app.contentResolver.openInputStream(source)?.use { stream ->
+ input.outputStream().use { out ->
+ val buf = ByteArray(1 shl 16)
+ while (true) {
+ val n = stream.read(buf)
+ if (n < 0) break
+ digest.update(buf, 0, n)
+ out.write(buf, 0, n)
+ }
+ }
+ } ?: return Result(null, "Cannot open file")
+ digest.update("$ext|${OfficeEngineStore.installedVersion(app)}".toByteArray())
+ val key = digest.digest().joinToString("") { "%02x".format(it) }.take(40)
+ // Password-protected output is never cached: the PDF is unencrypted.
+ val cached = File(cacheDir, "$key.pdf")
+ if (password == null && cached.isFile && cached.length() > 0) {
+ cached.setLastModified(System.currentTimeMillis())
+ return Result(cached)
+ }
+ val output = if (password == null) cached else File(cacheDir, "pw-${System.nanoTime()}.pdf")
+ val partial = File(cacheDir, "${output.name}.part")
+ val result = synchronized(lock) { runInService(app, input, partial, password, timeoutMs) }
+ if (result.pdf == null) {
+ partial.delete()
+ return result
+ }
+ if (!partial.renameTo(output)) return Result(null, "Cannot store converted PDF")
+ trimCache(cacheDir)
+ return Result(output)
+ } catch (e: InterruptedException) {
+ Thread.currentThread().interrupt()
+ return Result(null, "Cancelled")
+ } catch (t: Throwable) {
+ Log.w(TAG, "Office engine conversion failed", t)
+ return Result(null, t.message)
+ } finally {
+ input.delete()
+ }
+ }
+
+ private fun runInService(app: Context, input: File, output: File, password: String?, timeoutMs: Long): Result {
+ val connected = CountDownLatch(1)
+ val done = CountDownLatch(1)
+ val service = AtomicReference<Messenger?>()
+ val reply = AtomicReference<Bundle?>()
+
+ val connection = object : ServiceConnection {
+ override fun onServiceConnected(name: ComponentName, binder: IBinder) {
+ service.set(Messenger(binder))
+ connected.countDown()
+ }
+
+ // `:office` died (native crash, OOM, idle kill mid-job): fail fast.
+ override fun onServiceDisconnected(name: ComponentName) {
+ connected.countDown()
+ done.countDown()
+ }
+
+ override fun onBindingDied(name: ComponentName) {
+ connected.countDown()
+ done.countDown()
+ }
+ }
+ val replyTo = Messenger(Handler(Looper.getMainLooper()) { msg ->
+ if (msg.what == OfficeEngineService.MSG_RESULT) {
+ reply.set(msg.data)
+ done.countDown()
+ }
+ true
+ })
+
+ val intent = Intent(app, OfficeEngineService::class.java)
+ if (!app.bindService(intent, connection, Context.BIND_AUTO_CREATE)) {
+ return Result(null, "Office engine service unavailable")
+ }
+ var killProcess = false
+ try {
+ if (!connected.await(BIND_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
+ killProcess = true
+ return Result(null, "Office engine did not start")
+ }
+ val messenger = service.get() ?: return Result(null, "Office engine stopped")
+ messenger.send(Message.obtain(null, OfficeEngineService.MSG_CONVERT).apply {
+ data = Bundle().apply {
+ putString(OfficeEngineService.KEY_INPUT, input.absolutePath)
+ putString(OfficeEngineService.KEY_OUTPUT, output.absolutePath)
+ password?.let { putString(OfficeEngineService.KEY_PASSWORD, it) }
+ }
+ this.replyTo = replyTo
+ })
+ if (!done.await(timeoutMs, TimeUnit.MILLISECONDS)) {
+ killProcess = true
+ return Result(null, "Office engine timed out")
+ }
+ val data = reply.get() ?: return Result(null, "Office engine stopped unexpectedly")
+ return if (data.getBoolean(OfficeEngineService.KEY_OK)) {
+ Result(output)
+ } else {
+ Result(
+ null,
+ data.getString(OfficeEngineService.KEY_ERROR),
+ data.getBoolean(OfficeEngineService.KEY_NEEDS_PASSWORD)
+ )
+ }
+ } catch (e: InterruptedException) {
+ killProcess = true
+ throw e
+ } finally {
+ runCatching { app.unbindService(connection) }
+ if (killProcess) stopEngineProcess(app)
+ }
+ }
+
+ /** Kills `:office` (cancel/timeout/uninstall). Safe to call when it is not running. */
+ fun stopEngineProcess(context: Context) {
+ val app = context.applicationContext
+ val am = app.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager ?: return
+ val name = "${app.packageName}:office"
+ am.runningAppProcesses?.filter { it.processName == name }?.forEach { Process.killProcess(it.pid) }
+ }
+
+ fun clearCache(context: Context) {
+ File(context.applicationContext.cacheDir, "office-pdf").deleteRecursively()
+ }
+
+ private fun trimCache(dir: File) {
+ val files = dir.listFiles { f -> f.isFile && f.name.endsWith(".pdf") }?.sortedByDescending { it.lastModified() } ?: return
+ var total = 0L
+ files.forEachIndexed { index, file ->
+ total += file.length()
+ // Always keep the newest file: it is the one being opened right now.
+ if (index > 0 && total > CACHE_LIMIT_BYTES) file.delete()
+ }
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineInstaller.kt b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineInstaller.kt
new file mode 100644
index 0000000..791d86e
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineInstaller.kt
@@ -0,0 +1,51 @@
+package com.chethan616.clearpdf.office
+
+import android.app.Activity
+import kotlinx.coroutines.flow.StateFlow
+
+/** What the Settings "Office engine" section shows. */
+sealed interface OfficeEngineState {
+ /** No bundle for this device's ABI (e.g. x86) — the section is hidden. */
+ data object Unsupported : OfficeEngineState
+
+ data object NotInstalled : OfficeEngineState
+
+ /** [total] <= 0 means the size is not known yet (indeterminate progress). */
+ data class Downloading(val downloaded: Long, val total: Long, val waitingForNetwork: Boolean = false) : OfficeEngineState
+
+ /** Verifying and unpacking. */
+ data object Installing : OfficeEngineState
+
+ /** Play asks the user to approve a large download ([OfficeEngineInstaller.confirm]). */
+ data object NeedsConfirmation : OfficeEngineState
+
+ data class Installed(val version: String, val sizeBytes: Long, val updateAvailable: Boolean) : OfficeEngineState
+
+ data class Failed(val message: String) : OfficeEngineState
+}
+
+/**
+ * Gets the engine onto the device. One implementation per distribution flavor, created by
+ * `OfficeEngineFlavor.createInstaller` (src/play, src/foss); both finish through
+ * [OfficeEngineStore.commit] so the runtime side is identical.
+ */
+interface OfficeEngineInstaller {
+ val state: StateFlow<OfficeEngineState>
+
+ /** Whether starting an install should first ask for POST_NOTIFICATIONS (progress notification). */
+ val usesNotification: Boolean
+
+ /** Starts (or resumes) installing or updating. */
+ fun install()
+
+ fun cancel()
+
+ /** Removes the engine and frees its storage. */
+ fun uninstall()
+
+ /** Re-reads on-disk state (e.g. when Settings opens). */
+ fun refresh()
+
+ /** Answers [OfficeEngineState.NeedsConfirmation]; no-op where not applicable. */
+ fun confirm(activity: Activity) {}
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineManifest.kt b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineManifest.kt
new file mode 100644
index 0000000..371819b
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineManifest.kt
@@ -0,0 +1,66 @@
+package com.chethan616.clearpdf.office
+
+import android.os.Build
+import android.os.Process
+
+/**
+ * Pinned description of the optional Office engine (powered by LibreOffice).
+ *
+ * The engine is a prebuilt LibreOfficeKit bundle for Android (liblo-native-code.so + the
+ * LibreOffice runtime tree). Nothing about it is trusted at runtime except what is pinned here:
+ * the foss download is accepted only if its size and SHA-256 match, and the Play module is built
+ * from the same pinned archives (office_engine/build.gradle.kts — keep both in sync).
+ *
+ * Source: https://github.com/vasuki-re/LibreOffice-Lite release v2.0, a LibreOffice core build
+ * (MPL-2.0; see THIRD_PARTY_NOTICES.md). Values verified against the GitHub release API digests
+ * and by hashing the downloaded arm64 archive.
+ */
+object OfficeEngineManifest {
+
+ /** Bumping this makes installed engines report "update available". */
+ const val VERSION = "lo-lite-2.0"
+ const val DISPLAY_VERSION = "2.0"
+
+ /** Rough install footprint, for the "Not installed" row. */
+ const val APPROX_DOWNLOAD_BYTES = 47_521_152L
+
+ data class Bundle(val abi: String, val url: String, val sizeBytes: Long, val sha256: String)
+
+ val bundles: List<Bundle> = listOf(
+ Bundle(
+ abi = "arm64-v8a",
+ url = "https://github.com/vasuki-re/LibreOffice-Lite/releases/download/v2.0/LibreOffice-arm64.tar.xz",
+ sizeBytes = 47_521_152L,
+ sha256 = "6665ad47db41d116248c40e6fc608a3425b9eb4a304f5ad5e5d5c80dbea61e30"
+ ),
+ Bundle(
+ abi = "armeabi-v7a",
+ url = "https://github.com/vasuki-re/LibreOffice-Lite/releases/download/v2.0/LibreOffice-arm.tar.xz",
+ sizeBytes = 46_666_612L,
+ sha256 = "7546e244f66c8c1b5a5a4ede7cb26c8f7e767879bbf3b39d405a5d8fa148b045"
+ )
+ )
+
+ /**
+ * This particular build hard-codes its original host app's data directory in a few bootstrap
+ * paths (e.g. `file:///data/data/vasuki.istanpdf/files/program/unorc`), which ClearPDF cannot
+ * access. Those bytes are rewritten, at install time, to an equal-length alias that the
+ * `:office` process points at the engine directory — see [OfficeEngineRelocation].
+ * Set to null for a bundle built without hard-coded paths.
+ */
+ const val RELOCATE_FROM: String = "/data/data/vasuki.istanpdf/files"
+
+ /**
+ * The ABI the engine must match: the ABI this *process* runs as. An x86 device that also lists
+ * ARM ABIs (via translation) cannot load ARM libraries into an x86 process, so only the
+ * process's own primary ABI counts.
+ */
+ fun processAbi(): String? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Process.is64Bit()) {
+ Build.SUPPORTED_64_BIT_ABIS.firstOrNull()
+ } else {
+ Build.SUPPORTED_32_BIT_ABIS.firstOrNull()
+ }
+
+ /** The bundle for this device, or null when the engine is unsupported here (e.g. x86). */
+ fun bundleForDevice(): Bundle? = processAbi()?.let { abi -> bundles.firstOrNull { it.abi == abi } }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineRelocation.kt b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineRelocation.kt
new file mode 100644
index 0000000..b78d337
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineRelocation.kt
@@ -0,0 +1,105 @@
+package com.chethan616.clearpdf.office
+
+import android.system.Os
+import android.system.OsConstants
+import java.io.File
+import java.io.RandomAccessFile
+
+/**
+ * Makes a prebuilt engine that hard-codes another app's data directory usable from ClearPDF.
+ *
+ * LibreOffice's Android bootstrap bakes a few absolute paths into the library as string literals
+ * whose lengths are compile-time constants, so they can only be replaced by a path of exactly
+ * the same length. The replacement is `/proc/self/fd/<ALIAS_FD>/./././…`: a procfs link to a
+ * directory descriptor that the `:office` process opens on the engine directory and pins to
+ * [ALIAS_FD] before LibreOffice starts ([pinAlias]). Path walks through that link land in the
+ * engine directory, so the patched literals resolve to our own files.
+ *
+ * Install time: [patchLibraries]. Load time (in `:office` only): [pinAlias].
+ */
+internal object OfficeEngineRelocation {
+
+ /** High, fixed descriptor number; the literal is patched with it, so it cannot vary. */
+ private const val ALIAS_FD = 1023
+
+ fun aliasFor(needle: String): String {
+ val base = "/proc/self/fd/$ALIAS_FD"
+ val pad = needle.length - base.length
+ require(pad >= 0 && pad % 2 == 0) { "Cannot build an alias of length ${needle.length}" }
+ return base + "/.".repeat(pad / 2)
+ }
+
+ /** Rewrites every occurrence of [needle] in the .so files under [libDir]; returns the count. */
+ fun patchLibraries(libDir: File, needle: String): Int {
+ val from = needle.toByteArray(Charsets.US_ASCII)
+ val to = aliasFor(needle).toByteArray(Charsets.US_ASCII)
+ check(from.size == to.size)
+ var total = 0
+ libDir.listFiles { f -> f.isFile && f.name.endsWith(".so") }?.forEach { lib ->
+ total += patchFile(lib, from, to)
+ }
+ return total
+ }
+
+ private fun patchFile(file: File, from: ByteArray, to: ByteArray): Int {
+ val offsets = ArrayList<Long>()
+ val chunk = 1 shl 20
+ val overlap = from.size - 1
+ RandomAccessFile(file, "rw").use { raf ->
+ val buf = ByteArray(chunk + overlap)
+ var filePos = 0L
+ var carried = 0
+ while (true) {
+ val n = raf.read(buf, carried, chunk)
+ if (n <= 0) break
+ val valid = carried + n
+ var i = 0
+ val limit = valid - from.size
+ while (i <= limit) {
+ if (buf[i] == from[0] && matches(buf, i, from)) {
+ offsets += filePos - carried + i
+ i += from.size
+ } else {
+ i++
+ }
+ }
+ // Keep the tail so matches spanning chunk boundaries are found.
+ val keep = minOf(overlap, valid)
+ System.arraycopy(buf, valid - keep, buf, 0, keep)
+ filePos += n
+ carried = keep
+ }
+ // A match inside the carried tail could be found twice; offsets are de-duplicated.
+ val unique = offsets.distinct()
+ for (offset in unique) {
+ raf.seek(offset)
+ raf.write(to)
+ }
+ return unique.size
+ }
+ }
+
+ private fun matches(buf: ByteArray, at: Int, needle: ByteArray): Boolean {
+ for (k in needle.indices) if (buf[at + k] != needle[k]) return false
+ return true
+ }
+
+ /**
+ * Points [ALIAS_FD] at [engineDir] for the lifetime of this process. Must run in `:office`
+ * before LibreOfficeKit initialises. Throws if the descriptor is taken by something else.
+ */
+ fun pinAlias(engineDir: File) {
+ val link = File("/proc/self/fd/$ALIAS_FD")
+ val existing = runCatching { Os.readlink(link.path) }.getOrNull()
+ if (existing != null) {
+ check(File(existing).canonicalPath == engineDir.canonicalPath) {
+ "Descriptor $ALIAS_FD is already in use"
+ }
+ return
+ }
+ val fd = Os.open(engineDir.path, OsConstants.O_RDONLY, 0)
+ // dup2 duplicates onto ALIAS_FD; the original descriptor stays open too, deliberately
+ // never closed, as both live exactly as long as the process.
+ Os.dup2(fd, ALIAS_FD)
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineRuntime.kt b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineRuntime.kt
new file mode 100644
index 0000000..3ddaf1f
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineRuntime.kt
@@ -0,0 +1,83 @@
+package com.chethan616.clearpdf.office
+
+import android.content.Context
+import android.net.Uri
+import org.libreoffice.kit.LibreOfficeKit
+import org.libreoffice.kit.Office
+import java.io.File
+
+/**
+ * LibreOfficeKit inside the `:office` process. Never touch this from the main process: a native
+ * crash or runaway allocation here must only take down `:office` (see [OfficeEngineService]).
+ *
+ * LibreOfficeKit is a process-wide singleton that cannot be re-initialised, so this object is
+ * too; all calls are made from the service's single worker thread.
+ */
+internal object OfficeEngineRuntime {
+
+ private var office: Office? = null
+
+ class ConversionException(message: String, val needsPassword: Boolean = false) : Exception(message)
+
+ private fun ensureStarted(context: Context): Office {
+ office?.let { return it }
+ val app = context.applicationContext
+ val engineDir = OfficeEngineStore.installedDir(app)
+ ?: throw ConversionException("Office engine is not installed")
+ val lib = File(engineDir, "lib")
+
+ OfficeEngineRelocation.pinAlias(engineDir)
+ // Order matters: the STL first, then the engine that links against it.
+ System.load(File(lib, "libc++_shared.so").absolutePath)
+ System.load(File(lib, "liblo-native-code.so").absolutePath)
+
+ val tmp = File(app.cacheDir, "office-tmp").apply { mkdirs() }
+ LibreOfficeKit.putenv("SAL_LOG=-WARN-INFO")
+ LibreOfficeKit.putenv("SAL_LOK_OPTIONS=compact_fonts")
+ LibreOfficeKit.putenv("TMPDIR=${tmp.absolutePath}")
+ LibreOfficeKit.redirectStdio(true)
+ val ok = LibreOfficeKit.initializeNative(
+ engineDir.absolutePath,
+ tmp.absolutePath,
+ app.packageResourcePath,
+ app.assets
+ )
+ if (!ok) throw ConversionException("Office engine failed to initialise")
+ val handle = LibreOfficeKit.getLibreOfficeKitHandle()
+ ?: throw ConversionException("Office engine failed to initialise")
+ return Office(handle).also { office = it }
+ }
+
+ /** Converts [input] to PDF at [output]. The input's extension drives format detection. */
+ fun convertToPdf(context: Context, input: File, output: File, password: String?) {
+ val office = ensureStarted(context)
+ val inputUrl = Uri.fromFile(input).toString()
+ var passwordRequests = 0
+ office.callback = { type, _ ->
+ if (type == Office.LOK_CALLBACK_DOCUMENT_PASSWORD) {
+ passwordRequests++
+ // Offer the password once; a second request means it was wrong, so abort.
+ office.setDocumentPassword(inputUrl, if (passwordRequests == 1) password else null)
+ }
+ }
+ // Always ask for password callbacks: answering null aborts the load cleanly and tells us
+ // the file is protected (instead of LibreOffice failing with a generic error).
+ office.setOptionalFeatures(Office.FEATURE_DOCUMENT_PASSWORD)
+ try {
+ val document = office.documentLoad(inputUrl)
+ ?: throw ConversionException(
+ office.getError()?.takeIf { it.isNotBlank() } ?: "The Office engine could not open this file",
+ needsPassword = passwordRequests > 0
+ )
+ try {
+ output.delete()
+ document.saveAs(Uri.fromFile(output).toString(), "pdf", null)
+ } finally {
+ document.destroy()
+ }
+ } finally {
+ office.callback = null
+ }
+ if (!output.isFile || output.length() == 0L) throw ConversionException("The Office engine produced no PDF")
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineService.kt b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineService.kt
new file mode 100644
index 0000000..30e79be
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineService.kt
@@ -0,0 +1,88 @@
+package com.chethan616.clearpdf.office
+
+import android.app.Service
+import android.content.Intent
+import android.os.Bundle
+import android.os.Handler
+import android.os.HandlerThread
+import android.os.IBinder
+import android.os.Looper
+import android.os.Message
+import android.os.Messenger
+import android.os.Process
+import android.os.RemoteException
+import java.io.File
+
+/**
+ * Hosts LibreOfficeKit in the isolated `:office` process (android:process=":office").
+ *
+ * Why a separate process: the engine is ~190 MB of native code that can crash, leak or spin on a
+ * hostile document. Here it can only take down `:office`; the client sees the binder die and
+ * falls back to the built-in renderers. Memory is reclaimed by killing the whole process once it
+ * has been idle for [IDLE_KILL_MS] — LibreOfficeKit cannot be torn down and re-initialised.
+ *
+ * Protocol (Messenger): [MSG_CONVERT] with [KEY_INPUT], [KEY_OUTPUT], optional [KEY_PASSWORD];
+ * reply [MSG_RESULT] with [KEY_OK], [KEY_ERROR], [KEY_NEEDS_PASSWORD]. Paths live in the app's
+ * own cache directory, shared by both processes of this uid.
+ */
+class OfficeEngineService : Service() {
+
+ companion object {
+ const val MSG_CONVERT = 1
+ const val MSG_RESULT = 2
+ const val KEY_INPUT = "input"
+ const val KEY_OUTPUT = "output"
+ const val KEY_PASSWORD = "password"
+ const val KEY_OK = "ok"
+ const val KEY_ERROR = "error"
+ const val KEY_NEEDS_PASSWORD = "needsPassword"
+ private const val IDLE_KILL_MS = 60_000L
+
+ private val mainHandler = Handler(Looper.getMainLooper())
+ private val idleKill = Runnable { Process.killProcess(Process.myPid()) }
+ }
+
+ private lateinit var worker: HandlerThread
+ private lateinit var messenger: Messenger
+
+ override fun onCreate() {
+ super.onCreate()
+ mainHandler.removeCallbacks(idleKill)
+ worker = HandlerThread("office-engine").apply { start() }
+ messenger = Messenger(Handler(worker.looper) { msg -> handle(msg); true })
+ }
+
+ override fun onBind(intent: Intent?): IBinder = messenger.binder
+
+ private fun handle(msg: Message) {
+ if (msg.what != MSG_CONVERT) return
+ mainHandler.removeCallbacks(idleKill)
+ val data = msg.data
+ val reply = Bundle()
+ try {
+ val input = File(requireNotNull(data.getString(KEY_INPUT)))
+ val output = File(requireNotNull(data.getString(KEY_OUTPUT)))
+ OfficeEngineRuntime.convertToPdf(this, input, output, data.getString(KEY_PASSWORD))
+ reply.putBoolean(KEY_OK, true)
+ } catch (e: OfficeEngineRuntime.ConversionException) {
+ reply.putString(KEY_ERROR, e.message)
+ reply.putBoolean(KEY_NEEDS_PASSWORD, e.needsPassword)
+ } catch (t: Throwable) {
+ reply.putString(KEY_ERROR, t.message ?: t.javaClass.simpleName)
+ }
+ try {
+ msg.replyTo?.send(Message.obtain(null, MSG_RESULT).apply { this.data = reply })
+ } catch (_: RemoteException) {
+ // Client gave up (timeout/cancel); nothing to do.
+ }
+ mainHandler.postDelayed(idleKill, IDLE_KILL_MS)
+ }
+
+ override fun onDestroy() {
+ // Unbound: keep the warm engine briefly for the next document, then free its memory.
+ mainHandler.removeCallbacks(idleKill)
+ mainHandler.postDelayed(idleKill, IDLE_KILL_MS)
+ worker.quitSafely()
+ super.onDestroy()
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineStore.kt b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineStore.kt
new file mode 100644
index 0000000..f4c7adc
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineStore.kt
@@ -0,0 +1,99 @@
+package com.chethan616.clearpdf.office
+
+import android.content.Context
+import java.io.File
+import java.io.IOException
+
+/**
+ * On-disk home of the Office engine. Layout (under noBackupFilesDir, never backed up):
+ *
+ * office-engine/
+ * current name of the active engine directory
+ * <version>-<abi>/ engine directory = LibreOfficeKit's $APP_DATA_DIR
+ * .ready written last; the directory is valid only if present
+ * lib/ program/ share/ etc/ user/ cache/ (created by LibreOffice)
+ * staging/ an install in progress; renamed into place atomically
+ * download/ resumable download parts (foss)
+ *
+ * Installs never touch the active engine until the new one is complete: [commit] renames the
+ * finished staging directory into place, flips `current`, and only then deletes old versions.
+ */
+object OfficeEngineStore {
+
+ private const val READY = ".ready"
+ private const val CURRENT = "current"
+
+ fun root(context: Context): File = File(context.applicationContext.noBackupFilesDir, "office-engine")
+
+ fun stagingDir(context: Context): File = File(root(context), "staging")
+
+ fun downloadDir(context: Context): File = File(root(context), "download")
+
+ /** The active, complete engine directory, or null when no engine is installed. */
+ fun installedDir(context: Context): File? {
+ val root = root(context)
+ val name = runCatching { File(root, CURRENT).readText().trim() }.getOrNull()
+ ?.takeIf { it.isNotEmpty() && !it.contains('/') } ?: return null
+ val dir = File(root, name)
+ val ok = File(dir, READY).isFile &&
+ File(dir, "lib/liblo-native-code.so").isFile &&
+ File(dir, "lib/libc++_shared.so").isFile &&
+ File(dir, "program/fundamentalrc").isFile
+ return if (ok) dir else null
+ }
+
+ fun isInstalled(context: Context): Boolean = installedDir(context) != null
+
+ /** Engine version of the installed engine (see [OfficeEngineManifest.VERSION]). */
+ fun installedVersion(context: Context): String? =
+ installedDir(context)?.let { runCatching { File(it, READY).readText().trim() }.getOrNull() }
+
+ fun sizeOnDisk(context: Context): Long = root(context).walkBottomUp().filter { it.isFile }.sumOf { it.length() }
+
+ /** Fresh, empty staging directory. */
+ fun resetStaging(context: Context): File {
+ val staging = stagingDir(context)
+ staging.deleteRecursively()
+ if (!staging.mkdirs()) throw IOException("Cannot create $staging")
+ return staging
+ }
+
+ /**
+ * Finalises a fully extracted staging directory as the active engine: relocates hard-coded
+ * paths, validates, marks ready, swaps it in atomically and removes every older version.
+ */
+ @Synchronized
+ fun commit(context: Context, staging: File, abi: String) {
+ val lib = File(staging, "lib")
+ for (required in listOf("liblo-native-code.so", "libc++_shared.so")) {
+ if (!File(lib, required).isFile) throw IOException("Engine bundle is missing $required")
+ }
+ if (!File(staging, "program/fundamentalrc").isFile) throw IOException("Engine bundle is missing its runtime")
+ OfficeEngineRelocation.patchLibraries(lib, OfficeEngineManifest.RELOCATE_FROM)
+ File(staging, READY).writeText(OfficeEngineManifest.VERSION)
+
+ val root = root(context)
+ val name = "${OfficeEngineManifest.VERSION}-$abi"
+ val target = File(root, name)
+ if (target.exists()) {
+ // Reinstalling the same version: move the old copy aside first so `current` never
+ // points at a half-deleted directory.
+ val trash = File(root, "trash-${System.nanoTime()}")
+ if (!target.renameTo(trash)) throw IOException("Cannot replace $target")
+ }
+ if (!staging.renameTo(target)) throw IOException("Cannot activate $target")
+ val tmp = File(root, "$CURRENT.tmp")
+ tmp.writeText(name)
+ if (!tmp.renameTo(File(root, CURRENT))) throw IOException("Cannot switch engine version")
+
+ root.listFiles()?.forEach { f ->
+ if (f.isDirectory && f.name != name && f.name != "download") f.deleteRecursively()
+ }
+ }
+
+ /** Removes every trace of the engine, including partial downloads. */
+ @Synchronized
+ fun delete(context: Context) {
+ root(context).deleteRecursively()
+ }
+}
diff --git a/app/src/main/java/org/libreoffice/kit/Document.kt b/app/src/main/java/org/libreoffice/kit/Document.kt
new file mode 100644
index 0000000..8fe9177
--- /dev/null
+++ b/app/src/main/java/org/libreoffice/kit/Document.kt
@@ -0,0 +1,32 @@
+/*
+ * Binding for a loaded LibreOfficeKit document. Names are a JNI contract — see LibreOfficeKit.kt.
+ * Only the calls ClearPDF needs are declared; JNI resolves natives lazily, so omitting the rest
+ * (tile painting, input events, UNO commands) is harmless. Original ClearPDF code (MIT).
+ */
+package org.libreoffice.kit
+
+import java.nio.ByteBuffer
+
+class Document(
+ /** Read by native code by name ("handle", Ljava/nio/ByteBuffer;). */
+ @JvmField val handle: ByteBuffer
+) {
+ init {
+ bindMessageCallback()
+ }
+
+ private external fun bindMessageCallback()
+
+ external fun destroy()
+
+ external fun getParts(): Int
+
+ external fun getDocumentTypeNative(): Int
+
+ /** Saves to [url] (a file:// URL) in [format] (e.g. "pdf"), with optional filter options. */
+ external fun saveAs(url: String, format: String, options: String?)
+
+ /** Invoked from native code by name ("messageRetrieved", (ILjava/lang/String;)V). */
+ @Suppress("unused", "UNUSED_PARAMETER")
+ private fun messageRetrieved(type: Int, payload: String?) = Unit
+}
diff --git a/app/src/main/java/org/libreoffice/kit/LibreOfficeKit.kt b/app/src/main/java/org/libreoffice/kit/LibreOfficeKit.kt
new file mode 100644
index 0000000..0850b7a
--- /dev/null
+++ b/app/src/main/java/org/libreoffice/kit/LibreOfficeKit.kt
@@ -0,0 +1,31 @@
+/*
+ * Kotlin binding for the LibreOfficeKit JNI layer (liblo-native-code.so).
+ *
+ * The package, class, method and field names here are an interface contract with native code:
+ * the library exports `Java_org_libreoffice_kit_<Class>_<method>` symbols and looks up fields /
+ * callbacks by name, mirroring LibreOffice's own Android binding (MPL-2.0, android/source in
+ * LibreOffice core). Do not rename anything in this package; proguard-rules.pro keeps it intact.
+ *
+ * This file is original ClearPDF code (MIT); only the names are dictated by the native side.
+ */
+package org.libreoffice.kit
+
+import android.content.res.AssetManager
+import java.nio.ByteBuffer
+
+object LibreOfficeKit {
+
+ /** Native-side initialisation of LibreOfficeKit rooted at [dataDir] (its `$APP_DATA_DIR`). */
+ @JvmStatic
+ external fun initializeNative(dataDir: String, cacheDir: String, apkFile: String, assets: AssetManager): Boolean
+
+ /** Pointer to the process-wide `LibreOfficeKit` instance, wrapped as a direct buffer. */
+ @JvmStatic
+ external fun getLibreOfficeKitHandle(): ByteBuffer?
+
+ @JvmStatic
+ external fun putenv(entry: String)
+
+ @JvmStatic
+ external fun redirectStdio(enabled: Boolean)
+}
diff --git a/app/src/main/java/org/libreoffice/kit/Office.kt b/app/src/main/java/org/libreoffice/kit/Office.kt
new file mode 100644
index 0000000..6e3cd41
--- /dev/null
+++ b/app/src/main/java/org/libreoffice/kit/Office.kt
@@ -0,0 +1,51 @@
+/*
+ * Binding for a LibreOfficeKit office instance. Names are a JNI contract — see LibreOfficeKit.kt.
+ * Original ClearPDF code (MIT).
+ */
+package org.libreoffice.kit
+
+import java.nio.ByteBuffer
+
+class Office(
+ /** Read by native code by name ("handle", Ljava/nio/ByteBuffer;). */
+ @JvmField val handle: ByteBuffer
+) {
+ /** Receives LibreOfficeKit callbacks (for example document-password requests). */
+ @Volatile
+ var callback: ((type: Int, payload: String?) -> Unit)? = null
+
+ init {
+ bindMessageCallback()
+ }
+
+ private external fun bindMessageCallback()
+
+ external fun getError(): String?
+
+ private external fun documentLoadNative(url: String): ByteBuffer?
+
+ fun documentLoad(url: String): Document? = documentLoadNative(url)?.let(::Document)
+
+ /** Answers a [LOK_CALLBACK_DOCUMENT_PASSWORD] request; a null password aborts the load. */
+ external fun setDocumentPassword(url: String, password: String?)
+
+ external fun setOptionalFeatures(features: Long)
+
+ external fun destroy()
+
+ external fun destroyAndExit()
+
+ /** Invoked from native code by name ("messageRetrievedLOKit", (ILjava/lang/String;)V). */
+ @Suppress("unused")
+ private fun messageRetrievedLOKit(type: Int, payload: String?) {
+ callback?.invoke(type, payload)
+ }
+
+ companion object {
+ /** LibreOfficeKitOptionalFeatures: LOK_FEATURE_DOCUMENT_PASSWORD. */
+ const val FEATURE_DOCUMENT_PASSWORD = 1L shl 0
+
+ /** LibreOfficeKitCallbackType: LOK_CALLBACK_DOCUMENT_PASSWORD. */
+ const val LOK_CALLBACK_DOCUMENT_PASSWORD = 20
+ }
+}
diff --git a/app/src/main/res/values/strings_office_engine.xml b/app/src/main/res/values/strings_office_engine.xml
index eb78464..d390399 100644
--- a/app/src/main/res/values/strings_office_engine.xml
+++ b/app/src/main/res/values/strings_office_engine.xml
@@ -1,4 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="office_engine_module_title">Office engine (powered by LibreOffice)</string>
+ <string name="office_engine_title">Office engine</string>
+ <string name="office_engine_powered_by">Powered by LibreOffice</string>
+ <string name="office_engine_description">Opens Word, Excel, PowerPoint and OpenDocument files with LibreOffice’s own layout for the most faithful result. Optional — the built-in renderers keep working without it.</string>
+ <string name="office_engine_not_installed">Not installed · ~%1$s download</string>
+ <string name="office_engine_installed">Installed · %1$s · v%2$s</string>
+ <string name="office_engine_update_available">Update available · %1$s</string>
+ <string name="office_engine_downloading">Downloading…</string>
+ <string name="office_engine_downloading_progress">Downloading · %1$s of %2$s</string>
+ <string name="office_engine_waiting_network">Waiting for network…</string>
+ <string name="office_engine_installing">Verifying and installing…</string>
+ <string name="office_engine_needs_confirmation">Google Play needs your approval to download</string>
+ <string name="office_engine_failed">Install failed: %1$s</string>
+ <string name="office_engine_download">Download</string>
+ <string name="office_engine_install">Install</string>
+ <string name="office_engine_update">Update</string>
+ <string name="office_engine_delete">Delete</string>
+ <string name="office_engine_cancel">Cancel</string>
+ <string name="office_engine_retry">Retry</string>
+ <string name="office_engine_approve">Approve</string>
+ <string name="office_engine_use_for_office">Use for Office files</string>
+ <string name="office_engine_use_for_office_sub">Falls back to the built-in renderers if a file fails</string>
+ <string name="office_engine_licences">LibreOffice licences (MPL-2.0)</string>
+ <string name="office_engine_delete_title">Delete Office engine?</string>
+ <string name="office_engine_delete_message">Frees %1$s. Office files will open with the built-in renderers. You can download it again at any time.</string>
+ <string name="office_engine_notification_channel">Office engine download</string>
+ <string name="office_engine_hint">Improve fidelity with the Office engine</string>
+ <string name="office_engine_hint_sub">Optional download · powered by LibreOffice</string>
+ <string name="office_engine_hint_action">Get it</string>
</resources>
diff --git a/app/src/play/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt b/app/src/play/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt
new file mode 100644
index 0000000..70b490c
--- /dev/null
+++ b/app/src/play/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt
@@ -0,0 +1,173 @@
+package com.chethan616.clearpdf.office
+
+import android.app.Activity
+import android.content.Context
+import com.google.android.play.core.splitinstall.SplitInstallManager
+import com.google.android.play.core.splitinstall.SplitInstallManagerFactory
+import com.google.android.play.core.splitinstall.SplitInstallRequest
+import com.google.android.play.core.splitinstall.SplitInstallSessionState
+import com.google.android.play.core.splitinstall.SplitInstallStateUpdatedListener
+import com.google.android.play.core.splitinstall.model.SplitInstallSessionStatus
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.launch
+import java.io.File
+import java.io.IOException
+import java.util.zip.ZipFile
+
+/**
+ * play flavor: the engine is the on-demand dynamic feature `:office_engine`, delivered by Google
+ * Play (no INTERNET permission in this app). Once Play has installed the split, its libraries
+ * and runtime tree are copied into [OfficeEngineStore] — the engine must sit next to its runtime
+ * files and have a few paths relocated — and the split is then deferred-uninstalled so the
+ * ~190 MB library is not kept twice.
+ */
+internal object OfficeEngineFlavor {
+ fun createInstaller(context: Context): OfficeEngineInstaller = PlayOfficeEngineInstaller(context)
+}
+
+private class PlayOfficeEngineInstaller(private val context: Context) : OfficeEngineInstaller {
+
+ companion object {
+ const val MODULE = "office_engine"
+ private const val CONFIRM_REQUEST_CODE = 0x0FF1
+ }
+
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private val manager: SplitInstallManager = SplitInstallManagerFactory.create(context)
+ private val _state = MutableStateFlow(OfficeEngine.installedState(context))
+ override val state: StateFlow<OfficeEngineState> = _state.asStateFlow()
+ override val usesNotification: Boolean = false
+
+ @Volatile private var sessionId = 0
+ @Volatile private var pendingConfirmation: SplitInstallSessionState? = null
+ @Volatile private var extractJob: Job? = null
+
+ private val listener = SplitInstallStateUpdatedListener { s ->
+ if (s.moduleNames().contains(MODULE).not()) return@SplitInstallStateUpdatedListener
+ sessionId = s.sessionId()
+ when (s.status()) {
+ SplitInstallSessionStatus.PENDING, SplitInstallSessionStatus.DOWNLOADING ->
+ _state.value = OfficeEngineState.Downloading(s.bytesDownloaded(), s.totalBytesToDownload())
+ SplitInstallSessionStatus.REQUIRES_USER_CONFIRMATION -> {
+ pendingConfirmation = s
+ _state.value = OfficeEngineState.NeedsConfirmation
+ }
+ SplitInstallSessionStatus.DOWNLOADED, SplitInstallSessionStatus.INSTALLING ->
+ _state.value = OfficeEngineState.Installing
+ SplitInstallSessionStatus.INSTALLED -> extractFromSplit()
+ SplitInstallSessionStatus.FAILED ->
+ _state.value = OfficeEngineState.Failed("Google Play could not install the engine (error ${s.errorCode()})")
+ SplitInstallSessionStatus.CANCELED -> _state.value = OfficeEngine.installedState(context)
+ else -> Unit
+ }
+ }
+
+ init {
+ manager.registerListener(listener)
+ }
+
+ override fun install() {
+ if (!OfficeEngine.isSupported()) return
+ if (MODULE in manager.installedModules) {
+ extractFromSplit()
+ return
+ }
+ _state.value = OfficeEngineState.Downloading(0, 0)
+ val request = SplitInstallRequest.newBuilder().addModule(MODULE).build()
+ manager.startInstall(request)
+ .addOnSuccessListener { id -> sessionId = id }
+ .addOnFailureListener { e ->
+ _state.value = OfficeEngineState.Failed(e.message ?: "Google Play could not install the engine")
+ }
+ }
+
+ override fun confirm(activity: Activity) {
+ val pending = pendingConfirmation ?: return
+ pendingConfirmation = null
+ @Suppress("DEPRECATION")
+ manager.startConfirmationDialogForResult(pending, activity, CONFIRM_REQUEST_CODE)
+ }
+
+ override fun cancel() {
+ extractJob?.cancel()
+ if (sessionId != 0) manager.cancelInstall(sessionId)
+ _state.value = OfficeEngine.installedState(context)
+ }
+
+ override fun uninstall() {
+ extractJob?.cancel()
+ scope.launch {
+ OfficeEngine.removeInstalledEngine(context)
+ runCatching { manager.deferredUninstall(listOf(MODULE)) }
+ _state.value = OfficeEngine.installedState(context)
+ }
+ }
+
+ override fun refresh() {
+ scope.launch {
+ if (extractJob?.isActive != true && sessionId == 0) _state.value = OfficeEngine.installedState(context)
+ }
+ }
+
+ private fun extractFromSplit() {
+ if (extractJob?.isActive == true) return
+ _state.value = OfficeEngineState.Installing
+ extractJob = scope.launch {
+ try {
+ val abi = OfficeEngineManifest.bundleForDevice()?.abi ?: throw IOException("Unsupported device")
+ val staging = OfficeEngineStore.resetStaging(context)
+ val splits = splitApks()
+ var files = 0
+ for (apk in splits) {
+ ZipFile(apk).use { zip ->
+ for (entry in zip.entries()) {
+ if (!isActive()) throw kotlinx.coroutines.CancellationException()
+ if (entry.isDirectory) continue
+ val name = when {
+ entry.name.startsWith("lib/$abi/") -> abi + "/" + entry.name.removePrefix("lib/$abi/")
+ entry.name.startsWith("assets/lo/") -> entry.name.removePrefix("assets/lo/")
+ else -> continue
+ }
+ val target = EngineArchiveLayout.destinationFor(staging, abi, name) ?: continue
+ target.parentFile?.mkdirs()
+ zip.getInputStream(entry).use { input -> target.outputStream().use { input.copyTo(it, 1 shl 16) } }
+ files++
+ }
+ }
+ }
+ if (files == 0) throw IOException("The engine module is empty in this build")
+ OfficeEngineClient.stopEngineProcess(context)
+ OfficeEngineStore.commit(context, staging, abi)
+ OfficeEngineClient.clearCache(context)
+ // Everything needed now lives in app storage; let Play reclaim the split.
+ runCatching { manager.deferredUninstall(listOf(MODULE)) }
+ sessionId = 0
+ _state.value = OfficeEngine.installedState(context)
+ } catch (e: kotlinx.coroutines.CancellationException) {
+ OfficeEngineStore.stagingDir(context).deleteRecursively()
+ throw e
+ } catch (e: Exception) {
+ OfficeEngineStore.stagingDir(context).deleteRecursively()
+ sessionId = 0
+ _state.value = OfficeEngineState.Failed(e.message ?: "Could not install the engine")
+ }
+ }
+ }
+
+ private fun isActive(): Boolean = extractJob?.isActive != false
+
+ /** Installed split APKs (fresh from PackageManager) plus SplitCompat-emulated ones (local testing). */
+ private fun splitApks(): List<File> {
+ val info = context.packageManager.getApplicationInfo(context.packageName, 0)
+ val installed = info.splitSourceDirs.orEmpty().map(::File)
+ val emulated = File(context.filesDir, "splitcompat").walkTopDown().filter { it.isFile && it.extension == "apk" }.toList()
+ return (installed + emulated).filter { it.name.contains(MODULE) || it.name.contains("office") }
+ .ifEmpty { installed + emulated }
+ }
+}