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.

Auto dark pages (#74), Arabic copy/search order (#72), Fill Form tool fills on the page

chethan61659b33cae81e4
diff --git a/app/src/main/java/com/chethan616/clearpdf/data/repository/Preferences.kt b/app/src/main/java/com/chethan616/clearpdf/data/repository/Preferences.kt
index dbe1e53..266691a 100644
--- a/app/src/main/java/com/chethan616/clearpdf/data/repository/Preferences.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/data/repository/Preferences.kt
@@ -163,6 +163,7 @@ object AppSettingsManager {
private const val KEY_REMEMBER_RECENT_FILES = "remember_recent_files"
private const val KEY_KEEP_LOCAL_COPIES = "keep_local_document_copies"
private const val KEY_REDUCE_GLASS_MOTION = "reduce_glass_motion"
+ private const val KEY_AUTO_DARK_PAGES = "auto_dark_pages"
private fun prefs(context: Context): SharedPreferences =
context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
@@ -176,6 +177,10 @@ object AppSettingsManager {
// Opt-in (default off: full quality). Freezes the gravity-tracked specular highlight that
// every liquidGlassPanel/capsule reads instead of letting it keep publishing tilt updates —
// see UISensor's own KDoc for why that is the dominant redraw cost on devices sensitive to it.
+ /** Documents open with dark pages whenever the app is in dark mode (#74). */
+ fun getAutoDarkPages(context: Context): Boolean = prefs(context).getBoolean(KEY_AUTO_DARK_PAGES, false)
+ fun setAutoDarkPages(context: Context, enabled: Boolean) = prefs(context).edit().putBoolean(KEY_AUTO_DARK_PAGES, enabled).apply()
+
fun getReduceGlassMotion(context: Context): Boolean =
prefs(context).getBoolean(KEY_REDUCE_GLASS_MOTION, false)
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt b/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt
index ca338b3..4896779 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt
@@ -775,7 +775,7 @@ fun DocsNavGraph(
backdrop = backdrop,
viewModel = vm,
onBack = { navController.popBackStack() },
- onViewOutput = { uri -> navController.navigateToPdfViewer(uri) }
+ onFillOnPage = { uri -> navController.navigateToPdfViewer(uri) }
)
}
}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/FillFormScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/FillFormScreen.kt
index da9c212..c5f982b 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/FillFormScreen.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/FillFormScreen.kt
@@ -1,13 +1,8 @@
package com.chethan616.clearpdf.ui.screen
-import androidx.compose.runtime.setValue
-import androidx.compose.runtime.mutableStateOf
-import androidx.compose.runtime.remember
-import androidx.activity.compose.BackHandler
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
-import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
@@ -16,11 +11,13 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
-import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
-import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.rounded.ArrowDropDownCircle
+import androidx.compose.material.icons.rounded.CheckBox
import androidx.compose.material.icons.rounded.EditNote
+import androidx.compose.material.icons.rounded.Keyboard
+import androidx.compose.material.icons.rounded.Save
import androidx.compose.material.icons.rounded.UploadFile
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
@@ -30,170 +27,117 @@ import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
-import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
-import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.chethan616.clearpdf.R
-import com.chethan616.clearpdf.ui.components.GlassSectionHeader
+import com.chethan616.clearpdf.ui.components.AccentIconTile
import com.chethan616.clearpdf.ui.components.LiquidButton
import com.chethan616.clearpdf.ui.components.LiquidGlassErrorCard
-import com.chethan616.clearpdf.ui.components.LiquidToggle
import com.chethan616.clearpdf.ui.components.ToolScaffold
-import com.chethan616.clearpdf.ui.components.UnsavedChangesDialog
import com.chethan616.clearpdf.ui.components.liquidGlassPanel
+import com.chethan616.clearpdf.ui.theme.LiquidGlassColors
import com.chethan616.clearpdf.ui.theme.LocalIsDarkMode
import com.chethan616.clearpdf.ui.utils.rememberUISensor
import com.chethan616.clearpdf.ui.viewmodel.FillFormViewModel
-import com.kyant.pdfcore.form.PdfFormService
import com.kyant.backdrop.backdrops.LayerBackdrop
import kotlinx.coroutines.delay
private val FormAccent = Color(0xFF00695C)
+/**
+ * The Fill Form tool. Forms are filled on the page now (#68): pick a PDF, and if it has fields it
+ * opens in the viewer, where every field is a Liquid Glass control you fill where it's printed —
+ * instead of the old list of field names, where it was impossible to tell which field was which.
+ */
@Composable
fun FillFormScreen(
backdrop: LayerBackdrop,
viewModel: FillFormViewModel,
onBack: () -> Unit,
- onViewOutput: (Uri) -> Unit
+ onFillOnPage: (Uri) -> Unit
) {
val state by viewModel.uiState.collectAsState()
val isDark = LocalIsDarkMode.current
- val isLight = !isDark
- val text = if (isLight) Color(0xFF222222) else Color(0xFFF0F0F0)
- val sub = if (isLight) Color(0xFF888888) else Color(0xFFAAAAAA)
+ val text = LiquidGlassColors.text(isDark)
+ val sub = LiquidGlassColors.secondary(isDark)
val uiSensor = rememberUISensor()
val context = LocalContext.current
- LaunchedEffect(state.resultMessage, state.errorMessage) {
- if (state.resultMessage != null || state.errorMessage != null) { delay(3500); viewModel.clearFeedback() }
+ LaunchedEffect(state.errorMessage) {
+ if (state.errorMessage != null) { delay(4000); viewModel.clearFeedback() }
+ }
+ // A form with fields goes straight to the page. Reset first, so coming back here doesn't
+ // reopen it.
+ LaunchedEffect(state.loaded, state.fields.size, state.sourceUri) {
+ val uri = state.sourceUri ?: return@LaunchedEffect
+ if (state.loaded && state.fields.isNotEmpty()) {
+ viewModel.reset()
+ onFillOnPage(uri)
+ }
}
val filePicker = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocument()
) { uri -> if (uri != null) viewModel.onSelectFile(context, uri) }
- var confirmExit by remember { mutableStateOf(false) }
- val requestBack = { if (state.dirty && !state.isProcessing) confirmExit = true else onBack() }
- BackHandler(enabled = state.dirty && !confirmExit) { requestBack() }
-
ToolScaffold(
title = stringResource(R.string.tool_fill_form),
backdrop = backdrop,
- onBack = requestBack,
- onBackLongPress = requestBack,
- overlay = { screenGlass ->
- UnsavedChangesDialog(
- visible = confirmExit,
- onDiscard = { confirmExit = false; onBack() },
- onCancel = { confirmExit = false },
- onSave = { confirmExit = false; viewModel.save(context, onSaved = onBack) },
- backdrop = screenGlass,
- accent = FormAccent
- )
- }
+ onBack = onBack
) {
Column(
Modifier.fillMaxWidth().liquidGlassPanel(backdrop, uiSensor).padding(28.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
- Icon(Icons.Rounded.EditNote, null, Modifier.size(56.dp), FormAccent)
- BasicText(stringResource(R.string.tool_fill_form), style = TextStyle(text, 20.sp, fontWeight = FontWeight.SemiBold))
- BasicText(stringResource(R.string.tool_fill_form_sub), style = TextStyle(sub, 14.sp, textAlign = TextAlign.Center))
- LiquidButton(onClick = { filePicker.launch(arrayOf("application/pdf")) }, backdrop = backdrop, tint = FormAccent) {
- Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
- Icon(Icons.Rounded.UploadFile, null, Modifier.size(18.dp), Color.White)
- BasicText(stringResource(R.string.viewer_pick_pdf), style = TextStyle(Color.White, 15.sp, fontWeight = FontWeight.Medium))
- }
- }
- }
-
- if (state.fields.isNotEmpty()) {
- Column(
- Modifier.fillMaxWidth().liquidGlassPanel(backdrop, uiSensor).padding(20.dp),
- verticalArrangement = Arrangement.spacedBy(16.dp)
- ) {
- GlassSectionHeader(
- title = stringResource(R.string.fill_form_fields),
- icon = Icons.Rounded.EditNote, iconTint = FormAccent, titleColor = text,
- trailing = { BasicText("${state.fields.size}", style = TextStyle(sub, 13.sp)) }
- )
- state.fields.forEach { field ->
- when (field.type) {
- PdfFormService.FieldType.CHECKBOX -> {
- Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) {
- BasicText(field.name, style = TextStyle(text, 14.sp), maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
- LiquidToggle(
- selected = { field.value == "true" },
- onSelect = { viewModel.onFieldChange(field.name, if (it) "true" else "false") },
- backdrop = backdrop
- )
- }
- }
- else -> {
- Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
- BasicText(field.name, style = TextStyle(sub, 12.sp), maxLines = 1, overflow = TextOverflow.Ellipsis)
- BasicTextField(
- value = field.value,
- onValueChange = { viewModel.onFieldChange(field.name, it) },
- singleLine = true,
- textStyle = TextStyle(text, 15.sp),
- modifier = Modifier
- .fillMaxWidth()
- .clip(RoundedCornerShape(10.dp))
- .background(if (isDark) Color.White.copy(0.08f) else Color.Black.copy(0.05f))
- .padding(horizontal = 12.dp, vertical = 10.dp)
- )
- if (field.options.isNotEmpty()) {
- BasicText(field.options.joinToString(" · "), style = TextStyle(sub.copy(0.8f), 11.sp), maxLines = 1, overflow = TextOverflow.Ellipsis)
- }
- }
- }
- }
- }
-
- Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) {
- Column(Modifier.weight(1f)) {
- BasicText(stringResource(R.string.fill_form_flatten), style = TextStyle(text, 15.sp, fontWeight = FontWeight.Medium))
- BasicText(stringResource(R.string.fill_form_flatten_desc), style = TextStyle(sub, 12.sp))
- }
- LiquidToggle(selected = { state.flatten }, onSelect = viewModel::onFlattenChange, backdrop = backdrop)
- }
- }
-
+ AccentIconTile(Icons.Rounded.EditNote, FormAccent, size = 64, iconSize = 34)
+ BasicText(stringResource(R.string.fill_form_hero_title), style = TextStyle(text, 20.sp, fontWeight = FontWeight.SemiBold, textAlign = TextAlign.Center))
+ BasicText(stringResource(R.string.fill_form_hero_desc), style = TextStyle(sub, 14.sp, textAlign = TextAlign.Center, lineHeight = 19.sp))
LiquidButton(
- onClick = { if (!state.isProcessing) viewModel.save(context) },
- backdrop = backdrop, tint = FormAccent, modifier = Modifier.fillMaxWidth()
+ onClick = { if (state.sourceUri == null || state.loaded) filePicker.launch(arrayOf("application/pdf")) },
+ backdrop = backdrop,
+ tint = FormAccent
) {
- Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(vertical = 8.dp)) {
- if (state.isProcessing) CircularProgressIndicator(Modifier.size(18.dp), Color.White, strokeWidth = 2.dp)
- else Icon(Icons.Rounded.EditNote, null, Modifier.size(18.dp), Color.White)
- BasicText(
- stringResource(if (state.isProcessing) R.string.fill_form_working else R.string.fill_form_action),
- style = TextStyle(Color.White, 15.sp, fontWeight = FontWeight.Medium), maxLines = 1
- )
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
+ if (state.sourceUri != null && !state.loaded) CircularProgressIndicator(Modifier.size(18.dp), Color.White, strokeWidth = 2.dp)
+ else Icon(Icons.Rounded.UploadFile, null, Modifier.size(18.dp), Color.White)
+ BasicText(stringResource(R.string.fill_form_pick), style = TextStyle(Color.White, 15.sp, fontWeight = FontWeight.SemiBold))
}
}
}
- if (state.errorMessage != null) {
- LiquidGlassErrorCard(message = state.errorMessage!!, backdrop = backdrop, uiSensor = uiSensor, onDismiss = { viewModel.clearFeedback() })
+ Column(
+ Modifier.fillMaxWidth().liquidGlassPanel(backdrop, uiSensor).padding(horizontal = 20.dp, vertical = 18.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ FillFormStep(Icons.Rounded.Keyboard, LiquidGlassColors.Blue, R.string.fill_form_step_type_title, R.string.fill_form_step_type_desc, text, sub)
+ FillFormStep(Icons.Rounded.CheckBox, LiquidGlassColors.Indigo, R.string.fill_form_step_tick_title, R.string.fill_form_step_tick_desc, text, sub)
+ FillFormStep(Icons.Rounded.ArrowDropDownCircle, LiquidGlassColors.Teal, R.string.fill_form_step_pick_title, R.string.fill_form_step_pick_desc, text, sub)
+ FillFormStep(Icons.Rounded.Save, FormAccent, R.string.fill_form_step_save_title, R.string.fill_form_step_save_desc, text, sub)
}
- state.lastOutputUri?.let { outUri ->
- LiquidButton(onClick = { onViewOutput(outUri) }, backdrop = backdrop, tint = FormAccent, modifier = Modifier.fillMaxWidth()) {
- BasicText(stringResource(R.string.viewer_open_pdf), style = TextStyle(Color.White, 15.sp, FontWeight.SemiBold), modifier = Modifier.padding(vertical = 8.dp))
- }
+ if (state.errorMessage != null) {
+ LiquidGlassErrorCard(message = state.errorMessage!!, backdrop = backdrop, uiSensor = uiSensor, onDismiss = { viewModel.clearFeedback() })
}
Spacer(Modifier.height(40.dp))
}
}
+
+@Composable
+private fun FillFormStep(icon: ImageVector, accent: Color, title: Int, desc: Int, text: Color, sub: Color) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
+ AccentIconTile(icon, accent, size = 40, iconSize = 21)
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ BasicText(stringResource(title), style = TextStyle(text, 15.sp, FontWeight.SemiBold))
+ BasicText(stringResource(desc), style = TextStyle(sub, 12.5.sp, lineHeight = 17.sp))
+ }
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerScreen.kt
index a16ed7f..6de099f 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerScreen.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerScreen.kt
@@ -240,7 +240,11 @@ fun PdfViewerScreen(
val passwordFocusRequester = remember { FocusRequester() }
var showSignaturePad by remember { mutableStateOf(false) }
var showZoomHud by remember { mutableStateOf(false) }
- var darkPageAppearance by rememberSaveable { mutableStateOf(false) }
+ // #74: with "Dark pages in dark mode" on, every document opens with dark pages while the app is
+ // dark; the moon button still switches it per document.
+ val autoDarkPages = com.chethan616.clearpdf.ui.theme.LocalIsDarkMode.current &&
+ remember { com.chethan616.clearpdf.data.repository.AppSettingsManager.getAutoDarkPages(context) }
+ var darkPageAppearance by rememberSaveable { mutableStateOf(autoDarkPages) }
var bookmarkedPages by remember { mutableStateOf<List<Int>>(emptyList()) }
// Annotation (text box / sticky note) editing
var editingAnnoId by remember { mutableStateOf<Long?>(null) }
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SettingsScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SettingsScreen.kt
index 3316bc7..41d487d 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SettingsScreen.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SettingsScreen.kt
@@ -328,6 +328,20 @@ fun SettingsScreen(
style = TextStyle(sub, 12.sp)
)
SettingsDivider(isLight)
+ // #74: dark pages follow the app's dark mode, so night reading needs no tap.
+ var autoDarkPages by remember { mutableStateOf(com.chethan616.clearpdf.data.repository.AppSettingsManager.getAutoDarkPages(context)) }
+ SettingsToggleRow(
+ icon = Icons.Rounded.DarkMode,
+ title = stringResource(R.string.settings_auto_dark_pages),
+ desc = stringResource(R.string.settings_auto_dark_pages_desc),
+ checked = autoDarkPages,
+ onCheckedChange = {
+ autoDarkPages = it
+ com.chethan616.clearpdf.data.repository.AppSettingsManager.setAutoDarkPages(context, it)
+ },
+ backdrop = backdrop
+ )
+ SettingsDivider(isLight)
SettingsToggleRow(
icon = Icons.Rounded.Vibration,
title = stringResource(R.string.settings_reduce_glass_motion),
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfTextSelectionState.kt b/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfTextSelectionState.kt
index 11228b2..9d95d79 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfTextSelectionState.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfTextSelectionState.kt
@@ -197,7 +197,8 @@ class PdfTextSelectionState {
val (from, to) = pageRange(p) ?: continue
layout(p)?.substring(from, to)?.let { if (it.isNotBlank()) parts.add(it) }
}
- return parts.joinToString("\n\n")
+ // PDFs store right-to-left lines in visual order; copy them in reading order (#72).
+ return com.kyant.pdfcore.text.PdfBidi.visualToLogical(parts.joinToString("\n\n"))
}
/** Screen caret geometry for a selection end, or null when that page is not laid out. */
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/FillFormViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/FillFormViewModel.kt
index a962d85..68419cb 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/FillFormViewModel.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/FillFormViewModel.kt
@@ -54,7 +54,7 @@ class FillFormViewModel : ViewModel() {
_uiState.update {
it.copy(
fields = fields, loaded = true,
- errorMessage = if (fields.isEmpty()) "This PDF has no fillable form fields" else null
+ errorMessage = if (fields.isEmpty()) context.getString(com.chethan616.clearpdf.R.string.fill_form_no_fields) else null
)
}
}
@@ -94,6 +94,9 @@ class FillFormViewModel : ViewModel() {
}
}
+ /** Back to the empty state (after handing a form to the viewer). */
+ fun reset() = _uiState.update { FillFormUiState() }
+
fun clearFeedback() = _uiState.update { it.copy(errorMessage = null, resultMessage = null) }
private fun queryName(context: Context, uri: Uri): String =
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.kt
index 00c85b9..f8c1eb3 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.kt
@@ -1099,17 +1099,20 @@ private fun OcrTextBlock.findMatches(lower: String, page: Int): List<FindMatch>
if (lower.isEmpty()) return emptyList()
val bt = text.lowercase()
val out = ArrayList<FindMatch>()
+ // Right-to-left text is stored in visual order: look for the query's visual form too (#72).
+ for (q in com.kyant.pdfcore.text.PdfBidi.searchForms(lower)) {
var from = 0
while (true) {
- val idx = bt.indexOf(lower, from)
+ val idx = bt.indexOf(q, from)
if (idx < 0) break
- val endC = idx + lower.length - 1
+ val endC = idx + q.length - 1
if (charLefts.isNotEmpty() && idx < charLefts.size && endC < charRights.size) {
out.add(FindMatch(page, charLefts[idx], top, charRights[endC], bottom))
} else {
out.add(FindMatch(page, left, top, right, bottom))
}
- from = idx + lower.length
+ from = idx + q.length
+ }
}
return out
}
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index c3aaafd..3752018 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -155,6 +155,18 @@
<string name="tool_fill_form">Fill Form</string>
<string name="tool_fill_form_sub">Complete PDF form fields</string>
<string name="fill_form_fields">Form fields</string>
+ <string name="fill_form_hero_title">Fill forms right on the page</string>
+ <string name="fill_form_hero_desc">Pick a PDF form and it opens with every field ready to fill where it\'s printed.</string>
+ <string name="fill_form_pick">Choose a PDF form</string>
+ <string name="fill_form_step_type_title">Type in place</string>
+ <string name="fill_form_step_type_desc">Tap a text field and type. A bar above the keyboard jumps to the next field.</string>
+ <string name="fill_form_step_tick_title">Tick and choose</string>
+ <string name="fill_form_step_tick_desc">Checkboxes and radio buttons switch with a tap.</string>
+ <string name="fill_form_step_pick_title">Dropdowns and lists</string>
+ <string name="fill_form_step_pick_desc">Pick from a glass menu, or scroll a list right in its box.</string>
+ <string name="fill_form_step_save_title">Save or share</string>
+ <string name="fill_form_step_save_desc">Values are saved into the form itself, in its own style.</string>
+ <string name="fill_form_no_fields">This PDF has no fillable form fields</string>
<string name="fill_form_flatten">Flatten when saving</string>
<string name="fill_form_flatten_desc">Make the filled values permanent</string>
<string name="fill_form_action">Save Filled PDF</string>
@@ -327,6 +339,8 @@
<string name="text_edit_title">Edit text</string>
<string name="text_edit_hint">Rewrites this line of the document in its own font. Tap empty space with the Text tool to add new text instead.</string>
<string name="text_edit_revert">Restore</string>
+ <string name="settings_auto_dark_pages">Dark pages in dark mode</string>
+ <string name="settings_auto_dark_pages_desc">Documents open with dark pages whenever the app is dark</string>
<string name="form_fill_previous">Previous field</string>
<string name="form_fill_next">Next field</string>
<string name="tour_form_title">Fill the form on the page</string>
diff --git a/pdf-core/build.gradle.kts b/pdf-core/build.gradle.kts
index f56fe61..a8957b4 100644
--- a/pdf-core/build.gradle.kts
+++ b/pdf-core/build.gradle.kts
@@ -32,4 +32,6 @@ dependencies {
// Lossless PDF page operations (merge / split / reorder / rotate / text extraction).
// PdfRenderer can only rasterise pages; PdfBox preserves the original text & vectors.
implementation(libs.pdfbox.android)
+
+ testImplementation("junit:junit:4.13.2")
}
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfBidi.kt b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfBidi.kt
new file mode 100644
index 0000000..d796212
--- /dev/null
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfBidi.kt
@@ -0,0 +1,109 @@
+package com.kyant.pdfcore.text
+
+import java.text.Normalizer
+
+/**
+ * Right-to-left text (Arabic, Hebrew…) comes out of a PDF in *visual* order: glyphs left to right,
+ * as painted. Selecting and copying it that way pastes every word backwards (#72). This turns a
+ * line's visual order into the logical (reading) order apps expect, the way PDF readers do:
+ *
+ * - the line's direction is the majority of its strong letters;
+ * - it is split into runs of right-to-left and left-to-right text, and the spaces and punctuation
+ * between them join the neighbouring direction (or the line's, between two different ones);
+ * - for a right-to-left line the runs are read right to left; inside a right-to-left run the
+ * characters are reversed, and mirrored brackets swap; left-to-right runs (numbers, Latin words)
+ * keep their order;
+ * - Arabic presentation forms (the shaped glyph code points some PDFs use) are normalized back to
+ * the plain letters people type.
+ *
+ * Text without right-to-left letters is returned unchanged.
+ */
+object PdfBidi {
+
+ fun isRtl(c: Char): Boolean = c in '֐'..'ࣿ' || c in 'יִ'..'﷿' || c in 'ﹰ'..''
+
+ fun hasRtl(s: CharSequence): Boolean = s.any { isRtl(it) }
+
+ /**
+ * The strings to look for in a line's (visual-order) text when searching for [query]: the
+ * query itself, plus its visual form when it has right-to-left letters (the reordering is its
+ * own inverse for a line).
+ */
+ fun searchForms(query: String): List<String> {
+ if (!hasRtl(query)) return listOf(query)
+ val visual = query.split('\n').joinToString("\n") { lineToLogical(it) }
+ return if (visual == query) listOf(query) else listOf(query, visual)
+ }
+
+ /** Visual → logical order, line by line. */
+ fun visualToLogical(s: String): String {
+ if (!hasRtl(s)) return s
+ return s.split('\n').joinToString("\n") { lineToLogical(it) }.let(::normalizeArabic)
+ }
+
+ private enum class Dir { RTL, LTR, NEUTRAL }
+
+ private fun dirOf(c: Char): Dir = when {
+ isRtl(c) && (Character.isLetter(c) || Character.getType(c) == Character.NON_SPACING_MARK.toInt()) -> Dir.RTL
+ Character.isLetterOrDigit(c) -> Dir.LTR
+ else -> Dir.NEUTRAL
+ }
+
+ private fun lineToLogical(line: String): String {
+ if (!hasRtl(line)) return line
+ val dirs = line.map(::dirOf)
+ val rtlCount = dirs.count { it == Dir.RTL }
+ val ltrCount = line.indices.count { dirs[it] == Dir.LTR && line[it].isLetter() }
+ val base = if (rtlCount >= ltrCount) Dir.RTL else Dir.LTR
+
+ // Resolve neutrals: between two runs of the same direction they take it, otherwise the base.
+ val resolved = dirs.toMutableList()
+ var i = 0
+ while (i < resolved.size) {
+ if (resolved[i] != Dir.NEUTRAL) { i++; continue }
+ var j = i
+ while (j < resolved.size && resolved[j] == Dir.NEUTRAL) j++
+ val before = if (i > 0) resolved[i - 1] else base
+ val after = if (j < resolved.size) resolved[j] else base
+ val d = if (before == after) before else base
+ for (k in i until j) resolved[k] = d
+ i = j
+ }
+
+ // Runs of one direction, in visual order.
+ val runs = ArrayList<Pair<Dir, String>>()
+ var start = 0
+ for (k in 1..line.length) {
+ if (k == line.length || resolved[k] != resolved[start]) {
+ runs += resolved[start] to line.substring(start, k)
+ start = k
+ }
+ }
+ val ordered = if (base == Dir.RTL) runs.asReversed() else runs
+ return ordered.joinToString("") { (d, text) -> if (d == Dir.RTL) mirror(text.reversed()) else text }
+ }
+
+ private fun mirror(s: String): String = buildString(s.length) {
+ for (c in s) append(
+ when (c) {
+ '(' -> ')'; ')' -> '('
+ '[' -> ']'; ']' -> '['
+ '{' -> '}'; '}' -> '{'
+ '<' -> '>'; '>' -> '<'
+ '«' -> '»'; '»' -> '«'
+ else -> c
+ }
+ )
+ }
+
+ /** Arabic presentation forms (U+FB50–FDFF, U+FE70–FEFF) back to plain letters. */
+ private fun normalizeArabic(s: String): String {
+ if (s.none { it in 'ﭐ'..'﷿' || it in 'ﹰ'..'' }) return s
+ val sb = StringBuilder(s.length)
+ for (c in s) {
+ if (c in 'ﭐ'..'﷿' || c in 'ﹰ'..'') sb.append(Normalizer.normalize(c.toString(), Normalizer.Form.NFKC))
+ else sb.append(c)
+ }
+ return sb.toString()
+ }
+}
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextService.kt b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextService.kt
index 7d64041..455cfc5 100644
--- a/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextService.kt
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextService.kt
@@ -274,17 +274,20 @@ fun PdfTextBlock.matchRects(lower: String, pageIndex: Int): List<PdfSearchMatch>
if (lower.isEmpty() || charLefts.isEmpty()) return emptyList()
val bt = text.lowercase()
val out = ArrayList<PdfSearchMatch>()
- var from = 0
- while (true) {
- val idx = bt.indexOf(lower, from)
- if (idx < 0) break
- val endC = idx + lower.length - 1
- if (idx < charLefts.size && endC < charRights.size) {
- out.add(PdfSearchMatch(pageIndex, charLefts[idx], top, charRights[endC], bottom))
- } else {
- out.add(PdfSearchMatch(pageIndex, left, top, right, bottom))
+ // Right-to-left text is stored in visual order: look for the query's visual form too (#72).
+ for (q in PdfBidi.searchForms(lower)) {
+ var from = 0
+ while (true) {
+ val idx = bt.indexOf(q, from)
+ if (idx < 0) break
+ val endC = idx + q.length - 1
+ if (idx < charLefts.size && endC < charRights.size) {
+ out.add(PdfSearchMatch(pageIndex, charLefts[idx], top, charRights[endC], bottom))
+ } else {
+ out.add(PdfSearchMatch(pageIndex, left, top, right, bottom))
+ }
+ from = idx + q.length
}
- from = idx + lower.length
}
return out
}
diff --git a/pdf-core/src/test/java/com/kyant/pdfcore/text/PdfBidiTest.kt b/pdf-core/src/test/java/com/kyant/pdfcore/text/PdfBidiTest.kt
new file mode 100644
index 0000000..542c9e5
--- /dev/null
+++ b/pdf-core/src/test/java/com/kyant/pdfcore/text/PdfBidiTest.kt
@@ -0,0 +1,45 @@
+package com.kyant.pdfcore.text
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+/** #72: Arabic copied from a PDF must paste in reading order, not reversed. */
+class PdfBidiTest {
+
+ @Test fun pureArabicLineReadsInOrder() {
+ val logical = "هي أصل تمتلكه المنشأة"
+ assertEquals(logical, PdfBidi.visualToLogical(logical.reversed()))
+ }
+
+ @Test fun numbersInsideArabicKeepTheirOrder() {
+ // Painted right to left: the words reversed, the number left as is.
+ val visual = "هينج 120 رعس"
+ assertEquals("سعر 120 جنيه", PdfBidi.visualToLogical(visual))
+ }
+
+ @Test fun arabicInsideEnglishIsReversedInPlace() {
+ assertEquals("Price: سعر", PdfBidi.visualToLogical("Price: رعس"))
+ }
+
+ @Test fun bracketsMirror() {
+ val logical = "البضاعة (المشتريات)"
+ // Visual: whole line reversed, brackets as painted (mirrored glyphs read as the swapped char).
+ val visual = logical.reversed().map { when (it) { '(' -> ')'; ')' -> '('; else -> it } }.joinToString("")
+ assertEquals(logical, PdfBidi.visualToLogical(visual))
+ }
+
+ @Test fun latinTextIsUntouched() {
+ assertEquals("Hello world (test)", PdfBidi.visualToLogical("Hello world (test)"))
+ }
+
+ @Test fun presentationFormsBecomePlainLetters() {
+ // U+FE8E ARABIC LETTER ALEF FINAL FORM, U+FEE3 MEEM INITIAL FORM
+ assertEquals("ما", PdfBidi.visualToLogical("\uFE8E\uFEE3"))
+ }
+
+ @Test fun searchFindsArabicInVisualText() {
+ val visualLine = "هي أصل تمتلكه".reversed()
+ val forms = PdfBidi.searchForms("أصل")
+ assert(forms.any { visualLine.contains(it) })
+ }
+}