Skip to content

CircleToSearch with multi search engine support for all android

Kotlin

fix: removed tesseract completly

AKS Labsca79620b3328
diff --git a/OCR-translation/src/main/java/dev/davidv/translator/TranslationCoordinator.kt b/OCR-translation/src/main/java/dev/davidv/translator/TranslationCoordinator.kt
index 72c4ea8..e549958 100644
--- a/OCR-translation/src/main/java/dev/davidv/translator/TranslationCoordinator.kt
+++ b/OCR-translation/src/main/java/dev/davidv/translator/TranslationCoordinator.kt
@@ -291,6 +291,96 @@ class TranslationCoordinator(
}
}
+ /**
+ * OCR a bitmap and return the recognized source words without rendering a translation
+ * overlay — for surfaces that show the original image with tappable text (e.g. Circle to
+ * Search's screenshot). The plan still takes a target language ([to]) because recognition
+ * runs through the translation pipeline; the translation result is discarded.
+ *
+ * [onDetectedRegions] fires as soon as boxes are detected, before recognition finishes
+ * (for scan animations). Returns null when OCR failed; [onOcrUnavailable] flags a missing
+ * OCR model chain so the caller can prompt for a repair/download.
+ */
+ suspend fun ocrWordsOnly(
+ bitmap: Bitmap,
+ to: Language,
+ sourceSelection: OcrSourceSelection = OcrSourceSelection.Auto,
+ readingOrder: ReadingOrder? = null,
+ onDetectedRegions: (List<uniffi.translator_core.OrientedRect>, Int, Int) -> Unit = { _, _, _ -> },
+ onOcrUnavailable: () -> Unit = {},
+ ): OcrWordsResult? =
+ withContext(Dispatchers.IO) {
+ _isOcrInProgress.value = true
+ try {
+ val catalog = imageProcessor.loadCatalog() ?: return@withContext null
+ val minConfidence = settingsManager.settings.value.minConfidence
+ val backgroundMode = settingsManager.settings.value.backgroundMode
+ val maxImageSize = settingsManager.settings.value.maxImageSize
+ val ocrStart = System.currentTimeMillis()
+ val srcAddr = NativeBitmap.lockPixels(bitmap)
+ if (srcAddr == 0L) {
+ Log.e("TranslationCoordinator", "lockPixels(source) failed")
+ return@withContext null
+ }
+ val ocrImage =
+ uniffi.bindings.OcrImage.fromPixels(
+ srcAddr.toULong(),
+ bitmap.width.toUInt(),
+ bitmap.height.toUInt(),
+ )
+ NativeBitmap.unlockPixels(bitmap)
+
+ val detection =
+ try {
+ catalog.ocrImageDetect(ocrImage, maxImageSize)
+ } catch (e: uniffi.bindings.CatalogException) {
+ Log.d("OCR", "detect failed: ${e.message}")
+ null
+ }
+ detection?.let { boxes ->
+ onDetectedRegions(boxes.map { it.orientedBox }, bitmap.width, bitmap.height)
+ }
+
+ val plan =
+ try {
+ catalog.ocrImagePlan(
+ ocrImage,
+ maxImageSize,
+ sourceSelection,
+ to,
+ minConfidence,
+ readingOrder,
+ backgroundMode,
+ detection,
+ )
+ } catch (e: uniffi.bindings.CatalogException.MissingAsset) {
+ Log.d("OCR", "ocr plan failed: ${e.message}")
+ onOcrUnavailable()
+ ocrImage.close()
+ return@withContext null
+ } catch (e: uniffi.bindings.CatalogException) {
+ Log.d("OCR", "ocr plan failed: ${e.message}")
+ ocrImage.close()
+ return@withContext null
+ }
+ Log.i("TranslationCoordinator", "ocrWordsOnly: ${System.currentTimeMillis() - ocrStart}ms")
+ val result =
+ OcrWordsResult(
+ sourceWords = plan.sourceWords,
+ extractedText = plan.extractedText,
+ imageWidth = bitmap.width,
+ imageHeight = bitmap.height,
+ )
+ ocrImage.close()
+ result
+ } catch (e: Exception) {
+ Log.e("TranslationCoordinator", "Exception ${e.stackTrace}")
+ null
+ } finally {
+ _isOcrInProgress.value = false
+ }
+ }
+
suspend fun retranslateImageWithOverlay(
cachedPlan: PreparedImageOverlay,
from: Language,
@@ -436,3 +526,11 @@ data class ProcessedImageResult(
// Rust-side owner of the source pixels; reused for a language switch without re-OCR/copy.
val ocrImage: uniffi.bindings.OcrImage? = null,
)
+
+/** Recognized source words from an OCR-only pass ([TranslationCoordinator.ocrWordsOnly]). */
+data class OcrWordsResult(
+ val sourceWords: List<uniffi.translator_core.PositionedWord>,
+ val extractedText: String,
+ val imageWidth: Int,
+ val imageHeight: Int,
+)
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 0c0ef7a..5e83834 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -144,6 +144,5 @@ dependencies {
implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.1.0")
implementation("androidx.webkit:webkit:1.9.0")
implementation("com.google.code.gson:gson:2.10.1")
- implementation("com.github.adaptech-cz.Tesseract4Android:tesseract4android:4.8.0")
implementation("com.google.zxing:core:3.5.4")
}
diff --git a/app/src/main/assets/tessdata/eng.traineddata b/app/src/main/assets/tessdata/eng.traineddata
deleted file mode 100644
index bbef467..0000000
Binary files a/app/src/main/assets/tessdata/eng.traineddata and /dev/null differ
diff --git a/app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.kt b/app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.kt
index f72cb7b..0a853fa 100644
--- a/app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.kt
+++ b/app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.kt
@@ -61,7 +61,6 @@ import com.akslabs.circletosearch.data.BitmapRepository
import com.akslabs.circletosearch.data.GestureType
import com.akslabs.circletosearch.data.OverlayConfigurationManager
import com.akslabs.circletosearch.data.OverlaySegment
-import com.akslabs.circletosearch.ui.components.CopyTextOverlayManager
import com.akslabs.circletosearch.utils.ImageUtils
import java.util.concurrent.Executor
import java.util.concurrent.Executors
@@ -72,9 +71,6 @@ class CircleToSearchAccessibilityService : AccessibilityService() {
private val overlayViews = mutableListOf<View>() // Track all added segment views
private val executor: Executor = Executors.newSingleThreadExecutor()
private lateinit var configManager: OverlayConfigurationManager
-
- /** Kept by companion so scroll events can re-scan copy-text nodes. */
- internal var copyTextManager: CopyTextOverlayManager? = null
private var translatorBridge: TranslatorOverlayBridge? = null
@@ -1169,11 +1165,6 @@ class CircleToSearchAccessibilityService : AccessibilityService() {
}
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
- // Forward scroll events to the Copy Text overlay for live re-scan
- // Only if it's a scroll event and the copy manager is active
- if (event?.eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
- copyTextManager?.rescanNodes()
- }
translatorBridge?.onHostAccessibilityEvent(event)
}
@@ -1204,16 +1195,16 @@ class CircleToSearchAccessibilityService : AccessibilityService() {
translatorBridge?.setGestureAlpha(alpha)
}
+ /** The default target language for OCR-only plans (no translation rendered). */
+ fun defaultTargetLanguage(): dev.davidv.translator.Language? =
+ translatorBridge?.defaultTargetLanguage()
+
companion object {
var instance: CircleToSearchAccessibilityService? = null
private set
private var isFlashlightOn = false // Simple static state tracking
- fun setCopyTextManager(manager: CopyTextOverlayManager?) {
- instance?.copyTextManager = manager
- }
-
fun triggerCapture() {
android.util.Log.d("CircleToSearch", "triggerCapture static called. instance=${instance != null}")
instance?.performCapture(null)
diff --git a/app/src/main/java/com/akslabs/circletosearch/MainActivity.kt b/app/src/main/java/com/akslabs/circletosearch/MainActivity.kt
index a637f1b..c65ae9d 100644
--- a/app/src/main/java/com/akslabs/circletosearch/MainActivity.kt
+++ b/app/src/main/java/com/akslabs/circletosearch/MainActivity.kt
@@ -96,10 +96,8 @@ class MainActivity : ComponentActivity() {
androidx.compose.animation.Crossfade(targetState = currentScreen) { screen ->
when (screen) {
"settings" -> com.akslabs.circletosearch.ui.OverlaySettingsScreen(onBack = { currentScreen = "home" })
- "ocr_settings" -> com.akslabs.circletosearch.ui.OcrSettingsScreen(onBack = { currentScreen = "home" })
else -> SetupScreen(
- onSettingsClick = { currentScreen = "settings" },
- onOcrSettingsClick = { currentScreen = "ocr_settings" }
+ onSettingsClick = { currentScreen = "settings" }
)
}
}
@@ -112,7 +110,7 @@ class MainActivity : ComponentActivity() {
@OptIn(ExperimentalMaterial3Api::class)
@Composable
-fun SetupScreen(onSettingsClick: () -> Unit, onOcrSettingsClick: () -> Unit) {
+fun SetupScreen(onSettingsClick: () -> Unit) {
val context = LocalContext.current
val lifecycleOwner = androidx.lifecycle.compose.LocalLifecycleOwner.current
val prefs = context.getSharedPreferences("app_prefs", android.content.Context.MODE_PRIVATE)
@@ -486,52 +484,6 @@ fun SetupScreen(onSettingsClick: () -> Unit, onOcrSettingsClick: () -> Unit) {
Spacer(modifier = Modifier.height(12.dp))
- Card(
- onClick = onOcrSettingsClick,
- shape = M3ExpressiveShapes.AsymmetricCard,
- colors = CardDefaults.cardColors(
- containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f)
- ),
- modifier = Modifier
- .fillMaxWidth()
- .m3ExpressivePress()
- ) {
- Row(
- modifier = Modifier.padding(16.dp),
- verticalAlignment = Alignment.CenterVertically
- ) {
- Surface(
- shape = M3ExpressiveShapes.Clover4,
- color = MaterialTheme.colorScheme.tertiaryContainer,
- modifier = Modifier.size(48.dp)
- ) {
- Box(contentAlignment = Alignment.Center) {
- Icon(
- Icons.Default.Settings,
- contentDescription = null,
- tint = MaterialTheme.colorScheme.onTertiaryContainer,
- modifier = Modifier.size(24.dp)
- )
- }
- }
- Spacer(modifier = Modifier.width(16.dp))
- Column(modifier = Modifier.weight(1f)) {
- Text(
- text = stringResource(R.string.label_ocr_settings),
- style = MaterialTheme.typography.titleMedium,
- color = MaterialTheme.colorScheme.onSurface
- )
- Text(
- text = stringResource(R.string.label_ocr_settings_subtitle),
- style = MaterialTheme.typography.bodySmall,
- color = MaterialTheme.colorScheme.onSurfaceVariant
- )
- }
- }
- }
-
- Spacer(modifier = Modifier.height(12.dp))
-
Card(
onClick = {
try {
diff --git a/app/src/main/java/com/akslabs/circletosearch/OverlayActivity.kt b/app/src/main/java/com/akslabs/circletosearch/OverlayActivity.kt
index e1c8cc6..ee03669 100644
--- a/app/src/main/java/com/akslabs/circletosearch/OverlayActivity.kt
+++ b/app/src/main/java/com/akslabs/circletosearch/OverlayActivity.kt
@@ -31,13 +31,11 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.akslabs.circletosearch.data.BitmapRepository
import com.akslabs.circletosearch.ui.CircleToSearchScreen
-import com.akslabs.circletosearch.ui.components.CopyTextOverlayManager
import com.akslabs.circletosearch.ui.theme.CircleToSearchTheme
class OverlayActivity : ComponentActivity() {
private val screenshotBitmap = androidx.compose.runtime.mutableStateOf<android.graphics.Bitmap?>(null)
- private val copyTextManager = androidx.compose.runtime.mutableStateOf<CopyTextOverlayManager?>(null)
private val searchModeOverride = androidx.compose.runtime.mutableStateOf<Boolean?>(null)
override fun onCreate(savedInstanceState: Bundle?) {
@@ -53,13 +51,6 @@ class OverlayActivity : ComponentActivity() {
loadScreenshot()
updateOverride(intent)
- // Initialize manager for Activity-based layout
- copyTextManager.value = CopyTextOverlayManager(
- context = this,
- screenshotBitmap = screenshotBitmap.value
- )
- CircleToSearchAccessibilityService.setCopyTextManager(copyTextManager.value)
-
setContent {
CircleToSearchTheme {
Surface(
@@ -73,10 +64,6 @@ class OverlayActivity : ComponentActivity() {
onClose = {
BitmapRepository.clear()
finish()
- },
- copyTextManager = copyTextManager.value,
- onExitCopyMode = {
- // Copy Mode exited
}
)
}
@@ -92,19 +79,10 @@ class OverlayActivity : ComponentActivity() {
// IMMEDIATE NULLING to prevent flash of previous screen
screenshotBitmap.value = null
- copyTextManager.value?.dismiss()
- copyTextManager.value = null
searchModeOverride.value = null
loadScreenshot()
updateOverride(intent)
-
- // Recreate manager with new screenshot
- copyTextManager.value = CopyTextOverlayManager(
- context = this,
- screenshotBitmap = screenshotBitmap.value
- )
- CircleToSearchAccessibilityService.setCopyTextManager(copyTextManager.value)
}
private fun updateOverride(intent: android.content.Intent) {
@@ -127,8 +105,6 @@ class OverlayActivity : ComponentActivity() {
override fun onDestroy() {
super.onDestroy()
- copyTextManager.value?.dismiss()
- copyTextManager.value = null
if (isFinishing) {
com.akslabs.circletosearch.data.BitmapRepository.clear()
com.akslabs.circletosearch.utils.StorageUtils.clearAppCache(this)
diff --git a/app/src/main/java/com/akslabs/circletosearch/TranslatorOverlayBridge.kt b/app/src/main/java/com/akslabs/circletosearch/TranslatorOverlayBridge.kt
index 86f6535..d2d352d 100644
--- a/app/src/main/java/com/akslabs/circletosearch/TranslatorOverlayBridge.kt
+++ b/app/src/main/java/com/akslabs/circletosearch/TranslatorOverlayBridge.kt
@@ -539,6 +539,17 @@ class TranslatorOverlayBridge(
langStateManager.languageByCode(it)
}
+ /**
+ * The default target language. OCR-only flows (instant text selection over a screenshot)
+ * still need a target because the module's plan runs through the translation pipeline.
+ */
+ fun defaultTargetLanguage(): Language? =
+ if (::langStateManager.isInitialized) {
+ langStateManager.languageByCode(settingsManager.settings.value.defaultTargetLanguageCode)
+ } else {
+ null
+ }
+
private fun currentReadingOrderFor(language: Language?): ReadingOrder? =
if (language?.code == "ja") {
ocrReadingOrder
diff --git a/app/src/main/java/com/akslabs/circletosearch/ocr/TesseractEngine.kt b/app/src/main/java/com/akslabs/circletosearch/ocr/TesseractEngine.kt
deleted file mode 100644
index d773f77..0000000
--- a/app/src/main/java/com/akslabs/circletosearch/ocr/TesseractEngine.kt
+++ /dev/null
@@ -1,282 +0,0 @@
-package com.akslabs.circletosearch.ocr
-
-import android.content.Context
-import android.graphics.Bitmap
-import android.graphics.Rect
-import android.graphics.RectF
-import android.util.Log
-import com.akslabs.circletosearch.R
-import com.akslabs.circletosearch.ui.components.TextNode
-import com.akslabs.circletosearch.ui.components.Word
-import com.googlecode.tesseract.android.TessBaseAPI
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.async
-import kotlinx.coroutines.awaitAll
-import kotlinx.coroutines.coroutineScope
-import kotlinx.coroutines.withContext
-import java.io.File
-import java.io.FileOutputStream
-import java.util.UUID
-
-object TesseractEngine {
- private const val TAG = "TesseractEngine"
- private var isPrepared = false
-
- fun prepareTessData(context: Context): String {
- val filesDir = context.filesDir.absolutePath
- val tessDir = File(filesDir, "tessdata")
- if (!tessDir.exists()) {
- tessDir.mkdirs()
- }
-
- val engFile = File(tessDir, "eng.traineddata")
- if (!engFile.exists()) {
- Log.d(TAG, "Copying eng.traineddata from assets...")
- try {
- context.assets.open("tessdata/eng.traineddata").use { input ->
- FileOutputStream(engFile).use { output ->
- input.copyTo(output)
- }
- }
- } catch (e: Exception) {
- Log.e(TAG, "Failed to copy eng.traineddata: ${e.message}")
- }
- }
- isPrepared = true
- return filesDir
- }
-
- fun getAvailableModels(context: Context): List<String> {
- val dir = File(context.filesDir, "tessdata")
- if (!dir.exists()) {
- prepareTessData(context)
- }
-
- val files = dir.listFiles() ?: return listOf("eng")
- return files.filter { it.name.endsWith(".traineddata") }
- .map { it.name.removeSuffix(".traineddata") }
- .sorted()
- }
-
- fun importModel(context: Context, uri: android.net.Uri, callback: (Boolean, String) -> Unit) {
- try {
- val cursor = context.contentResolver.query(uri, null, null, null, null)
- var fileName = "unknown.traineddata"
- if (cursor != null && cursor.moveToFirst()) {
- val nameIndex = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
- if (nameIndex != -1) {
- fileName = cursor.getString(nameIndex)
- }
- cursor.close()
- }
-
- if (!fileName.endsWith(".traineddata")) {
- callback(false, context.getString(R.string.toast_invalid_model_file))
- return
- }
-
- val tessDir = File(context.filesDir, "tessdata")
- if (!tessDir.exists()) tessDir.mkdirs()
-
- val destFile = File(tessDir, fileName)
-
- context.contentResolver.openInputStream(uri)?.use { input ->
- FileOutputStream(destFile).use { output ->
- input.copyTo(output)
- }
- }
-
- Log.d(TAG, "Imported model to ${destFile.absolutePath}")
- callback(true, context.getString(R.string.toast_model_imported, fileName.removeSuffix(".traineddata").uppercase()))
-
- } catch (e: Exception) {
- Log.e(TAG, "Error importing model: ${e.message}")
- callback(false, context.getString(R.string.toast_model_import_failed))
- }
- }
-
- /**
- * Tiled extraction: Runs multiple OCR passes in parallel and merges results.
- * This mirrors the QR scanner's multi-resolution logic to maximize accuracy.
- */
- suspend fun extractText(context: Context, bitmap: Bitmap): List<TextNode> = coroutineScope {
- val dataPath = withContext(Dispatchers.IO) { prepareTessData(context) }
- val prefs = context.getSharedPreferences("OcrSettings", Context.MODE_PRIVATE)
- val lang = prefs.getString("selected_lang", "eng") ?: "eng"
-
- val w = bitmap.width
- val h = bitmap.height
-
- // Define Tiles (Full + 2x2 Grid with 20% overlap)
- val tiles = mutableListOf<Rect>()
- // 1. Full
- tiles.add(Rect(0, 0, w, h))
-
- // 2. 2x2 Grid (Each tile is ~60% size to provide nice overlap)
- val tw = (w * 0.6f).toInt()
- val th = (h * 0.6f).toInt()
- tiles.add(Rect(0, 0, tw, th)) // Top Left
- tiles.add(Rect(w - tw, 0, w, th)) // Top Right
- tiles.add(Rect(0, h - th, tw, h)) // Bottom Left
- tiles.add(Rect(w - tw, h - th, w, h)) // Bottom Right
-
- val allPasses = tiles.mapIndexed { index, rect ->
- async(Dispatchers.Default) {
- index to internalExtractWords(dataPath, lang, bitmap, rect)
- }
- }
-
- val allWordsWithSource = allPasses.awaitAll().flatMap { (index, words) ->
- words.map { index to it }
- }
-
- // Final Merge & Line Grouping
- groupWordsIntoNodes(allWordsWithSource)
- }
-
- private fun internalExtractWords(dataPath: String, lang: String, fullBitmap: Bitmap, crop: Rect): List<Word> {
- val words = mutableListOf<Word>()
- val tess = TessBaseAPI()
- try {
- if (!tess.init(dataPath, lang)) return emptyList()
-
- // If the crop is a sub-region, create a subset bitmap
- val tileBitmap = if (crop.left == 0 && crop.top == 0 && crop.width() == fullBitmap.width && crop.height() == fullBitmap.height) {
- fullBitmap
- } else {
- Bitmap.createBitmap(fullBitmap, crop.left, crop.top, crop.width(), crop.height())
- }
-
- tess.setImage(tileBitmap)
- tess.getUTF8Text() // Trigger recognition
-
- val iterator = tess.resultIterator ?: run {
- tess.recycle()
- return emptyList()
- }
-
- iterator.begin()
- do {
- val wordText = iterator.getUTF8Text(TessBaseAPI.PageIteratorLevel.RIL_WORD)
- if (wordText.isNullOrBlank()) continue
-
- val wordRectParams = iterator.getBoundingRect(TessBaseAPI.PageIteratorLevel.RIL_WORD)
- ?: iterator.getBoundingBox(TessBaseAPI.PageIteratorLevel.RIL_WORD)
-
- val wRect = if (wordRectParams is Rect) {
- wordRectParams
- } else if (wordRectParams is IntArray) {
- Rect(wordRectParams[0], wordRectParams[1], wordRectParams[2], wordRectParams[3])
- } else {
- continue
- }
-
- if (wRect.isEmpty || wRect.width() < 2) continue
-
- // Adjust coordinates to global screen space
- val globalBounds = RectF(
- (wRect.left + crop.left).toFloat(),
- (wRect.top + crop.top).toFloat(),
- (wRect.right + crop.left).toFloat(),
- (wRect.bottom + crop.top).toFloat()
- )
-
- words.add(
- Word(
- text = wordText,
- index = 0, // Assigned later
- startIndex = 0,
- endIndex = wordText.length,
- bounds = globalBounds
- )
- )
-
- } while (iterator.next(TessBaseAPI.PageIteratorLevel.RIL_WORD))
-
- iterator.delete()
- } catch (e: Exception) {
- Log.e(TAG, "Tile process error: ${e.message}")
- } finally {
- tess.recycle()
- }
- return words
- }
-
- private fun groupWordsIntoNodes(allWordsWithSource: List<Pair<Int, Word>>): List<TextNode> {
- if (allWordsWithSource.isEmpty()) return emptyList()
-
- // 1. Spatial Deduplication
- // We prefer results from quadrants (indices 1-4) over the full pass (index 0)
- // because zoomed-in crops generally yield higher accuracy for small text.
- val uniqueWords = mutableListOf<Word>()
- val sortedByPreference = allWordsWithSource.sortedWith(compareByDescending<Pair<Int, Word>> { it.first }.thenByDescending { it.second.bounds.width() * it.second.bounds.height() })
-
- for (pair in sortedByPreference) {
- val w = pair.second
- val isDuplicate = uniqueWords.any { existing ->
- val overlap = RectF(w.bounds)
- if (overlap.intersect(existing.bounds)) {
- val overlapArea = overlap.width() * overlap.height()
- val wArea = w.bounds.width() * w.bounds.height()
- val textMatch = w.text.equals(existing.text, ignoreCase = true)
- // If text matches and there is significant overlap, it's a duplicate
- overlapArea > wArea * 0.7 && textMatch
- } else false
- }
- if (!isDuplicate) uniqueWords.add(w)
- }
-
- // 2. Line Clustering (Vertical Overlap)
- val sortedWords = uniqueWords.sortedBy { it.bounds.top }
- val lines = mutableListOf<MutableList<Word>>()
-
- if (sortedWords.isNotEmpty()) {
- var currentLine = mutableListOf<Word>()
- currentLine.add(sortedWords[0])
- lines.add(currentLine)
-
- for (i in 1 until sortedWords.size) {
- val prev = currentLine.last()
- val curr = sortedWords[i]
-
- // If vertical centers are close enough, they are on the same line
- val verticalOverlap = Math.abs(curr.bounds.centerY() - prev.bounds.centerY()) < (prev.bounds.height() * 0.6f)
-
- if (verticalOverlap) {
- currentLine.add(curr)
- } else {
- currentLine = mutableListOf(curr)
- lines.add(currentLine)
- }
- }
- }
-
- // 3. Horizontal Sorting & Node Construction
- val result = mutableListOf<TextNode>()
- lines.forEach { lineWords ->
- val finalLineWords = lineWords.sortedBy { it.bounds.left }
- val fullText = finalLineWords.joinToString(" ") { it.text }
-
- val lineBounds = Rect()
- finalLineWords.forEachIndexed { idx, w ->
- // Re-index words for the line
- finalLineWords[idx].copy(index = idx)
-
- val r = Rect()
- w.bounds.roundOut(r)
- if (lineBounds.isEmpty()) lineBounds.set(r) else lineBounds.union(r)
- }
-
- result.add(
- TextNode(
- id = UUID.randomUUID().toString(),
- fullText = fullText,
- bounds = lineBounds,
- words = finalLineWords
- )
- )
- }
-
- return result
- }
-}
diff --git a/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt b/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt
index 9bd35c3..e4780e6 100644
--- a/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt
+++ b/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt
@@ -87,7 +87,6 @@ import androidx.compose.material.icons.filled.Image
import androidx.compose.material.icons.filled.LightMode
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.MoreVert
-import androidx.compose.material.icons.filled.MusicNote
import androidx.compose.material.icons.filled.OpenInNew
import androidx.compose.material.icons.filled.QrCode
import androidx.compose.material.icons.filled.Refresh
@@ -171,6 +170,11 @@ import com.akslabs.circletosearch.ui.qrResultShortLabel
import com.akslabs.circletosearch.utils.UIPreferences
import com.akslabs.circletosearch.ui.components.MoreAppsBottomSheet
import com.akslabs.circletosearch.ui.components.DonateBottomSheet
+import dev.davidv.translator.TranslatorApplication
+import dev.davidv.translator.ui.components.DetectedRegions
+import dev.davidv.translator.ui.components.ImageWordSelection
+import dev.davidv.translator.ui.components.ScanAnimationOverlay
+import dev.davidv.translator.ui.components.WordSelectionOverlay
import android.net.Uri
import kotlinx.coroutines.delay
import kotlinx.coroutines.Dispatchers
@@ -195,15 +199,52 @@ private const val TRANSLATE_TRIGGER_DELAY_MS = 400L
/** Lets the Circle to Search chrome hide before the translator overlay draws. */
private const val TRANSLATE_HIDE_DELAY_MS = 150L
+/**
+ * Runs the translator module's OCR over [bmp] and returns its recognized source words —
+ * no translation, no overlay bitmap. [onRegions] fires as soon as detection boxes arrive
+ * (for the scan animation). Returns null on failure/missing OCR models (toast shown).
+ */
+private suspend fun runInstantScreenshotOcr(
+ context: android.content.Context,
+ bmp: Bitmap,
+ onRegions: (DetectedRegions) -> Unit,
+): ImageWordSelection? {
+ val app = context.applicationContext as? TranslatorApplication ?: return null
+ val coordinator = runCatching { app.translationCoordinator }.getOrNull() ?: return null
+ val target = CircleToSearchAccessibilityService.instance?.defaultTargetLanguage() ?: return null
+ var ocrMissing = false
+ val result = coordinator.ocrWordsOnly(
+ bitmap = bmp,
+ to = target,
+ onDetectedRegions = { boxes, w, h -> onRegions(DetectedRegions(w, h, boxes)) },
+ onOcrUnavailable = { ocrMissing = true },
+ )
+ if (result == null) {
+ if (ocrMissing) {
+ withContext(Dispatchers.Main) {
+ android.widget.Toast.makeText(
+ context,
+ context.getString(dev.davidv.translator.R.string.ocr_models_missing),
+ android.widget.Toast.LENGTH_SHORT,
+ ).show()
+ }
+ }
+ return null
+ }
+ return ImageWordSelection(
+ imageWidth = result.imageWidth,
+ imageHeight = result.imageHeight,
+ sourceWords = result.sourceWords,
+ translatedWords = result.sourceWords,
+ )
+}
+
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CircleToSearchScreen(
screenshot: Bitmap?,
onClose: () -> Unit,
searchModeOverride: Boolean? = null,
- copyTextManager: com.akslabs.circletosearch.ui.components.CopyTextOverlayManager? = null,
- onCopyText: () -> Unit = {},
- onExitCopyMode: () -> Unit = {}
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
@@ -265,16 +306,12 @@ fun CircleToSearchScreen(
}
val searchEngines = preferredOrder
- // Copy Mode internal state
- var isCopyMode by remember { mutableStateOf(false) }
-
// Support Settings Sheet
var showSettingsScreen by remember { mutableStateOf(false) }
// Friendly Message State
var friendlyMessage by remember { mutableStateOf("") }
var isMessageVisible by remember { mutableStateOf(false) }
- var isCopyTextTriggered by remember { mutableStateOf(false) }
// Resizing state
var isResizing by remember { mutableStateOf(false) }
@@ -425,10 +462,14 @@ fun CircleToSearchScreen(
// stays visible as the backdrop under the module's scan/result overlays.
var isTranslatorMode by remember { mutableStateOf(false) }
+ // Instant OCR over the screenshot: scan animation boxes while recognizing, then the
+ // recognized source words — tap a word to select and copy (original text, no translation).
+ var instantWords by remember { mutableStateOf<ImageWordSelection?>(null) }
+ var instantRegions by remember { mutableStateOf<DetectedRegions?>(null) }
+
// Lifecycle reset: When screenshot changes, reset selection and modes
LaunchedEffect(screenshot) {
if (screenshot != null) {
- isCopyMode = false
selectionRect = null
selectedBitmap = null
isSearching = false
@@ -466,6 +507,15 @@ fun CircleToSearchScreen(
}
}
+ // Instant OCR: recognize the screenshot's words as soon as it arrives (module
+ // pipeline, no translation) — shown as tappable words over the frozen capture.
+ LaunchedEffect(screenshot) {
+ instantWords = null
+ instantRegions = null
+ val bmp = screenshot ?: return@LaunchedEffect
+ instantWords = runInstantScreenshotOcr(context, bmp) { instantRegions = it }
+ }
+
// Helper to create and configure WebView
fun createWebView(ctx: android.content.Context, engine: SearchEngine): WebView {
return WebView(ctx).apply {
@@ -561,11 +611,6 @@ fun CircleToSearchScreen(
CircleToSearchAccessibilityService.instance?.closeTranslateOverlay()
return@BackHandler
}
- if (isCopyMode) {
- isCopyMode = false
- onExitCopyMode()
- return@BackHandler
- }
val currentWebView = webViews[selectedEngine]
if (currentWebView != null && currentWebView.canGoBack()) {
currentWebView.goBack()
@@ -910,7 +955,7 @@ fun CircleToSearchScreen(
// Close button for Copy Mode (Top Left)
// Friendly Message Overlay (Top Center)
- if (!isCopyMode && !isTranslatorMode) {
+ if (!isTranslatorMode) {
Box(
modifier = Modifier
.fillMaxSize()
@@ -926,7 +971,7 @@ fun CircleToSearchScreen(
}
// 1. Screenshot Layer
- if (screenshot != null && !isCopyMode) {
+ if (screenshot != null) {
Box(
modifier = Modifier
.fillMaxSize()
@@ -984,7 +1029,7 @@ fun CircleToSearchScreen(
}
// 2. Gradient Border Layer (Overlaying screenshot, clipped to rounded corners)
- if (showGradientBorder && !isCopyMode && !isTranslatorMode) {
+ if (showGradientBorder && !isTranslatorMode) {
androidx.compose.animation.AnimatedVisibility(
visible = isUIVisible,
enter = androidx.compose.animation.fadeIn(animationSpec = tween(700))
@@ -1005,7 +1050,7 @@ fun CircleToSearchScreen(
}
// 3. Drawing Canvas (Interactive Layer)
- if (!isCopyMode && !isTranslatorMode) { Canvas(
+ if (!isTranslatorMode) { Canvas(
modifier = Modifier
.fillMaxSize()
.pointerInput(Unit) {
@@ -1208,9 +1253,32 @@ fun CircleToSearchScreen(
}
+ // Instant OCR overlays: scan animation while recognizing, then tappable source
+ // words over the frozen screenshot. Sits above the screenshot/drawing layers
+ // (later siblings) and below the chrome — drags still reach the drawing canvas,
+ // so circling a region coexists with word selection.
+ if (screenshot != null && !isTranslatorMode && !isEntityExtractMode) {
+ val words = instantWords
+ if (words != null) {
+ WordSelectionOverlay(
+ words = words.sourceWords,
+ imageWidth = words.imageWidth,
+ imageHeight = words.imageHeight,
+ modifier = Modifier.fillMaxSize(),
+ )
+ } else {
+ instantRegions?.let { regions ->
+ ScanAnimationOverlay(
+ regions = regions,
+ modifier = Modifier.fillMaxSize(),
+ )
+ }
+ }
+ }
+
// 4. Header (Top)
androidx.compose.animation.AnimatedVisibility(
- visible = isUIVisible && !isCopyMode && !isEntityExtractMode && !isTranslatorMode,
+ visible = isUIVisible && !isEntityExtractMode && !isTranslatorMode,
enter = androidx.compose.animation.slideInVertically(
initialOffsetY = { -it }, // Commence au-dessus de l'écran (-100%)
animationSpec = tween(500, easing = androidx.compose.animation.core.FastOutSlowInEasing)
@@ -1394,11 +1462,8 @@ fun CircleToSearchScreen(
}
}
// 5. Bottom Bar — Material 3 Expressive two-row card
- // State for Copy Text mode
- var isCopyTextTriggered by remember { mutableStateOf(false) }
-
androidx.compose.animation.AnimatedVisibility(
- visible = isUIVisible && !isCopyMode && !isEntityExtractMode && !isTranslatorMode,
+ visible = isUIVisible && !isEntityExtractMode && !isTranslatorMode,
enter = slideInVertically(
initialOffsetY = { it }, // slides up from below
animationSpec = tween(300, easing = androidx.compose.animation.core.CubicBezierEasing(0f, 0f, 0.2f, 1f))
@@ -1501,21 +1566,6 @@ fun CircleToSearchScreen(
}
}
- // Circular Button: Assist Copy (Music Icon)
- IconButton(
- onClick = {
- haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
- copyTextManager?.setOcrOnlyMode()
- isCopyMode = true
- isCopyTextTriggered = true
- },
- modifier = Modifier
- .size(60.dp)
- .background(MaterialTheme.colorScheme.surfaceContainer, CircleShape),
- ) {
- Icon(Icons.Default.MusicNote, contentDescription = stringResource(R.string.cd_assist_copy), tint = MaterialTheme.colorScheme.onSurface)
- }
-
// Circular Button: Translate
// Short press: freeze CTS (chrome hides, screenshot stays) and run the module's
// translator overlay on the capture; close/back returns to Circle to Search.
@@ -1637,23 +1687,43 @@ fun CircleToSearchScreen(
// }
// }
- // Smart Entity Extractor
+ // Smart Entity Extractor — instant OCR over the screenshot using
+ // the translator module's recognition (no Tesseract, no re-OCR).
BottomBarButton(stringResource(R.string.label_smartscan), { Icon(Icons.Default.Search, null, modifier = Modifier.size(22.dp)) }) {
isEntityExtractMode = true
if (detectedEntities.isEmpty() && !isExtractingEntities) {
isExtractingEntities = true
+ val cachedWords = instantWords?.sourceWords
scope.launch(kotlinx.coroutines.Dispatchers.IO) {
val bmp = screenshot ?: return@launch
- val textNodes = com.akslabs.circletosearch.ocr.TesseractEngine.extractText(context, bmp)
+ val sourceWords = cachedWords ?: runInstantScreenshotOcr(context, bmp) { }?.sourceWords
+ if (sourceWords == null) {
+ kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Main) {
+ isExtractingEntities = false
+ }
+ return@launch
+ }
val entities = mutableListOf<SmartEntity>()
-
+
val urlRegex = android.util.Patterns.WEB_URL.toRegex()
val emailRegex = android.util.Patterns.EMAIL_ADDRESS.toRegex()
val phoneRegexLine = Regex("""(\+?[\d\s\-\(\).]{9,20})""")
val upiRegex = Regex("""[a-zA-Z0-9.\-_]{2,256}@[a-zA-Z]{2,64}""")
- textNodes.forEach { node ->
- val lineText = node.fullText
+ // Group recognized words into lines; phone matches map into
+ // the line's union bounds by character ratio, like before.
+ sourceWords.groupBy { it.lineIndex }.forEach { (_, lineWords) ->
+ val lineText = lineWords.joinToString(" ") { it.text }
+ var left = Float.MAX_VALUE
+ var top = Float.MAX_VALUE
+ var right = -Float.MAX_VALUE
+ var bottom = -Float.MAX_VALUE
+ lineWords.forEach { w ->
+ left = min(left, w.bounds.cx - w.bounds.width / 2f)
+ top = min(top, w.bounds.cy - w.bounds.height / 2f)
+ right = max(right, w.bounds.cx + w.bounds.width / 2f)
+ bottom = max(bottom, w.bounds.cy + w.bounds.height / 2f)
+ }
phoneRegexLine.findAll(lineText).forEach { match ->
val phoneCandidate = match.value.trim()
if (phoneCandidate.count { it.isDigit() } >= 10) {
@@ -1662,20 +1732,26 @@ fun CircleToSearchScreen(
val ratioStart = startIdx.toFloat() / lineText.length.coerceAtLeast(1)
val ratioEnd = endIdx.toFloat() / lineText.length.coerceAtLeast(1)
val entityBounds = android.graphics.RectF(
- node.bounds.left.toFloat() + (ratioStart * node.bounds.width().toFloat()),
- node.bounds.top.toFloat(),
- node.bounds.left.toFloat() + (ratioEnd * node.bounds.width().toFloat()),
- node.bounds.bottom.toFloat()
+ left + (ratioStart * (right - left)),
+ top,
+ left + (ratioEnd * (right - left)),
+ bottom
)
entities.add(SmartEntity.Phone(phoneCandidate, entityBounds, context.getString(R.string.entity_type_phone)))
}
}
- node.words.forEach { word ->
- val txt = word.text.trim()
- if (emailRegex.matches(txt)) entities.add(SmartEntity.Email(txt, word.bounds, context.getString(R.string.entity_type_email)))
- else if (upiRegex.matches(txt)) entities.add(SmartEntity.Upi(txt, word.bounds, context.getString(R.string.entity_type_upi)))
- else if (urlRegex.matches(txt)) entities.add(SmartEntity.Url(txt, word.bounds, context.getString(R.string.entity_type_link)))
- }
+ }
+ sourceWords.forEach { word ->
+ val txt = word.text.trim()
+ val wordBounds = android.graphics.RectF(
+ word.bounds.cx - word.bounds.width / 2f,
+ word.bounds.cy - word.bounds.height / 2f,
+ word.bounds.cx + word.bounds.width / 2f,
+ word.bounds.cy + word.bounds.height / 2f
+ )
+ if (emailRegex.matches(txt)) entities.add(SmartEntity.Email(txt, wordBounds, context.getString(R.string.entity_type_email)))
+ else if (upiRegex.matches(txt)) entities.add(SmartEntity.Upi(txt, wordBounds, context.getString(R.string.entity_type_upi)))
+ else if (urlRegex.matches(txt)) entities.add(SmartEntity.Url(txt, wordBounds, context.getString(R.string.entity_type_link)))
}
kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Main) {
detectedEntities = entities
@@ -1690,13 +1766,6 @@ fun CircleToSearchScreen(
// showDonateSheet = true
// }
- // Copy Text
- BottomBarButton(stringResource(R.string.label_copy_text), { Icon(painterResource(id = com.akslabs.circletosearch.R.drawable.ocr), null, modifier = Modifier.size(20.dp)) }) {
- copyTextManager?.setOcrOnlyMode()
- isCopyMode = true
- isCopyTextTriggered = true
- }
-
// QR Scan
BottomBarButton(stringResource(R.string.label_scan_qr), { Icon(Icons.Default.QrCode, null) }) {
qrScanBitmap = selectedBitmap ?: screenshot
@@ -1735,23 +1804,8 @@ fun CircleToSearchScreen(
)
}
- // Copy Text overlay integration (Activity-based)
- if (isCopyMode && copyTextManager != null) {
- AndroidView(
- factory = { ctx ->
- copyTextManager.getOverlayView(onDismiss = {
- isCopyMode = false
- onExitCopyMode()
- })
- },
- modifier = Modifier
- .fillMaxSize()
- .zIndex(150f)
- )
- }
-
// 4. Selection Actions (Share) — Positioned at the very end for absolute top-layer rendering
- if (selectionRect != null && selectionAnim.value == 1f && !isCopyMode && !isTranslatorMode) {
+ if (selectionRect != null && selectionAnim.value == 1f && !isTranslatorMode) {
val rect = selectionRect!!
val density = androidx.compose.ui.platform.LocalDensity.current
val leftPx = rect.left.toFloat()
@@ -1912,7 +1966,7 @@ fun CircleToSearchScreen(
}
// --- NEW: QR Overlay Chips (High Layer) ---
- if (screenshot != null && !isCopyMode && !isTranslatorMode) {
+ if (screenshot != null && !isTranslatorMode) {
BoxWithConstraints(modifier = Modifier.fillMaxSize().zIndex(2500f)) {
val screenWidth = maxWidth
val screenHeight = maxHeight
@@ -1987,7 +2041,7 @@ fun CircleToSearchScreen(
}
// --- Phase 44: Smart Entity Extractor Overlay Chips ---
- if (isEntityExtractMode && screenshot != null && !isCopyMode) {
+ if (isEntityExtractMode && screenshot != null) {
BoxWithConstraints(modifier = Modifier.fillMaxSize().zIndex(2600f)) {
val screenWidth = maxWidth
val screenHeight = maxHeight
diff --git a/app/src/main/java/com/akslabs/circletosearch/ui/OcrSettingsScreen.kt b/app/src/main/java/com/akslabs/circletosearch/ui/OcrSettingsScreen.kt
deleted file mode 100644
index 93e9222..0000000
--- a/app/src/main/java/com/akslabs/circletosearch/ui/OcrSettingsScreen.kt
+++ /dev/null
@@ -1,230 +0,0 @@
-package com.akslabs.circletosearch.ui
-
-import android.content.Context
-import android.net.Uri
-import android.util.Log
-import android.widget.Toast
-import androidx.activity.compose.rememberLauncherForActivityResult
-import androidx.activity.result.contract.ActivityResultContracts
-import androidx.compose.foundation.clickable
-import androidx.compose.foundation.layout.*
-import androidx.compose.foundation.lazy.LazyColumn
-import androidx.compose.foundation.lazy.items
-import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.foundation.text.ClickableText
-import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.automirrored.filled.ArrowBack
-import androidx.compose.material.icons.filled.*
-import androidx.compose.material3.*
-import androidx.compose.runtime.*
-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.platform.LocalContext
-import androidx.compose.ui.platform.LocalUriHandler
-import androidx.compose.ui.text.AnnotatedString
-import androidx.compose.ui.text.SpanStyle
-import androidx.compose.ui.text.buildAnnotatedString
-import androidx.compose.ui.text.font.FontWeight
-import androidx.compose.ui.text.style.TextDecoration
-import androidx.compose.ui.text.withStyle
-import androidx.compose.ui.res.stringResource
-import androidx.compose.ui.unit.*
-import com.akslabs.circletosearch.R
-import com.akslabs.circletosearch.ocr.TesseractEngine
-import java.io.File
-import java.io.FileOutputStream
-import java.util.Locale
-
-@OptIn(ExperimentalMaterial3Api::class)
-@Composable
-fun OcrSettingsScreen(onBack: () -> Unit) {
- val context = LocalContext.current
- val prefs = context.getSharedPreferences("OcrSettings", Context.MODE_PRIVATE)
-
- var currentLang by remember { mutableStateOf(prefs.getString("selected_lang", "eng") ?: "eng") }
- var availableModels by remember { mutableStateOf(TesseractEngine.getAvailableModels(context)) }
- var isNoteVisible by remember { mutableStateOf(prefs.getBoolean("ocr_note_dismissed", false).not()) }
- val uriHandler = LocalUriHandler.current
-
- androidx.activity.compose.BackHandler(onBack = onBack)
-
- val filePickerLauncher = rememberLauncherForActivityResult(
- contract = ActivityResultContracts.GetContent()
- ) { uri: Uri? ->
- if (uri != null) {
- TesseractEngine.importModel(context, uri) { success, msg ->
- Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
- if (success) {
- availableModels = TesseractEngine.getAvailableModels(context)
- }
- }
- }
- }
-
- Scaffold(
- topBar = {
- TopAppBar(
- title = { Text(stringResource(R.string.title_ocr_settings), fontWeight = FontWeight.Bold) },
- navigationIcon = {
- IconButton(onClick = onBack) {
- Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.cd_back))
- }
- },
- colors = TopAppBarDefaults.topAppBarColors(
- containerColor = MaterialTheme.colorScheme.surface,
- titleContentColor = MaterialTheme.colorScheme.onSurface
- )
- )
- },
- floatingActionButton = {
- ExtendedFloatingActionButton(
- onClick = { filePickerLauncher.launch("*/*") },
- icon = { Icon(Icons.Default.Add, contentDescription = stringResource(R.string.cd_import_model)) },
- text = { Text(stringResource(R.string.btn_import_model)) }
- )
- }
- ) { padding ->
- LazyColumn(
- modifier = Modifier
- .fillMaxSize()
- .padding(padding),
- contentPadding = PaddingValues(bottom = 80.dp)
- ) {
- item {
- if (isNoteVisible) {
- Card(
- modifier = Modifier
- .fillMaxWidth()
- .padding(16.dp),
- colors = CardDefaults.cardColors(
- containerColor = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.7f)
- ),
- shape = RoundedCornerShape(24.dp)
- ) {
- Box(modifier = Modifier.padding(16.dp)) {
- Column(modifier = Modifier.fillMaxWidth().padding(end = 32.dp)) {
- Row(verticalAlignment = Alignment.CenterVertically) {
- Icon(
- imageVector = Icons.Default.Info,
- contentDescription = null,
- tint = MaterialTheme.colorScheme.primary,
- modifier = Modifier.size(20.dp)
- )
- Spacer(modifier = Modifier.width(8.dp))
- Text(
- text = stringResource(R.string.title_language_models_guide),
- style = MaterialTheme.typography.titleSmall,
- fontWeight = FontWeight.Bold,
- color = MaterialTheme.colorScheme.primary
- )
- }
-
- Spacer(modifier = Modifier.height(8.dp))
-
- val annotatedString = buildAnnotatedString {
- append(stringResource(R.string.info_ocr_guide_part1))
-
- pushStringAnnotation(tag = "URL", annotation = "https://t.me/AKSLabs")
- withStyle(style = SpanStyle(
- color = MaterialTheme.colorScheme.primary,
- fontWeight = FontWeight.Bold,
- textDecoration = TextDecoration.Underline
- )) {
- append(stringResource(R.string.info_ocr_guide_telegram_link))
- }
- pop()
-
- append(stringResource(R.string.info_ocr_guide_part2))
- }
-
- ClickableText(
- text = annotatedString,
- style = MaterialTheme.typography.bodyMedium.copy(
- color = MaterialTheme.colorScheme.onSecondaryContainer
- ),
- onClick = { offset ->
- annotatedString.getStringAnnotations(tag = "URL", start = offset, end = offset)
- .firstOrNull()?.let { annotation ->
- uriHandler.openUri(annotation.item)
- }
- }
- )
- }
-
- IconButton(
- onClick = {
- isNoteVisible = false
- prefs.edit().putBoolean("ocr_note_dismissed", true).apply()
- },
- modifier = Modifier
- .align(Alignment.TopEnd)
- .size(24.dp)
- ) {
- Icon(
- imageVector = Icons.Default.Close,
- contentDescription = stringResource(R.string.cd_dismiss),
- modifier = Modifier.size(16.dp)
- )
- }
- }
- }
- }
- }
-
- item {
- Text(
- text = stringResource(R.string.title_installed_models),
- style = MaterialTheme.typography.titleMedium,
- fontWeight = FontWeight.Bold,
- modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
- )
- }
-
- items(availableModels) { lang ->
- val isSelected = lang == currentLang
- Card(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = 16.dp, vertical = 4.dp),
- shape = RoundedCornerShape(16.dp),
- colors = CardDefaults.cardColors(
- containerColor = if (isSelected)
- MaterialTheme.colorScheme.primaryContainer
- else
- MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f)
- )
- ) {
- ListItem(
- headlineContent = { Text(lang.uppercase(), fontWeight = FontWeight.Bold) },
- supportingContent = { Text("$lang.traineddata", style = MaterialTheme.typography.labelSmall) },
- leadingContent = {
- Icon(
- Icons.Default.Translate,
- contentDescription = null,
- tint = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
- )
- },
- trailingContent = {
- if (isSelected) {
- Icon(
- Icons.Default.CheckCircle,
- contentDescription = stringResource(R.string.cd_selected),
- tint = MaterialTheme.colorScheme.primary
- )
- }
- },
- modifier = Modifier.clickable {
- currentLang = lang
- prefs.edit().putString("selected_lang", lang).apply()
- },
- colors = ListItemDefaults.colors(
- containerColor = Color.Transparent
- )
- )
- }
- }
- }
- }
-}
diff --git a/app/src/main/java/com/akslabs/circletosearch/ui/components/CopyTextOverlayManager.kt b/app/src/main/java/com/akslabs/circletosearch/ui/components/CopyTextOverlayManager.kt
deleted file mode 100644
index a3cb1a8..0000000
--- a/app/src/main/java/com/akslabs/circletosearch/ui/components/CopyTextOverlayManager.kt
+++ /dev/null
@@ -1,546 +0,0 @@
-/*
- * Copyright (C) 2025 AKS-Labs
- * SPDX-License-Identifier: GPL-3.0-or-later
- */
-
-package com.akslabs.circletosearch.ui.components
-
-import android.annotation.SuppressLint
-import android.content.ClipData
-import android.content.ClipboardManager
-import android.content.Context
-import android.content.Intent
-import android.graphics.*
-import android.net.Uri
-import android.util.Log
-import android.view.*
-import android.widget.FrameLayout
-import android.widget.Toast
-import androidx.compose.ui.platform.ComposeView
-import androidx.compose.runtime.*
-import androidx.compose.ui.Modifier
-import androidx.compose.foundation.layout.*
-import androidx.compose.material3.*
-import androidx.compose.ui.unit.dp
-import androidx.compose.ui.graphics.Color as ComposeColor
-import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.filled.Close
-import androidx.compose.material.icons.filled.MoreVert
-import androidx.compose.foundation.background
-import androidx.compose.foundation.shape.CircleShape
-import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.ui.Alignment
-import com.akslabs.circletosearch.R
-import com.akslabs.circletosearch.data.BitmapRepository
-import com.akslabs.circletosearch.ocr.TesseractEngine
-import com.akslabs.circletosearch.utils.ImageUtils
-import kotlinx.coroutines.*
-import java.util.UUID
-
-private enum class ToolbarAction { COPY, SHARE, TRANSLATE, ALL, CANCEL }
-
-/** Simple holder for a floating-toolbar button's label and screen hit-rect. */
-private class ToolbarButton(val label: String, val rect: Rect, val action: ToolbarAction)
-
-/**
- * Manages the dim+punch-out Copy Text overlay with OCR capabilities.
- */
-class CopyTextOverlayManager(
- private val context: Context,
- private val screenshotBitmap: android.graphics.Bitmap?
-) {
- private var dimView: DimPunchOutView? = null
- private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
- private var scanJob: Job? = null
- private var onDismissCallback: (() -> Unit)? = null
-
- // State for Compose and Drawing
- private val isScanning = mutableStateOf(false)
- private val textNodes = mutableStateListOf<TextNode>()
- private var allWords: List<Word> = emptyList()
-
- // Status message for the user
- private val statusMessage = mutableStateOf<String?>(null)
-
- fun setOcrOnlyMode() {
- textNodes.clear()
- allWords = emptyList()
- statusMessage.value = null
- }
-
- private fun updateAllWords() {
- allWords = textNodes.flatMap { node ->
- node.words.map { word ->
- word
- }
- }
- }
-
- // Selection state
- private var globalSelectionStart: Int = -1
- private var globalSelectionEnd: Int = -1
-
- fun getOverlayView(onDismiss: () -> Unit): View {
- onDismissCallback = onDismiss
-
- // Reset interactive state
- globalSelectionStart = -1
- globalSelectionEnd = -1
-
- val container = FrameLayout(context)
-
- val view = DimPunchOutView(context)
- dimView = view
- container.addView(view)
-
- val topBar = ComposeView(context).apply {
- setContent {
- MaterialTheme {
- Box(modifier = Modifier.fillMaxSize()) {
- TopBarUI(onClose = { dismiss() })
-
- if (isScanning.value) {
- Column(
- modifier = Modifier.align(Alignment.Center),
- horizontalAlignment = Alignment.CenterHorizontally
- ) {
- CircularProgressIndicator(
- modifier = Modifier.size(48.dp),
- color = ComposeColor.White,
- strokeWidth = 4.dp
- )
- Spacer(Modifier.height(16.dp))
- Text(
- context.getString(R.string.label_scanning_text),
- style = MaterialTheme.typography.titleMedium,
- color = ComposeColor.White,
- modifier = Modifier
- .background(ComposeColor.Black.copy(alpha = 0.4f), RoundedCornerShape(8.dp))
- .padding(horizontal = 12.dp, vertical = 6.dp)
- )
- }
- }
-
- statusMessage.value?.let { msg ->
- Box(
- modifier = Modifier
- .align(Alignment.BottomCenter)
- .padding(bottom = 100.dp)
- .background(ComposeColor.Black.copy(alpha = 0.7f), RoundedCornerShape(16.dp))
- .padding(horizontal = 20.dp, vertical = 10.dp)
- ) {
- Text(
- msg,
- color = ComposeColor.White,
- style = MaterialTheme.typography.bodyMedium
- )
- }
- }
- }
- }
- }
- }
- container.addView(topBar)
-
- scanNodes(view)
- return container
- }
-
- @Composable
- private fun TopBarUI(onClose: () -> Unit) {
- val filePickerLauncher = androidx.activity.compose.rememberLauncherForActivityResult(
- contract = androidx.activity.result.contract.ActivityResultContracts.GetContent()
- ) { uri: android.net.Uri? ->
- if (uri != null) {
- TesseractEngine.importModel(context, uri) { success, msg ->
- android.widget.Toast.makeText(context, msg, android.widget.Toast.LENGTH_SHORT).show()
- }
- }
- }
-
- Row(
- modifier = Modifier
- .fillMaxWidth()
- .statusBarsPadding()
- .padding(16.dp),
- horizontalArrangement = Arrangement.SpaceBetween,
- verticalAlignment = Alignment.CenterVertically
- ) {
- IconButton(
- onClick = onClose,
- modifier = Modifier
- .background(ComposeColor.Black.copy(alpha = 0.35f), CircleShape)
- .size(40.dp)
- ) {
- Icon(Icons.Default.Close, contentDescription = context.getString(R.string.cd_exit_copy_mode), tint = ComposeColor.White)
- }
-
- Spacer(modifier = Modifier.weight(1f))
-
- Box {
- var showMenu by remember { mutableStateOf(false) }
- IconButton(
- onClick = { showMenu = true },
- modifier = Modifier
- .background(ComposeColor.Black.copy(alpha = 0.35f), CircleShape)
- .size(40.dp)
- ) {
- Icon(Icons.Default.MoreVert, contentDescription = context.getString(R.string.cd_menu), tint = ComposeColor.White)
- }
-
- DropdownMenu(
- expanded = showMenu,
- onDismissRequest = { showMenu = false },
- shape = RoundedCornerShape(28.dp),
- tonalElevation = 6.dp
- ) {
- DropdownMenuItem(
- text = { Text(context.getString(R.string.menu_select_language_model)) },
- onClick = {
- showMenu = false
- showLanguageModelSelector()
- }
- )
- DropdownMenuItem(
- text = { Text(context.getString(R.string.menu_import_model)) },
- onClick = {
- showMenu = false
- filePickerLauncher.launch("*/*")
- }
- )
- }
- }
- }
- }
-
- private fun Int.toComposeColor(): ComposeColor = ComposeColor(this)
-
- private fun showLanguageModelSelector() {
- val models = TesseractEngine.getAvailableModels(context)
- val prefs = context.getSharedPreferences("OcrSettings", Context.MODE_PRIVATE)
- val current = prefs.getString("selected_lang", "eng") ?: "eng"
-
- android.app.AlertDialog.Builder(context)
- .setTitle(context.getString(R.string.title_select_ocr_model))
- .setSingleChoiceItems(models.toTypedArray(), models.indexOf(current)) { dialog, which ->
- val selected = models[which]
- prefs.edit().putString("selected_lang", selected).apply()
- Toast.makeText(context, context.getString(R.string.toast_ocr_model_selected, selected.uppercase()), Toast.LENGTH_SHORT).show()
- dialog.dismiss()
- rescanNodes()
- }
- .setNegativeButton(context.getString(R.string.cancel), null)
- .show()
- }
-
- fun dismiss() {
- scanJob?.cancel()
- dimView = null
- onDismissCallback?.invoke()
- onDismissCallback = null
- }
-
- fun rescanNodes() {
- dimView?.let { scanNodes(it) }
- }
-
- private fun scanNodes(view: View) {
- scanJob?.cancel()
- statusMessage.value = null
- scanJob = scope.launch(Dispatchers.Main) {
- isScanning.value = true
- val bitmap = screenshotBitmap ?: BitmapRepository.getScreenshot()
-
- if (bitmap == null) {
- isScanning.value = false
- view.invalidate()
- return@launch
- }
-
- try {
- // OCR scan runs on background thread
- val ocrNodes = TesseractEngine.extractText(context, bitmap)
-
- val sortedNodes = ocrNodes.sortedWith(compareBy({ it.bounds.top }, { it.bounds.left }))
- textNodes.clear()
- textNodes.addAll(sortedNodes)
- updateAllWords()
-
- if (textNodes.isEmpty()) {
- statusMessage.value = context.getString(R.string.label_no_text_found)
- }
-
- Log.d("CopyTextOverlay", "Capture complete: ${textNodes.size} total nodes")
- } catch (e: Exception) {
- Log.e("CopyTextOverlay", "Extraction failed: ${e.message}")
- } finally {
- isScanning.value = false
- view.invalidate()
- }
- }
- }
-
- @SuppressLint("ClickableViewAccessibility")
- inner class DimPunchOutView(context: Context) : View(context) {
- private val density = resources.displayMetrics.density
- private val viewLocation = IntArray(2)
-
- private val dimPaint = Paint().apply { color = Color.BLACK; alpha = 38; isAntiAlias = false }
- private val selectedWordPaint = Paint().apply {
- color = try { context.getColor(android.R.color.system_accent1_200) } catch(e: Exception) { Color.parseColor("#D0BCFF") }
- alpha = 150; isAntiAlias = true
- }
- private val handlePaint = Paint().apply { color = Color.parseColor("#6750A4"); isAntiAlias = true }
- private val toolbarBgPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.parseColor("#F3EDF7") }
- private val toolbarActionPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.parseColor("#6750A4") }
- private val clearPaint = Paint().apply {
- xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
- isAntiAlias = true
- }
-
- private var dragHandleType = 0
- private var toolbarButtons: List<ToolbarButton> = emptyList()
- private var toolbarRect = RectF()
- private var dragHandleRect = RectF()
- private var toolbarOffsetX = 0f
- private var toolbarOffsetY = 0f
- private var isDraggingToolbar = false
- private var toolbarInitialized = false
- private var lastTouchX = 0f
- private var lastTouchY = 0f
-
- init {
- setLayerType(LAYER_TYPE_SOFTWARE, null)
- }
-
- private fun toLocal(screenRect: Rect): RectF {
- getLocationOnScreen(viewLocation)
- return RectF(
- (screenRect.left - viewLocation[0]).toFloat(),
- (screenRect.top - viewLocation[1]).toFloat(),
- (screenRect.right - viewLocation[0]).toFloat(),
- (screenRect.bottom - viewLocation[1]).toFloat()
- )
- }
-
- private fun toLocal(screenRectF: RectF): RectF {
- getLocationOnScreen(viewLocation)
- return RectF(
- screenRectF.left - viewLocation[0],
- screenRectF.top - viewLocation[1],
- screenRectF.right - viewLocation[0],
- screenRectF.bottom - viewLocation[1]
- )
- }
-
- private fun toScreenX(localX: Float): Float { getLocationOnScreen(viewLocation); return localX + viewLocation[0] }
- private fun toScreenY(localY: Float): Float { getLocationOnScreen(viewLocation); return localY + viewLocation[1] }
-
- override fun onDraw(canvas: Canvas) {
- val saveCount = canvas.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null)
- canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), dimPaint)
-
- textNodes.forEach { node ->
- val localBounds = toLocal(node.bounds)
- localBounds.inset(-12f, -8f)
- canvas.drawRoundRect(localBounds, 12f, 12f, clearPaint)
- }
-
- if (globalSelectionStart != -1 && globalSelectionEnd != -1) {
- val start = globalSelectionStart.coerceAtMost(globalSelectionEnd)
- val end = globalSelectionStart.coerceAtLeast(globalSelectionEnd)
- val selectedWords = (start..end).mapNotNull { allWords.getOrNull(it) }
-
- val highlightPath = Path()
- selectedWords.groupBy { (it.bounds.centerY() / 20).toInt() }.forEach { (_, wordsInLine) ->
- if (wordsInLine.isEmpty()) return@forEach
- val first = wordsInLine.minBy { it.bounds.left }
- val last = wordsInLine.maxBy { it.bounds.right }
- val lineRect = RectF(first.bounds.left, wordsInLine.minOf { it.bounds.top }, last.bounds.right, wordsInLine.maxOf { it.bounds.bottom })
- val localHighlight = toLocal(lineRect)
- localHighlight.inset(-12f, -8f)
- highlightPath.addRoundRect(localHighlight, 8f, 8f, Path.Direction.CW)
- }
- canvas.drawPath(highlightPath, selectedWordPaint)
-
- val startLocal = toLocal(allWords[start].bounds)
- val endLocal = toLocal(allWords[end].bounds)
- drawHandle(canvas, startLocal.left, startLocal.top, true)
- drawHandle(canvas, endLocal.right, endLocal.bottom, false)
-
- val encompassing = RectF(allWords[start].bounds)
- selectedWords.forEach { encompassing.union(it.bounds) }
- drawFloatingToolbar(canvas, toLocal(encompassing))
- }
- canvas.restoreToCount(saveCount)
- }
-
- private fun drawHandle(canvas: Canvas, x: Float, y: Float, isStart: Boolean) {
- canvas.drawCircle(x, y, 18f, handlePaint)
- if (isStart) canvas.drawRect(x - 2f, y, x + 2f, y + 40f, handlePaint)
- else canvas.drawRect(x - 2f, y - 40f, x + 2f, y, handlePaint)
- }
-
- private fun drawFloatingToolbar(canvas: Canvas, anchor: RectF) {
- val toolbarItems = listOf(
- ToolbarAction.COPY to context.getString(R.string.toolbar_btn_copy),
- ToolbarAction.SHARE to context.getString(R.string.toolbar_btn_share),
- ToolbarAction.TRANSLATE to context.getString(R.string.toolbar_btn_translate),
- ToolbarAction.ALL to context.getString(R.string.toolbar_btn_all),
- ToolbarAction.CANCEL to context.getString(R.string.toolbar_btn_cancel)
- )
- val buttonLabels = toolbarItems.map { it.second }
- val btnPadding = 16f * density
- val btnHeight = 36f * density
- val btnSpacing = 6f * density
- val m = 10f * density
-
- toolbarActionPaint.textSize = 30f
- val labelWidths = buttonLabels.map { toolbarActionPaint.measureText(it) + btnPadding * 2 }
- val dragHandleWidth = 24f * density
- val totalWidth = labelWidths.sum() + (buttonLabels.size - 1) * btnSpacing + m * 2 + dragHandleWidth + btnSpacing
-
- val tx = ((width - totalWidth) / 2) + toolbarOffsetX
- if (!toolbarInitialized) {
- toolbarOffsetY = anchor.top - (btnHeight + m * 2) - 32f
- if (toolbarOffsetY < 150f) toolbarOffsetY = anchor.bottom + 32f
- toolbarInitialized = true
- }
- val ty = toolbarOffsetY
- toolbarRect.set(tx, ty, tx + totalWidth, ty + btnHeight + m * 2)
-
- val dynamicSurface = try { context.getColor(android.R.color.system_surface_container_light) } catch(e: Exception) { Color.parseColor("#F3EDF7") }
- val shadowPaint = Paint(toolbarBgPaint).apply { setShadowLayer(12f * density, 0f, 4f * density, Color.BLACK and 0x2F000000) }
- canvas.drawRoundRect(toolbarRect, 22f * density, 22f * density, shadowPaint)
- canvas.drawRoundRect(toolbarRect, 22f * density, 22f * density, toolbarBgPaint.apply { color = dynamicSurface })
-
- val dx = tx + m
- dragHandleRect.set(dx, ty + m, dx + dragHandleWidth, ty + m + btnHeight)
- val hPaint = Paint(toolbarActionPaint).apply { color = Color.LTGRAY; style = Paint.Style.FILL }
- canvas.drawRoundRect(dx + 8f * density, ty + m + 8f * density, dx + 16f * density, ty + m + btnHeight - 8f * density, 4f * density, 4f * density, hPaint)
-
- var currentX = tx + m + dragHandleWidth + btnSpacing
- val newButtons = mutableListOf<ToolbarButton>()
- buttonLabels.forEachIndexed { i, label ->
- val bWidth = labelWidths[i]
- val bRect = RectF(currentX, ty + m, currentX + bWidth, ty + m + btnHeight)
- val dynamicPrimary = try { context.getColor(android.R.color.system_accent1_600) } catch(e: Exception) { Color.parseColor("#6750A4") }
- canvas.drawRoundRect(bRect, btnHeight / 2, btnHeight / 2, handlePaint.apply { color = dynamicPrimary })
-
- val fontMetrics = toolbarActionPaint.fontMetrics
- val textOffset = ((fontMetrics.descent - fontMetrics.ascent) / 2) - fontMetrics.descent
- canvas.drawText(label, bRect.centerX(), bRect.centerY() + textOffset, toolbarActionPaint.apply {
- color = Color.WHITE; style = Paint.Style.FILL; textSize = 30f; typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD); textAlign = Paint.Align.CENTER
- })
- newButtons.add(ToolbarButton(label, Rect(bRect.left.toInt(), bRect.top.toInt(), bRect.right.toInt(), bRect.bottom.toInt()), toolbarItems[i].first))
- currentX += bWidth + btnSpacing
- }
- toolbarButtons = newButtons
- }
-
- override fun onTouchEvent(event: MotionEvent): Boolean {
- val lx = event.x; val ly = event.y
- when (event.action) {
- MotionEvent.ACTION_DOWN -> {
- lastTouchX = lx; lastTouchY = ly
- for (btn in toolbarButtons) {
- if (Rect(btn.rect).apply { inset(-24, -24) }.contains(lx.toInt(), ly.toInt())) {
- handleToolbarAction(btn.action); return true
- }
- }
- if (dragHandleRect.contains(lx, ly)) { isDraggingToolbar = true; return true }
- if (globalSelectionStart != -1) {
- val start = globalSelectionStart.coerceAtMost(globalSelectionEnd)
- val end = globalSelectionStart.coerceAtLeast(globalSelectionEnd)
- val startLocal = toLocal(allWords[start].bounds)
- val endLocal = toLocal(allWords[end].bounds)
- if (isPointNear(lx, ly, startLocal.left, startLocal.top)) { dragHandleType = 1; return true }
- if (isPointNear(lx, ly, endLocal.right, endLocal.bottom)) { dragHandleType = 2; return true }
- }
- val sx = toScreenX(lx); val sy = toScreenY(ly)
- val nearest = findNearestWordGlobal(sx, sy)
- if (nearest != -1) {
- globalSelectionStart = nearest; globalSelectionEnd = nearest
- performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); invalidate(); return true
- } else { globalSelectionStart = -1; globalSelectionEnd = -1; invalidate() }
- }
- MotionEvent.ACTION_MOVE -> {
- val dx = lx - lastTouchX; val dy = ly - lastTouchY
- lastTouchX = lx; lastTouchY = ly
- if (isDraggingToolbar) { toolbarOffsetX += dx; toolbarOffsetY += dy; invalidate(); return true }
- val sx = toScreenX(lx); val sy = toScreenY(ly)
- if (dragHandleType != 0) {
- val nearest = findNearestWordGlobal(sx, sy)
- if (nearest != -1) {
- if (dragHandleType == 1) globalSelectionStart = nearest else globalSelectionEnd = nearest
- invalidate()
- }
- return true
- } else if (globalSelectionStart != -1) {
- val nearest = findNearestWordGlobal(sx, sy)
- if (nearest != -1) { globalSelectionEnd = nearest; invalidate(); return true }
- }
- }
- MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
- isDraggingToolbar = false; dragHandleType = 0; invalidate()
- }
- }
- return true
- }
-
- private fun findNearestWordGlobal(sx: Float, sy: Float): Int {
- var minDist = Float.MAX_VALUE; var nearest = -1
- allWords.forEachIndexed { idx, word ->
- val dx = sx - word.bounds.centerX(); val dy = sy - word.bounds.centerY()
- val d = dx * dx + dy * dy
- if (d < minDist) { minDist = d; nearest = idx }
- }
- return if (minDist < 600 * 600) nearest else -1
- }
-
- private fun isPointNear(px: Float, py: Float, x: Float, y: Float): Boolean {
- val dx = px - x; val dy = py - y
- return dx * dx + dy * dy < 80 * 80
- }
-
- private fun handleToolbarAction(action: ToolbarAction) {
- val start = globalSelectionStart.coerceAtMost(globalSelectionEnd)
- val end = globalSelectionStart.coerceAtLeast(globalSelectionEnd)
- if (start == -1) return
- val selectedText = (start..end).mapNotNull { allWords.getOrNull(it) }.joinToString(" ") { it.text }
-
- when (action) {
- ToolbarAction.COPY -> {
- val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
- clipboard.setPrimaryClip(ClipData.newPlainText("Copied Text", selectedText))
- Toast.makeText(context, context.getString(R.string.toast_text_copied), Toast.LENGTH_SHORT).show()
- dismiss()
- }
- ToolbarAction.SHARE -> {
- val intent = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
- type = "text/plain"; putExtra(android.content.Intent.EXTRA_TEXT, selectedText); addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
- }
- context.startActivity(android.content.Intent.createChooser(intent, context.getString(R.string.share_chooser_text)).apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) })
- dismiss()
- }
- ToolbarAction.ALL -> { globalSelectionStart = 0; globalSelectionEnd = allWords.lastIndex; invalidate() }
- ToolbarAction.CANCEL -> { globalSelectionStart = -1; globalSelectionEnd = -1; invalidate() }
- ToolbarAction.TRANSLATE -> { openUrl(context, "https://translate.google.com/?text=${Uri.encode(selectedText)}") }
- }
- }
- }
-
- private fun openUrl(context: Context, url: String) {
- var finalUrl = url
- if (!finalUrl.startsWith("http://") && !finalUrl.startsWith("https://")) {
- finalUrl = "https://" + finalUrl
- }
- try {
- context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(finalUrl)).apply {
- addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- })
- } catch (e: Exception) {
- Toast.makeText(context, context.getString(R.string.toast_cannot_open_link), Toast.LENGTH_SHORT).show()
- }
- }
-}
diff --git a/app/src/main/java/com/akslabs/circletosearch/ui/components/CopyTextOverlayManagerOG.kt b/app/src/main/java/com/akslabs/circletosearch/ui/components/CopyTextOverlayManagerOG.kt
deleted file mode 100644
index 7c6cf5f..0000000
--- a/app/src/main/java/com/akslabs/circletosearch/ui/components/CopyTextOverlayManagerOG.kt
+++ /dev/null
@@ -1,711 +0,0 @@
-///*
-// * Copyright (C) 2025 AKS-Labs
-// * SPDX-License-Identifier: GPL-3.0-or-later
-// *
-// * CopyTextOverlayManager — fully offline, zero network, zero logging.
-// * Uses AccessibilityNodeInfo tree traversal + PorterDuff.Mode.CLEAR canvas
-// * punch-out to highlight selectable text regions on screen.
-// */
-//
-//package com.akslabs.circletosearch.ui.components
-//
-//import android.annotation.SuppressLint
-//import android.content.ClipData
-//import android.content.ClipboardManager
-//import android.content.Context
-//import android.graphics.Canvas
-//import android.graphics.Color
-//import android.graphics.Paint
-//import android.graphics.PixelFormat
-//import android.graphics.PorterDuff
-//import android.graphics.PorterDuffXfermode
-//import android.graphics.Rect
-//import android.graphics.RectF
-//import android.os.Build
-//import android.os.Bundle
-//import android.provider.Settings
-//import android.view.GestureDetector
-//import android.view.Gravity
-//import android.view.MotionEvent
-//import android.view.View
-//import android.view.WindowManager
-//import android.view.accessibility.AccessibilityNodeInfo
-//import android.widget.Toast
-//import kotlinx.coroutines.CoroutineScope
-//import kotlinx.coroutines.Dispatchers
-//import kotlinx.coroutines.Job
-//import kotlinx.coroutines.SupervisorJob
-//import kotlinx.coroutines.launch
-//import kotlinx.coroutines.withContext
-//
-///** Simple holder for a floating-toolbar button's label and screen hit-rect. */
-//private class ToolbarButton(val label: String, val rect: Rect)
-//
-///**
-// * Manages the dim+punch-out Copy Text overlay.
-// *
-// * Usage:
-// * val mgr = CopyTextOverlayManager(context, windowManager, { getRootInActiveWindow() })
-// * mgr.show(onDismiss = { ... })
-// * mgr.rescanNodes() // call on scroll events
-// * mgr.dismiss()
-// */
-//class CopyTextOverlayManager(
-// private val context: Context,
-// /** Lambda that returns the current AccessibilityNodeInfo root. */
-// private val getRoot: () -> AccessibilityNodeInfo?
-//) {
-// private var dimView: DimPunchOutView? = null
-// private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
-// private var scanJob: Job? = null
-// private var onDismissCallback: (() -> Unit)? = null
-//
-// // Selection state
-// private var detectedNodes = mutableListOf<TextNode>()
-// private var activeNode: TextNode? = null
-// private var selectionStart: Int = -1 // word index
-// private var selectionEnd: Int = -1 // word index
-//
-// /** Whether screen transition animations are effectively disabled by the user. */
-// private val reduceMotion: Boolean
-// get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 &&
-// Settings.Global.getFloat(
-// context.contentResolver,
-// Settings.Global.TRANSITION_ANIMATION_SCALE,
-// 1f
-// ) == 0f
-//
-// // ── Public API ───────────────────────────────────────────────────────────
-//
-// fun getOverlayView(onDismiss: () -> Unit): View {
-// if (dimView != null) return dimView!!
-// android.util.Log.d("CopyText", "getOverlayView() called")
-// onDismissCallback = onDismiss
-//
-// val view = DimPunchOutView(context) { dismiss() }
-// dimView = view
-//
-// // Kick off node scan
-// android.util.Log.d("CopyText", "Starting accessibility node scan...")
-// scanNodes(view)
-// return view
-// }
-//
-// fun dismiss() {
-// scanJob?.cancel()
-// dimView = null
-// onDismissCallback?.invoke()
-// onDismissCallback = null
-// }
-//
-// /** Call on TYPE_VIEW_SCROLLED events to refresh punched-out regions live. */
-// fun rescanNodes() {
-// dimView?.let { scanNodes(it) }
-// }
-//
-// // ── Node scanning ────────────────────────────────────────────────────────
-//
-// private fun scanNodes(view: DimPunchOutView) {
-// scanJob?.cancel()
-// scanJob = scope.launch {
-// android.util.Log.d("CopyText", "scanNodes triggered")
-// // Check for snapshot nodes first
-// val snapshot = com.akslabs.circletosearch.CircleToSearchAccessibilityService.lastCapturedNodes
-// if (snapshot != null) {
-// android.util.Log.d("CopyText", "Using snapshot with ${snapshot.size} nodes")
-// detectedNodes.clear()
-// detectedNodes.addAll(snapshot)
-// com.akslabs.circletosearch.CircleToSearchAccessibilityService.lastCapturedNodes = null
-// view.invalidate()
-// return@launch
-// }
-//
-// val root = getRoot()
-// if (root == null) {
-// android.util.Log.e("CopyText", "scanNodes: getRoot() is NULL. Check accessibility permissions and window state.")
-// detectedNodes.clear()
-// view.invalidate()
-// return@launch
-// }
-// android.util.Log.d("CopyText", "scanNodes: Dynamic scan on root package=${root.packageName}")
-//
-// val nodes = withContext(Dispatchers.Default) {
-// collectTextNodes(root)
-// }
-// android.util.Log.d("CopyText", "Dynamic scan complete: ${nodes.size} nodes found")
-// detectedNodes.clear()
-// detectedNodes.addAll(nodes)
-// view.invalidate()
-// }
-// }
-//
-// internal fun collectTextNodes(root: AccessibilityNodeInfo?): List<TextNode> {
-// if (root == null) return emptyList()
-//
-// val allNodes = mutableListOf<AccessibilityNodeInfo>()
-// val queue = ArrayDeque<AccessibilityNodeInfo>()
-// queue.add(root)
-//
-// // 1. Breadth-first collect all nodes that potentially contain text
-// while (queue.isNotEmpty()) {
-// val node = queue.removeFirst()
-// try {
-// if (isPotentialTextNode(node)) {
-// allNodes.add(AccessibilityNodeInfo.obtain(node))
-// }
-// for (i in 0 until node.childCount) {
-// node.getChild(i)?.let { queue.add(it) }
-// }
-// } catch (e: Exception) {
-// android.util.Log.e("CopyText", "Error during traversal: ${e.message}")
-// }
-// }
-//
-// // 2. Leaf-first filter: Remove a node if any of its descendants are already in the list
-// val leafNodes = allNodes.filter { parent ->
-// allNodes.none { child -> child != parent && isDescendantOf(child, parent) }
-// }
-//
-// // 3. Convert leaf nodes to TextNodes
-// val result = mutableListOf<TextNode>()
-// leafNodes.forEach { node ->
-// val text = getBestText(node)
-// if (!text.isNullOrBlank() && text.length > 1) {
-// val rect = Rect()
-// node.getBoundsInScreen(rect)
-//
-// // Final validation: check if it's visible and has dimensions
-// if (!rect.isEmpty && rect.width() > 5 && rect.height() > 5) {
-// val words = splitIntoWords(text.toString(), rect)
-// if (words.isNotEmpty()) {
-// result.add(TextNode(
-// id = java.util.UUID.randomUUID().toString(),
-// fullText = text.toString(),
-// bounds = rect,
-// words = words
-// ))
-// }
-// }
-// }
-// }
-//
-// // Optimization: Recycle collected nodes
-// allNodes.forEach { try { it.recycle() } catch (ignore: Exception) {} }
-//
-// android.util.Log.d("CopyText", "LEAF-FIRST: Collected ${result.size} final text nodes from ${allNodes.size} potential nodes")
-// return result
-// }
-//
-// private fun isPotentialTextNode(node: AccessibilityNodeInfo): Boolean {
-// val className = node.className?.toString() ?: ""
-// val text = node.text
-// val contentDesc = node.contentDescription
-//
-// // Basic heuristics:
-// // 1. Has direct text? Yes.
-// // 2. Is a WebView node? Yes (let it pass to check children).
-// // 3. Is a clickable widget with content description? Yes.
-//
-// if (!text.isNullOrEmpty()) return true
-//
-// // For buttons/icons, contentDescription is text
-// if (!contentDesc.isNullOrEmpty() && (node.isClickable || className.contains("Button") || className.contains("Image"))) {
-// return true
-// }
-//
-// // WebView nodes might not have text themselves but we need to traverse them
-// if (className.contains("WebView") || className.contains("webkit")) return true
-//
-// return false
-// }
-//
-// private fun getBestText(node: AccessibilityNodeInfo): CharSequence? {
-// val text = node.text
-// if (!text.isNullOrEmpty()) return text
-//
-// // Fallback to contentDescription only for meaningful components
-// val className = node.className?.toString() ?: ""
-// if (node.isClickable || className.contains("Button") || className.contains("Image")) {
-// return node.contentDescription
-// }
-//
-// return null
-// }
-//
-// private fun isDescendantOf(child: AccessibilityNodeInfo, parent: AccessibilityNodeInfo): Boolean {
-// var current: AccessibilityNodeInfo? = child.parent
-// while (current != null) {
-// if (current == parent) {
-// try { current.recycle() } catch (_: Exception) {}
-// return true
-// }
-// val nextParent = current.parent
-// try { current.recycle() } catch (_: Exception) {}
-// current = nextParent
-// }
-// return false
-// }
-//
-// internal fun splitIntoWords(fullText: String, nodeBounds: Rect): List<Word> {
-// val words = mutableListOf<Word>()
-// val rawWords = fullText.split(Regex("\\s+"))
-// var currentIdx = 0
-// rawWords.forEachIndexed { wordIdx, wordText ->
-// if (wordText.isEmpty()) return@forEachIndexed
-// val start = fullText.indexOf(wordText, currentIdx)
-// val end = start + wordText.length
-// val bounds = estimateWordBounds(start, end, fullText, nodeBounds)
-// words.add(Word(wordText, wordIdx, start, end, bounds))
-// currentIdx = end
-// }
-// return words
-// }
-//
-// private fun estimateWordBounds(start: Int, end: Int, fullText: String, nodeBounds: Rect): RectF {
-// val totalChars = fullText.length.toFloat()
-// if (totalChars == 0f) return RectF(nodeBounds)
-//
-// val leftFraction = start / totalChars
-// val rightFraction = end / totalChars
-//
-// return RectF(
-// nodeBounds.left + (nodeBounds.width() * leftFraction),
-// nodeBounds.top.toFloat(),
-// nodeBounds.left + (nodeBounds.width() * rightFraction),
-// nodeBounds.bottom.toFloat()
-// )
-// }
-//
-// // ── Dim + punch-out View ─────────────────────────────────────────────────
-//
-// @SuppressLint("ClickableViewAccessibility")
-// inner class DimPunchOutView(
-// context: Context,
-// private val onBackPress: () -> Unit
-// ) : View(context) {
-//
-// init {
-// this.background = null
-// setWillNotDraw(false)
-// }
-//
-// // Coordinate conversion: Screen to Local
-// private val viewLocation = IntArray(2)
-//
-// private fun toLocal(screenRect: Rect): RectF {
-// getLocationOnScreen(viewLocation)
-// return RectF(
-// (screenRect.left - viewLocation[0]).toFloat(),
-// (screenRect.top - viewLocation[1]).toFloat(),
-// (screenRect.right - viewLocation[0]).toFloat(),
-// (screenRect.bottom - viewLocation[1]).toFloat()
-// )
-// }
-//
-// private fun toLocal(screenRectF: RectF): RectF {
-// getLocationOnScreen(viewLocation)
-// return RectF(
-// screenRectF.left - viewLocation[0],
-// screenRectF.top - viewLocation[1],
-// screenRectF.right - viewLocation[0],
-// screenRectF.bottom - viewLocation[1]
-// )
-// }
-//
-// private fun screenToLocalX(screenX: Float): Float {
-// getLocationOnScreen(viewLocation)
-// return screenX - viewLocation[0]
-// }
-//
-// private fun screenToLocalY(screenY: Float): Float {
-// getLocationOnScreen(viewLocation)
-// return screenY - viewLocation[1]
-// }
-//
-// // 15% black dim over the full screen (alpha = 0.15 * 255 ≈ 38)
-// private val dimPaint = Paint().apply {
-// color = Color.BLACK
-// alpha = 38
-// isAntiAlias = false
-// }
-//
-// // Paint for pulsing highlights
-// private val highlightPaint = Paint().apply {
-// color = Color.parseColor("#4FC3F7") // Light blue
-// style = Paint.Style.STROKE
-// strokeWidth = 4f
-// isAntiAlias = true
-// }
-//
-// private val highlightFillPaint = Paint().apply {
-// color = Color.WHITE
-// alpha = 20 // Subtly white
-// style = Paint.Style.FILL
-// isAntiAlias = true
-// }
-//
-// private val selectedWordPaint = Paint().apply {
-// color = Color.parseColor("#1565C0")
-// alpha = 90
-// isAntiAlias = true
-// }
-//
-// private val wordTextPaint = Paint().apply {
-// color = Color.WHITE
-// textSize = 38f
-// isAntiAlias = true
-// }
-//
-// private val handlePaint = Paint().apply {
-// color = Color.parseColor("#1565C0")
-// isAntiAlias = true
-// }
-//
-// private val cardPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
-// color = Color.WHITE
-// }
-// private val copyBtnPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
-// color = Color.parseColor("#FF6750A4")
-// }
-// private val btnTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
-// color = Color.parseColor("#FF1C1B1F")
-// textSize = 42f
-// textAlign = Paint.Align.CENTER
-// }
-// private val copyBtnTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
-// color = Color.WHITE
-// textSize = 42f
-// textAlign = Paint.Align.CENTER
-// }
-//
-// private var toolbarButtons: List<ToolbarButton> = emptyList()
-//
-// private var pulseAlpha = 1.0f
-// private var pulseIncreasing = false
-// private val handler = android.os.Handler(android.os.Looper.getMainLooper())
-// private val pulseRunnable = object : Runnable {
-// override fun run() {
-// if (pulseIncreasing) {
-// pulseAlpha += 0.02f
-// if (pulseAlpha >= 1.0f) {
-// pulseAlpha = 1.0f
-// pulseIncreasing = false
-// }
-// } else {
-// pulseAlpha -= 0.02f
-// if (pulseAlpha <= 0.4f) {
-// pulseAlpha = 0.4f
-// pulseIncreasing = true
-// }
-// }
-// invalidate()
-// handler.postDelayed(this, 30)
-// }
-// }
-//
-// private val gestureDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
-// override fun onLongPress(e: MotionEvent) {
-// val x = e.x.toInt()
-// val y = e.y.toInt()
-//
-// if (activeNode == null) {
-// // Node discovery from tap (already in local coords from e.x/e.y)
-// detectedNodes.find { toLocal(it.bounds).contains(x.toFloat(), y.toFloat()) }?.let { enterNode(it) }
-// } else {
-// val wordIdx = findNearestWord(x.toFloat(), y.toFloat(), activeNode!!.words)
-// selectionStart = wordIdx
-// selectionEnd = wordIdx
-// invalidate()
-// }
-// }
-//
-// override fun onSingleTapUp(e: MotionEvent): Boolean {
-// val x = e.x.toInt()
-// val y = e.y.toInt()
-//
-// // 1. Check toolbar
-// if (activeNode != null && selectionStart != -1) {
-// for (btn in toolbarButtons) {
-// if (btn.rect.contains(x, y)) {
-// handleToolbarAction(btn.label)
-// return true
-// }
-// }
-// }
-//
-// // 2. Click in active node -> select word
-// activeNode?.let { node ->
-// val localBounds = toLocal(node.bounds)
-// if (localBounds.contains(x.toFloat(), y.toFloat())) {
-// val wordIdx = findNearestWord(x.toFloat(), y.toFloat(), node.words)
-// if (selectionStart == -1 || (selectionStart == selectionEnd && wordIdx != selectionStart)) {
-// selectionStart = wordIdx
-// selectionEnd = wordIdx
-// } else {
-// if (wordIdx < selectionStart) selectionStart = wordIdx
-// else if (wordIdx > selectionEnd) selectionEnd = wordIdx
-// }
-// invalidate()
-// return true
-// } else {
-// exitNode()
-// return true
-// }
-// }
-//
-// // 3. Click highlighting node -> enter it
-// detectedNodes.find { toLocal(it.bounds).contains(x.toFloat(), y.toFloat()) }?.let {
-// enterNode(it)
-// return true
-// }
-//
-// // 4. Click empty space -> exit overlay
-// onBackPress()
-// return true
-// }
-// })
-//
-// init {
-// setLayerType(LAYER_TYPE_SOFTWARE, null)
-// handler.post(pulseRunnable)
-// }
-//
-// private var dragHandleType = 0 // 0: none, 1: start, 2: end
-//
-// private fun enterNode(node: TextNode) {
-// activeNode = node
-// selectionStart = 0
-// selectionEnd = node.words.lastIndex
-// invalidate()
-// }
-//
-// private fun exitNode() {
-// activeNode = null
-// selectionStart = -1
-// selectionEnd = -1
-// invalidate()
-// }
-//
-// fun setTextRects(rects: List<Rect>) {
-// // Deprecated, we use detectedNodes
-// invalidate()
-// }
-//
-// override fun onDraw(canvas: Canvas) {
-// // 1. Dim background
-// canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), dimPaint)
-//
-// // 2. Draw node highlights
-// detectedNodes.forEach { node ->
-// if (activeNode?.id == node.id) return@forEach // Don't draw highlight for active node
-//
-// val localBounds = toLocal(node.bounds)
-// highlightPaint.alpha = (pulseAlpha * 255).toInt()
-// canvas.drawRoundRect(localBounds, 12f, 12f, highlightFillPaint)
-// canvas.drawRoundRect(localBounds, 12f, 12f, highlightPaint)
-// }
-//
-// // 3. Draw active node words and selection
-// activeNode?.let { node ->
-// node.words.forEach { word ->
-// if (word.index in selectionStart..selectionEnd) {
-// val localWordBounds = toLocal(word.bounds)
-// canvas.drawRoundRect(localWordBounds, 8f, 8f, selectedWordPaint)
-// }
-// }
-//
-// // Draw handles
-// if (selectionStart != -1 && selectionEnd != -1) {
-// val startWord = node.words[selectionStart]
-// val endWord = node.words[selectionEnd]
-//
-// val startLocal = toLocal(startWord.bounds)
-// val endLocal = toLocal(endWord.bounds)
-//
-// drawHandle(canvas, startLocal.left, startLocal.top, true)
-// drawHandle(canvas, endLocal.right, endLocal.bottom, false)
-//
-// // Draw toolbar
-// drawFloatingToolbar(canvas, toLocal(node.bounds))
-// }
-// }
-// }
-//
-// private fun drawHandle(canvas: Canvas, x: Float, y: Float, isStart: Boolean) {
-// canvas.drawCircle(x, y, 18f, handlePaint)
-// if (isStart) {
-// canvas.drawRect(x - 2f, y, x + 2f, y + 40f, handlePaint)
-// } else {
-// canvas.drawRect(x - 2f, y - 40f, x + 2f, y, handlePaint)
-// }
-// }
-//
-// private fun drawFloatingToolbar(canvas: Canvas, anchor: RectF) {
-// val btnW = 210
-// val btnH = 88
-// val padding = 14
-// val gap = 8
-// val labels = listOf("Copy", "Select All", "Cancel")
-//
-// val totalW = labels.size * btnW + (labels.size - 1) * gap + padding * 2
-// val totalH = btnH + padding * 2
-//
-// var left = anchor.centerX().toInt() - totalW / 2
-// var top = anchor.top.toInt() - totalH - 18
-// if (top < 0) top = anchor.bottom.toInt() + 18
-// if (left < 0) left = 8
-// if (left + totalW > width) left = width - totalW - 8
-//
-// // Card background with shadow via cardPaint
-// cardPaint.setShadowLayer(16f, 0f, 4f, Color.parseColor("#44000000"))
-// canvas.drawRoundRect(
-// RectF(left.toFloat(), top.toFloat(), (left + totalW).toFloat(), (top + totalH).toFloat()),
-// 24f, 24f, cardPaint
-// )
-// cardPaint.clearShadowLayer()
-//
-// val buttons = mutableListOf<ToolbarButton>()
-// labels.forEachIndexed { idx, label ->
-// val bLeft = left + padding + idx * (btnW + gap)
-// val bTop = top + padding
-// val bRect = Rect(bLeft, bTop, bLeft + btnW, bTop + btnH)
-// buttons.add(ToolbarButton(label, bRect))
-//
-// val bRectF = RectF(bRect)
-// if (label == "Copy") {
-// canvas.drawRoundRect(bRectF, 12f, 12f, copyBtnPaint)
-// canvas.drawText(
-// label,
-// bRectF.centerX(), bRectF.centerY() + copyBtnTextPaint.textSize / 3f,
-// copyBtnTextPaint
-// )
-// } else {
-// canvas.drawText(
-// label,
-// bRectF.centerX(), bRectF.centerY() + btnTextPaint.textSize / 3f,
-// btnTextPaint
-// )
-// }
-// }
-// toolbarButtons = buttons
-// }
-//
-// override fun onTouchEvent(event: MotionEvent): Boolean {
-// val x = event.x
-// val y = event.y
-//
-// when (event.action) {
-// MotionEvent.ACTION_DOWN -> {
-// // Check handles
-// activeNode?.let { node ->
-// if (selectionStart != -1) {
-// val startWord = node.words[selectionStart]
-// val endWord = node.words[selectionEnd]
-//
-// val startLocal = toLocal(startWord.bounds)
-// val endLocal = toLocal(endWord.bounds)
-//
-// if (isPointNear(x, y, startLocal.left, startLocal.top)) {
-// dragHandleType = 1
-// return true
-// }
-// if (isPointNear(x, y, endLocal.right, endLocal.bottom)) {
-// dragHandleType = 2
-// return true
-// }
-// }
-// }
-// }
-// MotionEvent.ACTION_MOVE -> {
-// if (dragHandleType != 0) {
-// updateSelectionFromDrag(x, y)
-// invalidate()
-// return true
-// }
-// }
-// MotionEvent.ACTION_UP -> {
-// if (dragHandleType != 0) {
-// dragHandleType = 0
-// return true
-// }
-//
-// // Gesture Detector handles taps
-// gestureDetector.onTouchEvent(event)
-// }
-// }
-// return gestureDetector.onTouchEvent(event)
-// }
-//
-// private fun isPointNear(px: Float, py: Float, x: Float, y: Float): Boolean {
-// val dist = Math.sqrt(Math.pow((px - x).toDouble(), 2.0) + Math.pow((py - y).toDouble(), 2.0))
-// return dist < 80 // Large touch target for handles
-// }
-//
-// private fun updateSelectionFromDrag(x: Float, y: Float) {
-// val node = activeNode ?: return
-// val nearestWordIdx = findNearestWord(x, y, node.words)
-// val oldStart = selectionStart
-// val oldEnd = selectionEnd
-//
-// if (dragHandleType == 1) {
-// selectionStart = Math.min(nearestWordIdx, selectionEnd)
-// } else if (dragHandleType == 2) {
-// selectionEnd = Math.max(nearestWordIdx, selectionStart)
-// }
-//
-// if (oldStart != selectionStart || oldEnd != selectionEnd) {
-// performHapticFeedback(android.view.HapticFeedbackConstants.TEXT_HANDLE_MOVE)
-// }
-// }
-//
-// private fun findNearestWord(x: Float, y: Float, words: List<Word>): Int {
-// var minDist = Float.MAX_VALUE
-// var nearestIdx = 0
-// words.forEachIndexed { idx, word ->
-// val dx = x - word.bounds.centerX()
-// val dy = y - word.bounds.centerY()
-// val dist = dx * dx + dy * dy
-// if (dist < minDist) {
-// minDist = dist
-// nearestIdx = idx
-// }
-// }
-// return nearestIdx
-// }
-//
-// private fun handleToolbarAction(label: String) {
-// val node = activeNode ?: return
-// when (label) {
-// "Copy" -> {
-// if (selectionStart != -1 && selectionEnd != -1) {
-// val selectedWords = node.words.filter { it.index in selectionStart..selectionEnd }
-// val selectedText = selectedWords.joinToString(" ") { it.text }
-//
-// val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
-// clipboard.setPrimaryClip(ClipData.newPlainText("Copied Text", selectedText))
-// Toast.makeText(context, "Text copied ✓", Toast.LENGTH_SHORT).show()
-// dismiss()
-// }
-// }
-// "Select All" -> {
-// selectionStart = 0
-// selectionEnd = node.words.lastIndex
-// invalidate()
-// }
-// "Cancel" -> {
-// exitNode()
-// }
-// }
-// }
-//
-// override fun isInEditMode(): Boolean = false
-//
-// override fun onKeyDown(keyCode: Int, event: android.view.KeyEvent): Boolean {
-// if (keyCode == android.view.KeyEvent.KEYCODE_BACK) {
-// onBackPress()
-// return true
-// }
-// return super.onKeyDown(keyCode, event)
-// }
-// }
-//}
diff --git a/app/src/main/res/drawable/ocr.xml b/app/src/main/res/drawable/ocr.xml
deleted file mode 100644
index 7cfd8cf..0000000
--- a/app/src/main/res/drawable/ocr.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
- android:width="22dp"
- android:height="22dp"
- android:viewportWidth="22"
- android:viewportHeight="22">
- <path
- android:fillColor="#FF000000"
- android:pathData="M18.1,0h-2.8c-0.7,0 -1.1,0.4 -1.1,1.1s0.4,1.1 1.1,1.1h2.8c0.9,0 1.6,0.7 1.6,1.6v2.7c0,0.7 0.4,1.1 1.1,1.1S22,7.3 22,6.6V3.8C22,1.8 20.2,0 18.1,0"/>
- <path
- android:fillColor="#FF000000"
- android:pathData="M20.9,14.3c-0.7,0 -1.1,0.4 -1.1,1.1v2.7c0,0.9 -0.7,1.6 -1.6,1.6h-2.8c-0.7,0 -1.1,0.4 -1.1,1.1s0.4,1.1 1.1,1.1h2.8c2.1,0 3.9,-1.7 3.9,-3.9v-2.7C22,14.7 21.6,14.3 20.9,14.3"/>
- <path
- android:fillColor="#FF000000"
- android:pathData="M6.6,19.8H3.8c-0.9,0 -1.6,-0.7 -1.6,-1.6v-2.7c0,-0.7 -0.4,-1.1 -1.1,-1.1S0,14.7 0,15.4v2.7C0,20.3 1.7,22 3.8,22h2.8c0.7,0 1.1,-0.4 1.1,-1.1S7.3,19.8 6.6,19.8"/>
- <path
- android:fillColor="#FF000000"
- android:pathData="M1.1,7.7c0.7,0 1.1,-0.4 1.1,-1.1V3.8c0,-0.9 0.7,-1.6 1.6,-1.6h2.8c0.7,0 1.1,-0.4 1.1,-1.1S7.3,0 6.6,0H3.8C1.7,0 0,1.7 0,3.8v2.7C0,7.3 0.4,7.7 1.1,7.7"/>
- <path
- android:fillColor="#FF000000"
- android:pathData="M17,6.6h-2.2c-0.3,0 -0.6,0.2 -0.6,0.6c0,0.3 0.2,0.5 0.6,0.5H17c0.3,0 0.6,-0.2 0.6,-0.5C17.6,6.8 17.4,6.6 17,6.6"/>
- <path
- android:fillColor="#FF000000"
- android:pathData="M17,9.9h-5.5c-0.3,0 -0.6,0.2 -0.6,0.6s0.2,0.6 0.6,0.6H17c0.3,0 0.6,-0.2 0.6,-0.6S17.4,9.9 17,9.9"/>
- <path
- android:fillColor="#FF000000"
- android:pathData="M17,13.2h-6.6c-0.3,0 -0.6,0.2 -0.6,0.6s0.2,0.6 0.6,0.6H17c0.3,0 0.6,-0.2 0.6,-0.6S17.4,13.2 17,13.2"/>
- <path
- android:fillColor="#FF000000"
- android:pathData="M17,16.5H4.9c-0.3,0 -0.5,0.2 -0.5,0.5c0,0.3 0.2,0.6 0.5,0.6H17c0.3,0 0.6,-0.2 0.6,-0.6C17.6,16.7 17.4,16.5 17,16.5"/>
- <path
- android:fillColor="#FF000000"
- android:pathData="M4.4,5.5c0,0.6 0.5,1.1 1.1,1.1H7l-0.8,5.3c-0.1,0.6 0.3,1.2 0.9,1.2c0.6,0.1 1.2,-0.3 1.2,-0.9l0.8,-5.6H11c0.6,0 1.1,-0.5 1.1,-1.1S11.6,4.4 11,4.4H5.5C4.9,4.4 4.4,4.9 4.4,5.5"/>
-</vector>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 421ff0f..44b99cb 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -63,8 +63,6 @@
<string name="label_set_default_assistant_subtitle">Hold the Home button or edge-swipe up to summon CircleToSearch.</string>
<string name="section_customization">CUSTOMIZATION</string>
<string name="info_lens_needs_google">Lens needs Google App Installed. But Degoogled friends can stick with the versatile Multi-Search Engine mode.</string>
- <string name="label_ocr_settings">OCR Language Settings</string>
- <string name="label_ocr_settings_subtitle">Import custom Tesseract OCR models</string>
<string name="label_from_akslabs">From AKS-Labs With \u2764\uFE0F</string>
<string name="toast_could_not_open_link">Could not open link</string>
<string name="toast_accessibility_settings_error">Could not open Accessibility Settings</string>
@@ -86,7 +84,6 @@
<string name="cd_logo">Logo</string>
<string name="cd_voice_search">Voice Search</string>
<string name="cd_lens">Lens</string>
- <string name="cd_assist_copy">Assist Copy</string>
<string name="cd_translate">Translate</string>
<string name="cd_github">Github</string>
<string name="cd_donate">Donate</string>
@@ -96,13 +93,10 @@
<string name="cd_move_down">Move Down</string>
<string name="cd_back">Back</string>
<string name="cd_delete">Delete</string>
- <string name="cd_exit_copy_mode">Exit Copy Mode</string>
<string name="cd_search_icon">Search Icon</string>
- <string name="cd_import_model">Import Model</string>
<!-- Search Screen Labels -->
<string name="label_smartscan">SmartScan</string>
- <string name="label_copy_text">Copy Text</string>
<string name="label_scan_qr">Scan QR</string>
<string name="label_fullscreen">Fullscreen</string>
<string name="label_share">Share</string>
@@ -140,10 +134,6 @@
<string name="toast_auto_rotate">Auto Rotate: %1$s</string>
<string name="toast_auto_rotate_permission">Permission required for Auto Rotate</string>
<string name="toast_enable_accessibility_tile">Please enable Circle to Search Accessibility Service</string>
- <string name="toast_invalid_model_file">File must be a .traineddata Tesseract model.</string>
- <string name="toast_model_imported">Successfully imported %1$s model!</string>
- <string name="toast_model_import_failed">Failed to import model</string>
- <string name="toast_ocr_model_selected">Selected: %1$s. Restarting scan\u2026</string>
<string name="toast_save_failed">Save failed</string>
<!-- Share -->
@@ -187,15 +177,6 @@
<string name="title_select_app">Select App</string>
<string name="hint_search_apps">Search apps</string>
- <!-- OCR Settings Screen -->
- <string name="title_ocr_settings">OCR Language Models</string>
- <string name="btn_import_model">Import Model</string>
- <string name="title_language_models_guide">Language Models Guide</string>
- <string name="info_ocr_guide_part1">This app uses language models to detect text. By default, it uses a fast English model which may miss some text. To use high-accuracy models or detect other languages, download them from the </string>
- <string name="info_ocr_guide_telegram_link">developer\'s Telegram group</string>
- <string name="info_ocr_guide_part2"> with /model command, e.g. /model english and import them below.</string>
- <string name="title_installed_models">Installed Models</string>
-
<!-- QR Code Result Sheet -->
<string name="label_contact">Contact</string>
<string name="qr_title_scanning">Scanning\u2026</string>