CircleToSearch with multi search engine support for all android
Kotlin
redesigned bottom bar and added new features
AKS Labsbcfae9dd4d23
diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 21f9b42..05e64f1 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -34,7 +34,7 @@ android {applicationId = "com.akslabs.circletosearch"minSdk = 29targetSdk = 36- versionCode = 4+ versionCode = 6versionName = "0.4"testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"diff --git a/app/release/output-metadata.json b/app/release/output-metadata.jsonindex 7434c2c..1652a9d 100644--- a/app/release/output-metadata.json+++ b/app/release/output-metadata.json@@ -11,7 +11,7 @@"type": "SINGLE","filters": [],"attributes": [],- "versionCode": 4,+ "versionCode": 6,"versionName": "0.4","outputFile": "app-release.apk"}diff --git a/app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.kt b/app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.ktindex 689dcc9..73e5d66 100644--- a/app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.kt+++ b/app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.kt@@ -42,11 +42,13 @@ import android.view.Viewimport android.view.ViewOutlineProviderimport android.view.WindowManagerimport android.view.accessibility.AccessibilityEvent+import android.view.accessibility.AccessibilityNodeInfoimport com.akslabs.circletosearch.data.ActionTypeimport com.akslabs.circletosearch.data.BitmapRepositoryimport com.akslabs.circletosearch.data.GestureTypeimport com.akslabs.circletosearch.data.OverlayConfigurationManagerimport com.akslabs.circletosearch.data.OverlaySegment+import com.akslabs.circletosearch.ui.components.CopyTextOverlayManagerimport java.util.concurrent.Executorimport java.util.concurrent.Executors@@ -57,6 +59,9 @@ class CircleToSearchAccessibilityService : AccessibilityService() {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+// Bubble related - Keeping existing logic but refactoring slightly if needed// For now, keeping bubble separate as requested in prompt "statusbar overlay customization... but it should work normally like now"// The prompt asks to disable statusbar overlay in landscape but keep it working normally.@@ -81,6 +86,12 @@ class CircleToSearchAccessibilityService : AccessibilityService() {windowManager = getSystemService(WINDOW_SERVICE) as WindowManagerconfigManager = OverlayConfigurationManager(this)+ // Add FLAG_RETRIEVE_INTERACTIVE_WINDOWS at runtime so we can read+ // node info from other windows without touching AndroidManifest.xml.+ val info = serviceInfo+ info.flags = info.flags or android.accessibilityservice.AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS+ serviceInfo = info+prefs.registerOnSharedPreferenceChangeListener(prefsListener)overlayPrefs.registerOnSharedPreferenceChangeListener(overlayPrefsListener)@@ -717,7 +728,12 @@ class CircleToSearchAccessibilityService : AccessibilityService() {startActivity(intent)}- override fun onAccessibilityEvent(event: AccessibilityEvent?) {}+ override fun onAccessibilityEvent(event: AccessibilityEvent?) {+ // Forward scroll events to the Copy Text overlay for live re-scan+ if (event?.eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED) {+ copyTextManager?.rescanNodes()+ }+ }override fun onInterrupt() {}@@ -729,6 +745,19 @@ class CircleToSearchAccessibilityService : AccessibilityService() {android.util.Log.d("CircleToSearch", "triggerCapture static called. instance=${instance != null}")instance?.performCapture()}++ /**+ * Returns the current root AccessibilityNodeInfo for the active window.+ * Used by [com.akslabs.circletosearch.ui.components.CopyTextOverlayManager]+ * to scan on-screen text nodes.+ */+ fun getRootNode(): AccessibilityNodeInfo? = instance?.rootInActiveWindow++ /** Allows OverlayActivity to register an active CopyTextOverlayManager+ * so scroll events can trigger a live re-scan. */+ fun setCopyTextManager(mgr: CopyTextOverlayManager?) {+ instance?.copyTextManager = mgr+ }}override fun onCreate() {diff --git a/app/src/main/java/com/akslabs/circletosearch/OverlayActivity.kt b/app/src/main/java/com/akslabs/circletosearch/OverlayActivity.ktindex 8ca2f89..ea6fc29 100644--- a/app/src/main/java/com/akslabs/circletosearch/OverlayActivity.kt+++ b/app/src/main/java/com/akslabs/circletosearch/OverlayActivity.kt@@ -20,6 +20,7 @@package com.akslabs.circletosearchimport android.os.Bundle+import android.view.WindowManagerimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdge@@ -29,11 +30,13 @@ import androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Colorimport com.akslabs.circletosearch.data.BitmapRepositoryimport com.akslabs.circletosearch.ui.CircleToSearchScreen+import com.akslabs.circletosearch.ui.components.CopyTextOverlayManagerimport com.akslabs.circletosearch.ui.theme.CircleToSearchThemeclass OverlayActivity : ComponentActivity() {private val screenshotBitmap = androidx.compose.runtime.mutableStateOf<android.graphics.Bitmap?>(null)+ private var copyTextManager: CopyTextOverlayManager? = nulloverride fun onCreate(savedInstanceState: Bundle?) {enableEdgeToEdge()@@ -53,13 +56,40 @@ class OverlayActivity : ComponentActivity() {onClose = {BitmapRepository.clear()finish()- }+ },+ onCopyText = { activateCopyText() })}}}}+ /**+ * Activates the Copy Text overlay.+ * Uses the accessibility service's root node as the source for text scanning.+ */+ private fun activateCopyText() {+ if (copyTextManager != null) return // Already active+ android.util.Log.d("CircleToSearch", "Activating Copy Text overlay")++ val wm = getSystemService(WINDOW_SERVICE) as WindowManager++ copyTextManager = CopyTextOverlayManager(+ context = this,+ windowManager = wm,+ getRoot = {+ // Delegate to accessibility service for the current window's node tree+ CircleToSearchAccessibilityService.getRootNode()+ }+ )++ copyTextManager?.show(onDismiss = {+ android.util.Log.d("CircleToSearch", "Copy Text overlay dismissed")+ copyTextManager = null+ // Forward scroll-rescan binding is automatic via accessibility event forwarding+ })+ }+override fun onNewIntent(intent: android.content.Intent) {super.onNewIntent(intent)android.util.Log.d("CircleToSearch", "OverlayActivity onNewIntent")@@ -74,12 +104,13 @@ class OverlayActivity : ComponentActivity() {screenshotBitmap.value = bitmap} else {android.util.Log.e("CircleToSearch", "No bitmap in Repository")- // Fallback or finish? For now just log.}}override fun onDestroy() {super.onDestroy()+ copyTextManager?.dismiss()+ copyTextManager = nullif (isFinishing) {BitmapRepository.clear()}diff --git a/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt b/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.ktindex fbbc8ff..812ef7b 100644--- a/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt+++ b/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt@@ -76,6 +76,20 @@ import androidx.compose.material.icons.filled.OpenInNewimport androidx.compose.material.icons.filled.BorderOuterimport androidx.compose.material.icons.filled.Translateimport androidx.compose.material.icons.filled.Fullscreen+import androidx.compose.material.icons.filled.TextFields+import androidx.compose.animation.core.Spring+import androidx.compose.animation.core.spring+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.slideInVertically+import androidx.compose.animation.slideOutVertically+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.interaction.collectIsPressedAsState+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.wrapContentSize+import androidx.compose.material3.FilledTonalIconButton+import androidx.compose.material3.IconButtonDefaults+import androidx.compose.ui.text.style.TextAlignimport androidx.compose.material3.BottomSheetDefaultsimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.ExperimentalMaterial3ExpressiveApi@@ -145,7 +159,8 @@ import android.os.Build@Composablefun CircleToSearchScreen(screenshot: Bitmap?,- onClose: () -> Unit+ onClose: () -> Unit,+ onCopyText: () -> Unit = {}) {val context = LocalContext.currentval scope = rememberCoroutineScope()@@ -1142,138 +1157,362 @@ fun CircleToSearchScreen(}}}- // 5. Search Bar / Pill+ // 5. Bottom Bar — Material 3 Expressive two-row card+ // State for Copy Text mode+ var isCopyTextActive by remember { mutableStateOf(false) }+androidx.compose.animation.AnimatedVisibility(visible = isUIVisible,- enter = androidx.compose.animation.slideInVertically(- initialOffsetY = { it }, // Commence en dessous de l'écran (+100%)- animationSpec = tween(500, easing = androidx.compose.animation.core.FastOutSlowInEasing)- ),+ enter = slideInVertically(+ initialOffsetY = { it }, // slides up from below+ animationSpec = tween(300, easing = androidx.compose.animation.core.CubicBezierEasing(0f, 0f, 0.2f, 1f))+ ) + fadeIn(animationSpec = tween(300)),+ exit = slideOutVertically(+ targetOffsetY = { it }, // slides back down+ animationSpec = tween(200, easing = androidx.compose.animation.core.CubicBezierEasing(0.4f, 0f, 1f, 1f))+ ) + fadeOut(animationSpec = tween(200)),modifier = Modifier.align(Alignment.BottomCenter)) {+ // ── Outer card container ──────────────────────────────────────────androidx.compose.material3.Surface(modifier = Modifier.align(Alignment.BottomCenter).navigationBarsPadding().fillMaxWidth()- .padding(horizontal = 16.dp, vertical = 24.dp)- .height(64.dp),- shape = CircleShape,- color = barBgColor, // Utilise la couleur dynamique/pitch black- border = androidx.compose.foundation.BorderStroke(- width = 1.dp,- color = contentColor.copy(alpha = 0.1f) // Bordure subtile assortie- ),- shadowElevation = 12.dp+ .padding(horizontal = 12.dp, vertical = 16.dp),+ shape = RoundedCornerShape(28.dp),+ color = MaterialTheme.colorScheme.surfaceContainerHigh,+ shadowElevation = 8.dp,+ tonalElevation = 4.dp) {- Row(+ Column(modifier = Modifier- .fillMaxSize()- .padding(horizontal = 12.dp),- verticalAlignment = Alignment.CenterVertically+ .fillMaxWidth()+ .padding(horizontal = 12.dp, vertical = 10.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)) {- // Left: App Logo- Image(- painter = painterResource(id = com.akslabs.circletosearch.R.drawable.circletosearch),- contentDescription = "Logo",+ // ── ROW 1: Main search pill ─────────────────────────────+ androidx.compose.material3.Surface(modifier = Modifier- .size(50.dp)- .clickable {- haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)- scope.launch { scaffoldState.bottomSheetState.expand() }+ .fillMaxWidth()+ .height(60.dp),+ shape = CircleShape,+ color = MaterialTheme.colorScheme.surfaceContainer,+ tonalElevation = 2.dp+ ) {+ Row(+ modifier = Modifier+ .fillMaxSize()+ .padding(horizontal = 14.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ // App logo — tapping expands search results sheet+ Image(+ painter = painterResource(id = com.akslabs.circletosearch.R.drawable.circletosearch),+ contentDescription = "Circle to Search Logo",+ modifier = Modifier+ .size(44.dp)+ .clickable {+ haptic.performHapticFeedback(+ androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress+ )+ scope.launch { scaffoldState.bottomSheetState.expand() }+ }+ )++ Spacer(modifier = Modifier.weight(1f))++ // Mic button — voice search+ val micInteraction = remember { MutableInteractionSource() }+ val micPressed by micInteraction.collectIsPressedAsState()+ val micScale by animateFloatAsState(+ targetValue = if (micPressed) 0.92f else 1f,+ animationSpec = spring(stiffness = 400f, dampingRatio = 0.75f),+ label = "micScale"+ )+ IconButton(+ onClick = {+ haptic.performHapticFeedback(+ androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress+ )+ try {+ val intent = android.content.Intent(android.speech.RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {+ putExtra(android.speech.RecognizerIntent.EXTRA_LANGUAGE_MODEL,+ android.speech.RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)+ addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)+ }+ context.startActivity(intent)+ } catch (e: Exception) {+ android.util.Log.e("CircleToSearch", "Voice search failed", e)+ }+ },+ interactionSource = micInteraction,+ modifier = Modifier+ .size(44.dp)+ .graphicsLayer { scaleX = micScale; scaleY = micScale }+ ) {+ Icon(+ Icons.Default.Mic,+ contentDescription = "Voice Search",+ tint = MaterialTheme.colorScheme.onSurface,+ modifier = Modifier.size(24.dp)+ )}- )- Spacer(modifier = Modifier.weight(1f))+ Spacer(modifier = Modifier.width(4.dp))- // Right: Actions Container+ // Lens button — Google Lens visual search+ val lensInteraction = remember { MutableInteractionSource() }+ val lensPressed by lensInteraction.collectIsPressedAsState()+ val lensScale by animateFloatAsState(+ targetValue = if (lensPressed) 0.92f else 1f,+ animationSpec = spring(stiffness = 400f, dampingRatio = 0.75f),+ label = "lensScale"+ )+ IconButton(+ onClick = {+ haptic.performHapticFeedback(+ androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress+ )+ // Reuse existing Google Lens flow+ uiPreferences.setUseGoogleLensOnly(true)+ if (screenshot != null) {+ scope.launch {+ selectedBitmap = screenshot+ }+ }+ },+ interactionSource = lensInteraction,+ modifier = Modifier+ .size(44.dp)+ .graphicsLayer { scaleX = lensScale; scaleY = lensScale }+ ) {+ // Use circletosearch ring logo as lens indicator+ Icon(+ painter = painterResource(id = com.akslabs.circletosearch.R.drawable.circletosearch),+ contentDescription = "Google Lens",+ tint = MaterialTheme.colorScheme.primary,+ modifier = Modifier.size(26.dp)+ )+ }+ }+ }++ // ── ROW 2: Action buttons ───────────────────────────────Row(- verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.spacedBy(8.dp)+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceEvenly,+ verticalAlignment = Alignment.CenterVertically) {- // Social/Contribution Bubble (Anthracite / Dynamic)- androidx.compose.material3.Surface(- shape = CircleShape,- color = bubbleColor, // Utilise l'anthracite ou le container dynamique- modifier = Modifier.height(44.dp)+ // Helper composable for each tonal icon button with label+ @Composable+ fun BottomBarButton(+ label: String,+ icon: @Composable () -> Unit,+ onClick: () -> Unit) {- Row(- verticalAlignment = Alignment.CenterVertically,- modifier = Modifier.padding(horizontal = 4.dp)+ val interactionSource = remember { MutableInteractionSource() }+ val isPressed by interactionSource.collectIsPressedAsState()+ val scale by animateFloatAsState(+ targetValue = if (isPressed) 0.92f else 1f,+ animationSpec = spring(+ stiffness = Spring.StiffnessMediumLow,+ dampingRatio = 0.75f+ ),+ label = "scale_$label"+ )++ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(4.dp),+ modifier = Modifier.graphicsLayer {+ scaleX = scale+ scaleY = scale+ }) {- // Boutons sociaux - On utilise contentColor pour les icônes- val socialButtons = listOf(- com.akslabs.circletosearch.R.drawable.telegram to "https://t.me/akslabs",- com.akslabs.circletosearch.R.drawable.github to "https://github.com/aks-labs"+ FilledTonalIconButton(+ onClick = {+ haptic.performHapticFeedback(+ androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress+ )+ onClick()+ },+ modifier = Modifier.size(52.dp),+ interactionSource = interactionSource+ ) {+ icon()+ }+ Text(+ text = label,+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ textAlign = TextAlign.Center,+ maxLines = 1,+ softWrap = false,+ modifier = Modifier.wrapContentSize())+ }+ }- socialButtons.forEach { (iconRes, url) ->- IconButton(onClick = {- haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)+ // 1. Song Search ♪+ BottomBarButton(+ label = "Song",+ icon = { Icon(Icons.Default.MusicNote, contentDescription = "Song Search") },+ onClick = {+ try {+ // Try Shazam first, fallback to SoundHound, fallback to chooser+ val shazamIntent = context.packageManager+ .getLaunchIntentForPackage("com.shazam.android")+ val soundHoundIntent = context.packageManager+ .getLaunchIntentForPackage("com.melodis.midomiMusicIdentifier.freemium")+ val launchIntent = (shazamIntent ?: soundHoundIntent)?.apply {+ addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)+ }+ if (launchIntent != null) {+ context.startActivity(launchIntent)+ } else {+ // Fallback: open Play Store searchcontext.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW,- android.net.Uri.parse(url)- )- )- }, modifier = Modifier.size(36.dp)) {- Icon(- painterResource(id = iconRes),- null,- tint = contentColor,- modifier = Modifier.size(20.dp)+ android.net.Uri.parse("https://play.google.com/store/search?q=shazam&c=apps")+ ).apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) })}+ } catch (e: Exception) {+ android.util.Log.e("CircleToSearch", "Song search failed", e)}+ }+ )- IconButton(- onClick = { showSupportSheet = true },- modifier = Modifier.size(36.dp)- ) {- Icon(- painterResource(id = com.akslabs.circletosearch.R.drawable.donation),- null,- tint = contentColor,- modifier = Modifier.size(20.dp)- )+ // 2. Translate 文A+ BottomBarButton(+ label = "Translate",+ icon = { Icon(Icons.Default.Translate, contentDescription = "Translate") },+ onClick = {+ try {+ // Google Translate deep link+ val intent = context.packageManager+ .getLaunchIntentForPackage("com.google.android.apps.translate")+ ?.apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) }+ if (intent != null) {+ context.startActivity(intent)+ } else {+ context.startActivity(+ android.content.Intent(+ android.content.Intent.ACTION_VIEW,+ android.net.Uri.parse("https://translate.google.com")+ ).apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) }+ )+ }+ } catch (e: Exception) {+ android.util.Log.e("CircleToSearch", "Translate failed", e)}}- }+ )- // Fullscreen Scan Bubble (Anthracite / Dynamic)- androidx.compose.material3.Surface(- modifier = Modifier- .size(44.dp)- .clip(CircleShape)- .clickable {- haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)- if (screenshot != null) {- val rect =- Rect(0, 0, screenshot.width, screenshot.height)- selectionRect = rect- currentPathPoints.clear()- scope.launch {- selectionAnim.snapTo(0f)- selectionAnim.animateTo(1f, tween(600))- selectedBitmap = screenshot- isSearching = true+ // 3. Share / Send ✈+ BottomBarButton(+ label = "Share",+ icon = { Icon(Icons.Default.Send, contentDescription = "Share") },+ onClick = {+ if (screenshot != null) {+ scope.launch {+ try {+ val path = com.akslabs.circletosearch.utils.ImageUtils+ .saveBitmap(context, selectedBitmap ?: screenshot)+ val file = java.io.File(path)+ val uri = androidx.core.content.FileProvider.getUriForFile(+ context,+ "com.akslabs.circletosearch.fileprovider",+ file+ )+ val shareIntent = android.content.Intent(android.content.Intent.ACTION_SEND).apply {+ type = "image/*"+ putExtra(android.content.Intent.EXTRA_STREAM, uri)+ addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)+ addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)+ }+ context.startActivity(+ android.content.Intent.createChooser(shareIntent, "Share Image")+ .apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) }+ )+ } catch (e: Exception) {+ android.util.Log.e("CircleToSearch", "Share failed", e)}}- },- shape = CircleShape,- color = bubbleColor // Même couleur anthracite/dynamique- ) {- Box(contentAlignment = Alignment.Center) {+ }+ }+ )++ // 4. GitHub 🐙+ BottomBarButton(+ label = "GitHub",+ icon = {Icon(- imageVector = Icons.Default.Fullscreen,- contentDescription = "Scan All",- tint = contentColor, // Icone blanche en sombre, colorée en clair- modifier = Modifier.size(24.dp)+ painterResource(id = com.akslabs.circletosearch.R.drawable.github),+ contentDescription = "GitHub",+ modifier = Modifier.size(22.dp)+ )+ },+ onClick = {+ context.startActivity(+ android.content.Intent(+ android.content.Intent.ACTION_VIEW,+ android.net.Uri.parse("https://github.com/aks-labs")+ ).apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) })}- }- }- }+ )++ // 5. Donate 🤲♥+ BottomBarButton(+ label = "Donate",+ icon = {+ Icon(+ painterResource(id = com.akslabs.circletosearch.R.drawable.donation),+ contentDescription = "Donate",+ modifier = Modifier.size(22.dp)+ )+ },+ onClick = { showSupportSheet = true }+ )++ // 6. Copy Text T|+ BottomBarButton(+ label = "Copy Text",+ icon = { Icon(Icons.Default.TextFields, contentDescription = "Copy Text") },+ onClick = { isCopyTextActive = true }+ )++ // 7. Fullscreen ⛶+ BottomBarButton(+ label = "Fullscreen",+ icon = { Icon(Icons.Default.Fullscreen, contentDescription = "Fullscreen") },+ onClick = {+ if (screenshot != null) {+ val rect = Rect(0, 0, screenshot.width, screenshot.height)+ selectionRect = rect+ currentPathPoints.clear()+ scope.launch {+ selectionAnim.snapTo(0f)+ selectionAnim.animateTo(1f, tween(600))+ selectedBitmap = screenshot+ isSearching = true+ }+ }+ }+ )+ } // End Row 2+ } // End Column+ } // End outer Surface card+ } // End AnimatedVisibility++ // Copy Text overlay activation — fires a callback to OverlayActivity+ LaunchedEffect(isCopyTextActive) {+ if (isCopyTextActive) {+ onCopyText()+ isCopyTextActive = false}}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.ktnew file mode 100644index 0000000..42663ad--- /dev/null+++ b/app/src/main/java/com/akslabs/circletosearch/ui/components/CopyTextOverlayManager.kt@@ -0,0 +1,431 @@+/*+ * 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.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,+ private val windowManager: WindowManager,+ /** 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++ /** 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 show(onDismiss: () -> Unit) {+ if (dimView != null) return // Already visible+ onDismissCallback = onDismiss++ val view = DimPunchOutView(context) { dismiss() }+ dimView = view++ val params = WindowManager.LayoutParams(+ WindowManager.LayoutParams.MATCH_PARENT,+ WindowManager.LayoutParams.MATCH_PARENT,+ WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY,+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or+ WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or+ WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,+ PixelFormat.TRANSLUCENT+ ).apply {+ gravity = Gravity.TOP or Gravity.START+ }++ try {+ windowManager.addView(view, params)+ } catch (e: Exception) {+ e.printStackTrace()+ return+ }++ // Kick off node scan+ scanNodes(view)+ }++ fun dismiss() {+ scanJob?.cancel()+ dimView?.let {+ try { windowManager.removeView(it) } catch (_: Exception) {}+ }+ 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 {+ val rects = withContext(Dispatchers.Default) {+ collectTextRects(getRoot())+ }+ view.setTextRects(rects)+ }+ }++ /**+ * BFS traversal collecting bounding rects of all nodes that carry readable text.+ * Null-safe; never throws.+ */+ private fun collectTextRects(root: AccessibilityNodeInfo?): List<Rect> {+ if (root == null) return emptyList()+ val result = mutableListOf<Rect>()+ val queue = ArrayDeque<AccessibilityNodeInfo>()+ queue.add(root)++ while (queue.isNotEmpty()) {+ val node = queue.removeFirst()+ try {+ val hasText = !node.text.isNullOrEmpty() ||+ !node.contentDescription.isNullOrEmpty()+ val isTextClass = node.className?.let { cls ->+ cls.contains("TextView") || cls.contains("EditText") ||+ cls.contains("Button") || cls.contains("Label")+ } == true+ val isSelectable = node.isTextSelectable++ if (((hasText || isSelectable) && isTextClass) || (hasText && node.isClickable)) {+ val rect = Rect()+ node.getBoundsInScreen(rect)+ if (!rect.isEmpty) {+ result.add(rect)+ }+ }++ for (i in 0 until node.childCount) {+ node.getChild(i)?.let { queue.add(it) }+ }+ } catch (_: Exception) {+ /* Skip broken/recycled nodes */+ }+ }+ return result+ }++ // ── Dim + punch-out View ─────────────────────────────────────────────────++ @SuppressLint("ClickableViewAccessibility")+ inner class DimPunchOutView(+ context: Context,+ private val onBackPress: () -> Unit+ ) : View(context) {++ private val textRects = mutableListOf<Rect>()++ // 15% black dim over the full screen (alpha = 0.15 * 255 ≈ 38)+ private val dimPaint = Paint().apply {+ color = Color.BLACK+ alpha = 38+ isAntiAlias = false+ }++ // PorterDuff CLEAR — erases dim pixels, revealing real content at full brightness+ private val clearPaint = Paint().apply {+ xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)+ isAntiAlias = true+ }++ // Toolbar state+ private var toolbarAnchor: Rect? = null+ private var tappedNodeText: CharSequence? = null+ private var tappedNodeInfo: AccessibilityNodeInfo? = null+ private var toolbarButtons: List<ToolbarButton> = emptyList()++ // Paint objects for the floating toolbar — created once, not per-frame+ private val cardPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {+ color = Color.WHITE+ // shadow is set in onDraw via setLayerType(SOFTWARE)+ }+ private val copyBtnPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {+ color = Color.parseColor("#FF6750A4") // M3 primary purple+ }+ 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+ }++ init {+ // Software layer needed for shadow in card paint+ setLayerType(LAYER_TYPE_SOFTWARE, null)+ }++ fun setTextRects(rects: List<Rect>) {+ textRects.clear()+ textRects.addAll(rects)+ invalidate()+ }++ override fun onDraw(canvas: Canvas) {+ // saveLayer is required for PorterDuff.CLEAR to work on this layer+ val saveCount = canvas.saveLayer(+ 0f, 0f, width.toFloat(), height.toFloat(), null+ )++ // 1. Dim the entire screen at 15% opacity+ canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), dimPaint)++ // 2. Punch out each text region — dim is erased, showing full-brightness content+ for (rect in textRects) {+ canvas.drawRoundRect(+ rect.left.toFloat() - 2f,+ rect.top.toFloat() - 2f,+ rect.right.toFloat() + 2f,+ rect.bottom.toFloat() + 2f,+ 8f, 8f, clearPaint+ )+ }++ canvas.restoreToCount(saveCount)++ // 3. Draw floating action toolbar above the tapped rect (outside saveLayer)+ toolbarAnchor?.let { drawFloatingToolbar(canvas, it) }+ }++ private fun drawFloatingToolbar(canvas: Canvas, anchor: Rect) {+ 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() - totalW / 2+ var top = anchor.top - totalH - 18+ if (top < 0) top = anchor.bottom + 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 {+ if (event.action != MotionEvent.ACTION_UP) return true++ val x = event.x.toInt()+ val y = event.y.toInt()++ // Check toolbar button tap first+ if (toolbarAnchor != null) {+ for (btn in toolbarButtons) {+ if (btn.rect.contains(x, y)) {+ handleToolbarAction(btn.label)+ return true+ }+ }+ // Tap outside toolbar — close just the toolbar+ toolbarAnchor = null+ tappedNodeInfo = null+ tappedNodeText = null+ toolbarButtons = emptyList()+ invalidate()+ return true+ }++ // Check if user tapped inside a bright (punched-out) text rect+ for (i in textRects.indices) {+ val rect = textRects[i]+ if (rect.contains(x, y)) {+ showToolbarFor(rect, i)+ return true+ }+ }++ // Tap outside all text regions — dismiss the whole overlay+ onBackPress()+ return true+ }++ private fun showToolbarFor(rect: Rect, nodeIndex: Int) {+ val root = getRoot()+ if (root != null) {+ val nodes = collectFlatTextNodes(root)+ if (nodeIndex < nodes.size) {+ tappedNodeInfo = nodes[nodeIndex]+ tappedNodeText = tappedNodeInfo?.text+ ?: tappedNodeInfo?.contentDescription+ }+ }+ toolbarAnchor = rect+ invalidate()+ }++ /** Same BFS as outer [collectTextRects] but returns the node objects themselves. */+ private fun collectFlatTextNodes(root: AccessibilityNodeInfo): List<AccessibilityNodeInfo> {+ val result = mutableListOf<AccessibilityNodeInfo>()+ val queue = ArrayDeque<AccessibilityNodeInfo>()+ queue.add(root)+ while (queue.isNotEmpty()) {+ val node = queue.removeFirst()+ try {+ val hasText = !node.text.isNullOrEmpty() || !node.contentDescription.isNullOrEmpty()+ val isTextClass = node.className?.let {+ it.contains("TextView") || it.contains("EditText") ||+ it.contains("Button") || it.contains("Label")+ } == true+ if (((hasText || node.isTextSelectable) && isTextClass) || (hasText && node.isClickable)) {+ val r = Rect()+ node.getBoundsInScreen(r)+ if (!r.isEmpty) result.add(node)+ }+ for (i in 0 until node.childCount) {+ node.getChild(i)?.let { queue.add(it) }+ }+ } catch (_: Exception) {}+ }+ return result+ }++ private fun handleToolbarAction(label: String) {+ when (label) {+ "Copy" -> {+ val text = tappedNodeText+ if (!text.isNullOrEmpty()) {+ val clipboard = context+ .getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager+ clipboard.setPrimaryClip(ClipData.newPlainText("Copied Text", text))+ Toast.makeText(context, "Text copied ✓", Toast.LENGTH_SHORT).show()+ } else {+ Toast.makeText(context, "No text found in this region", Toast.LENGTH_SHORT).show()+ }+ }+ "Select All" -> {+ tappedNodeInfo?.let { node ->+ val text = node.text+ if (!text.isNullOrEmpty()) {+ val args = Bundle().apply {+ putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, 0)+ putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, text.length)+ }+ node.performAction(AccessibilityNodeInfo.ACTION_SET_SELECTION, args)+ val clipboard = context+ .getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager+ clipboard.setPrimaryClip(ClipData.newPlainText("Copied Text", text))+ Toast.makeText(context, "All text copied ✓", Toast.LENGTH_SHORT).show()+ }+ }+ }+ "Cancel" -> { /* fall through to cleanup below */ }+ }+ // Reset toolbar state regardless of action+ toolbarAnchor = null+ tappedNodeInfo = null+ tappedNodeText = null+ toolbarButtons = emptyList()+ invalidate()+ }++ 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)+ }+ }+}