CircleToSearch with multi search engine support for all android
Kotlin
improved selected text overlay
AKS Labs7c4cb103c076
diff --git a/COPY_TEXT_CODE_CHANGES.md b/COPY_TEXT_CODE_CHANGES.mddeleted file mode 100644index c411f25..0000000--- a/COPY_TEXT_CODE_CHANGES.md+++ /dev/null@@ -1,403 +0,0 @@-# Copy Text Feature Fix - Code Changes Details--## Overview-Fixed a critical bug in the Circle to Search app's "Copy Text" feature where the accessibility node tree was returning null, preventing any text from being detected or displayed for copying.-------## Change 1: CircleToSearchAccessibilityService.kt--### Location-File: `C:\Users\ashin\AndroidStudioProjects\CircleToSearch\app\src\main\java\com\akslabs\circletosearch\CircleToSearchAccessibilityService.kt`-Lines: 750-810 (in companion object)--### What Was Changed-The `getRootNode()` function which retrieves the accessibility node tree for text scanning.--### Old Code (BUGGY)-```kotlin-/**- * Returns the current root AccessibilityNodeInfo for the active application window.- * Skips TYPE_ACCESSIBILITY_OVERLAY windows (like our own UI) to find underlying text.- */-fun getRootNode(): AccessibilityNodeInfo? {- val service = instance ?: return null- val ourPackage = service.packageName- android.util.Log.d("CTS_Node", "getRootNode triggered. Our package: $ourPackage")-- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {- val windows = service.windows- android.util.Log.d("CTS_Node", "Window count: ${windows.size}")-- // 1. Filter out accessibility overlays and our own windows- // Sort by layer/id to usually get the top-most content window- val candidateWindows = windows.filter { window ->- val root = try { window.root } catch (_: Exception) { null }- window.type != android.view.accessibility.AccessibilityWindowInfo.TYPE_ACCESSIBILITY_OVERLAY &&- root?.packageName != ourPackage && // ❌ PROBLEM: Filters out our package entirely- root != null- }-- // prefer TYPE_APPLICATION- val appWindow = candidateWindows.firstOrNull {- it.type == android.view.accessibility.AccessibilityWindowInfo.TYPE_APPLICATION- }- if (appWindow != null) {- android.util.Log.d("CTS_Node", "Found app window: ${appWindow.root?.packageName}")- return appWindow.root- }-- // fallback to any candidate- val fallbackWindow = candidateWindows.firstOrNull()- if (fallbackWindow != null) {- android.util.Log.d("CTS_Node", "Fallback window: ${fallbackWindow.root?.packageName}")- return fallbackWindow.root- }- }-- // Final fallback logic- val root = service.rootInActiveWindow- if (root?.packageName != ourPackage) { // ❌ PROBLEM: Rejects if our package is active- android.util.Log.d("CTS_Node", "Defaulting to rootInActiveWindow: ${root?.packageName}")- return root- }-- android.util.Log.e("CTS_Node", "No suitable root node found (omitting our own package)")- return null // ❌ RETURNS NULL when OverlayActivity is active-}-```--### New Code (FIXED)-```kotlin-/**- * Returns the current root AccessibilityNodeInfo for the active application window.- * Prioritizes TYPE_APPLICATION windows, filters out pure accessibility overlays,- * and returns our OverlayActivity if it's the active window (contains the dimmed screenshot).- */-fun getRootNode(): AccessibilityNodeInfo? {- val service = instance ?: return null- val ourPackage = service.packageName- android.util.Log.d("CTS_Node", "getRootNode triggered. Our package: $ourPackage")-- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {- val windows = service.windows- android.util.Log.d("CTS_Node", "Window count: ${windows.size}")-- // Strategy:- // 1. Prefer TYPE_APPLICATION windows from OTHER packages (real content)- // 2. Fall back to any non-overlay window (including our OverlayActivity if it's TYPE_APPLICATION)- // 3. Last resort: use rootInActiveWindow-- val allWindowsWithRoots = windows.map { window ->- try {- val root = window.root- Pair(window, root)- } catch (_: Exception) {- Pair(window, null)- }- }.filter { (_, root) -> root != null }-- // Find other-package TYPE_APPLICATION windows (highest priority)- val otherPackageAppWindows = allWindowsWithRoots.filter { (window, root) ->- window.type == android.view.accessibility.AccessibilityWindowInfo.TYPE_APPLICATION &&- root?.packageName != ourPackage // ✅ Only exclude OTHER packages, not ours- }-- if (otherPackageAppWindows.isNotEmpty()) {- val window = otherPackageAppWindows.first()- val packageName = window.second?.packageName- android.util.Log.d("CTS_Node", "Found other-app TYPE_APPLICATION window: $packageName")- return window.second // ✅ Return real app content- }-- // Fall back to any non-overlay window (includes our OverlayActivity TYPE_APPLICATION)- val nonOverlayWindows = allWindowsWithRoots.filter { (window, _) ->- window.type != android.view.accessibility.AccessibilityWindowInfo.TYPE_ACCESSIBILITY_OVERLAY- }-- if (nonOverlayWindows.isNotEmpty()) {- val window = nonOverlayWindows.first()- val packageName = window.second?.packageName- android.util.Log.d("CTS_Node", "Found non-overlay window (fallback): $packageName")- return window.second // ✅ Return OverlayActivity if no other app- }- }-- // Final fallback: use rootInActiveWindow (works for our OverlayActivity too)- val root = service.rootInActiveWindow- if (root != null) {- android.util.Log.d("CTS_Node", "Using rootInActiveWindow fallback: ${root.packageName}")- return root // ✅ Return valid node instead of filtering- }-- android.util.Log.e("CTS_Node", "ERROR: No suitable root node found!")- return null // ✅ Only null as last resort-}-```--### Key Changes-1. **Line 768-769**: Changed priority strategy - now prefers OTHER packages' TYPE_APPLICATION windows-2. **Line 779-788**: Added fallback that INCLUDES our OverlayActivity windows-3. **Line 794-797**: Removed the `root?.packageName != ourPackage` check that was causing null returns-4. **Line 799**: Changed error conditions to be more lenient-5. **Throughout**: Enhanced logging for troubleshooting-------## Change 2: CopyTextOverlayManager.kt--### Location-File: `C:\Users\ashin\AndroidStudioProjects\CircleToSearch\app\src\main\java\com\akslabs\circletosearch\ui\components\CopyTextOverlayManager.kt`--### Change 2A: Enhanced `show()` Method--**Lines: 68-95**--#### Old Code-```kotlin-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,- PixelFormat.TRANSLUCENT- ).apply {- gravity = Gravity.TOP or Gravity.START- }-- try {- windowManager.addView(view, params) // ❌ No logging on success- } catch (e: Exception) {- e.printStackTrace() // ❌ Minimal logging- return- }-- // Kick off node scan- scanNodes(view) // ❌ No logging before scan-}-```--#### New Code-```kotlin-fun show(onDismiss: () -> Unit) {- if (dimView != null) return // Already visible- android.util.Log.d("CopyText", "show() called - setting up Copy Text overlay") // ✅ Added- 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,- PixelFormat.TRANSLUCENT- ).apply {- gravity = Gravity.TOP or Gravity.START- }-- try {- windowManager.addView(view, params)- android.util.Log.d("CopyText", "Overlay view added to window manager successfully") // ✅ Added- } catch (e: Exception) {- android.util.Log.e("CopyText", "Failed to add overlay view: ${e.message}", e) // ✅ Enhanced- e.printStackTrace()- return- }-- // Kick off node scan- android.util.Log.d("CopyText", "Starting accessibility node scan...") // ✅ Added- scanNodes(view)-}-```--### Change 2B: Improved `scanNodes()` Method--**Lines: ~140-155**--#### Old Code-```kotlin-private fun scanNodes(view: DimPunchOutView) {- scanJob?.cancel()- scanJob = scope.launch {- val nodes = withContext(Dispatchers.Default) {- collectTextNodes(getRoot()) // ❌ No null handling- }- detectedNodes.clear()- detectedNodes.addAll(nodes)- view.invalidate()- }-}-```--#### New Code-```kotlin-private fun scanNodes(view: DimPunchOutView) {- scanJob?.cancel()- scanJob = scope.launch {- val root = getRoot() // ✅ Get root first- android.util.Log.d("CopyText", "scanNodes: Root node = $root, package = ${root?.packageName}") // ✅ Added-- if (root == null) { // ✅ Check for null- android.util.Log.w("CopyText", "ERROR: getRoot() returned null! Cannot scan text nodes.") // ✅ Added- detectedNodes.clear()- view.invalidate()- return@launch- }-- val nodes = withContext(Dispatchers.Default) {- collectTextNodes(root) // ✅ Pass valid root- }- android.util.Log.d("CopyText", "Collected ${nodes.size} text nodes from accessibility tree") // ✅ Added- detectedNodes.clear()- detectedNodes.addAll(nodes)- view.invalidate()- }-}-```--### Change 2C: Rewritten `collectTextNodes()` Method--**Lines: ~157-195**--#### Old Code-```kotlin-private fun collectTextNodes(root: AccessibilityNodeInfo?): List<TextNode> {- if (root == null) return emptyList() // ❌ Silent fail, no logging- val result = mutableListOf<TextNode>()- val queue = ArrayDeque<AccessibilityNodeInfo>()- queue.add(root)-- while (queue.isNotEmpty()) {- val node = queue.removeFirst()- try {- val text = node.text ?: node.contentDescription- if (!text.isNullOrEmpty()) {- val rect = Rect()- node.getBoundsInScreen(rect)- if (!rect.isEmpty) {- val fullText = text.toString()- val words = splitIntoWords(fullText, rect)- result.add(TextNode(- id = java.util.UUID.randomUUID().toString(),- fullText = fullText,- bounds = rect,- words = words- ))- }- }-- for (i in 0 until node.childCount) {- node.getChild(i)?.let { queue.add(it) }- }- } catch (_: Exception) {} // ❌ Silent exception swallowing- }- return result // ❌ No logging of results-}-```--#### New Code-```kotlin-private fun collectTextNodes(root: AccessibilityNodeInfo?): List<TextNode> {- if (root == null) {- android.util.Log.w("CopyText", "collectTextNodes called with null root!") // ✅ Added- return emptyList()- }- val result = mutableListOf<TextNode>()- val queue = ArrayDeque<AccessibilityNodeInfo>()- queue.add(root)- var processedCount = 0 // ✅ Added counter-- while (queue.isNotEmpty()) {- val node = queue.removeFirst()- processedCount++ // ✅ Track processed count- try {- val text = node.text ?: node.contentDescription- if (!text.isNullOrEmpty()) {- val rect = Rect()- node.getBoundsInScreen(rect)- if (!rect.isEmpty) {- val fullText = text.toString()- val words = splitIntoWords(fullText, rect)- if (words.isNotEmpty()) { // ✅ Added word count check- result.add(TextNode(- id = java.util.UUID.randomUUID().toString(),- fullText = fullText,- bounds = rect,- words = words- ))- }- }- }-- for (i in 0 until node.childCount) {- node.getChild(i)?.let { queue.add(it) }- }- } catch (e: Exception) { // ✅ Better exception handling- android.util.Log.e("CopyText", "Error processing accessibility node: ${e.message}") // ✅ Added- }- }- android.util.Log.d("CopyText", "Processed $processedCount accessibility nodes, found ${result.size} text regions") // ✅ Added- return result-}-```-------## Testing the Fix--### Step 1: Build and Deploy-```bash-cd C:\Users\ashin\AndroidStudioProjects\CircleToSearch-./gradlew assembleDebug-adb install -r app/build/outputs/apk/debug/app-debug.apk-```--### Step 2: Test Copy Text Feature-1. Open any app with text (Chrome, Gmail, etc.)-2. Double-tap the status bar to trigger Circle to Search-3. Click "Copy Text" button in the bottom bar-4. **Expected**: Overlay appears with text regions highlighted in blue-5. **Tap on text**: Selectable words appear with handles-6. **Select and Copy**: Floating toolbar shows Copy/SelectAll/Cancel buttons-7. **Tap Copy**: Text copied to clipboard with toast confirmation--### Step 3: Monitor Logcat-```bash-adb logcat | grep -E "CTS_Node|CopyText"-```--Expected output:-```-D/CTS_Node: getRootNode triggered. Our package: com.akslabs.circletosearch-D/CTS_Node: Window count: 3-D/CTS_Node: Found non-overlay window (fallback): com.akslabs.circletosearch-D/CopyText: show() called - setting up Copy Text overlay-D/CopyText: Overlay view added to window manager successfully-D/CopyText: Starting accessibility node scan...-D/CopyText: scanNodes: Root node = AccessibilityNodeInfo@abc123, package = com.akslabs.circletosearch-D/CopyText: Collected 47 text nodes from accessibility tree-D/CopyText: Processed 156 accessibility nodes, found 47 text regions-```-------## Summary of Fixes--| Issue | Location | Old Behavior | New Behavior |-|-------|----------|--------------|--------------|-| getRootNode() returns null | CircleToSearchAccessibilityService.kt L750-810 | Filtered out our package completely | Allows OverlayActivity when it's active |-| No error handling | CopyTextOverlayManager.kt show() | No logging before scan | Added debug context |-| Silent null failures | CopyTextOverlayManager.kt scanNodes() | Silently passes null to tree walk | Detects and logs null root |-| No diagnostics | CopyTextOverlayManager.kt collectTextNodes() | No insight into what was processed | Logs node counts and text regions found |-| Text copy broken | Overall flow | Shows transparent screen only | Shows highlighted text ready for selection |diff --git a/COPY_TEXT_FIX_COMPLETE.md b/COPY_TEXT_FIX_COMPLETE.mddeleted file mode 100644index fd114bf..0000000--- a/COPY_TEXT_FIX_COMPLETE.md+++ /dev/null@@ -1,181 +0,0 @@-# COPY TEXT FEATURE FIX - EXECUTIVE SUMMARY--## Problem-When users clicked the "Copy Text" button in the Circle to Search overlay, they saw:-- ❌ A transparent black dimmed screen-- ❌ Only a close button visible-- ❌ NO text regions highlighted-- ❌ NO selectable text-- ❌ Copy button non-functional--## Root Cause-The accessibility service's `getRootNode()` function returned **null** when the app's OverlayActivity became the active window. This prevented the text scanning system from detecting any text in the accessibility tree.--### Technical Details-1. **Original Logic Bug**: The getRootNode() function filtered out windows from the app's own package (com.akslabs.circletosearch)-2. **Timing Issue**: When Copy Text was triggered, the OverlayActivity became the active window-3. **Chain Failure**:- - getRoot() → null- - scanNodes(null)- - collectTextNodes(null) → returns []- - No text regions to display- - Transparent overlay only--## Solution Implemented--### Files Modified-1. **CircleToSearchAccessibilityService.kt** - Complete rewrite of `getRootNode()` function-2. **CopyTextOverlayManager.kt** - Enhanced error handling and diagnostic logging--### Key Fixes-✅ **New Window Priority Logic**:-1. First: Look for OTHER apps' TYPE_APPLICATION windows (real app content)-2. Second: Accept ANY non-overlay windows (includes our OverlayActivity)-3. Third: Use rootInActiveWindow directly (no filtering)--✅ **Better Error Handling**:-- Null safety checks at every level-- Comprehensive debug logging-- Graceful fallbacks--✅ **Improved Diagnostics**:-- Log window count and package names-- Track nodes processed vs text regions found-- Report errors instead of silently failing--## Expected Behavior After Fix--### User Experience-1. User opens any app with text (Chrome, Gmail, etc.)-2. User double-taps status bar → Circle to Search overlay appears-3. User clicks "Copy Text" button-4. ✅ Overlay appears with:- - 15% black dim background- - Text regions highlighted with blue glow- - Animated pulsing effect on highlights-5. User taps a text region to enter it-6. ✅ Shows:- - Darker blue highlighting on selected text- - Selection handles at start and end of text- - Floating toolbar with Copy/SelectAll/Cancel buttons-7. User can:- - ✅ Tap words to select individual words- - ✅ Drag handles to adjust selection- - ✅ Click "Select All" to select entire region- - ✅ Click "Copy" to copy to clipboard- - ✅ Click "Cancel" to exit selection mode--### Technical Verification-When checking logs with: `adb logcat | grep -E "CTS_Node|CopyText"`--**Should see**:-```-D/CTS_Node: getRootNode triggered. Our package: com.akslabs.circletosearch-D/CTS_Node: Window count: 3-D/CTS_Node: Found non-overlay window (fallback): com.akslabs.circletosearch-D/CopyText: show() called - setting up Copy Text overlay-D/CopyText: Overlay view added to window manager successfully-D/CopyText: Starting accessibility node scan...-D/CopyText: scanNodes: Root node = AccessibilityNodeInfo@..., package = com.akslabs.circletosearch-D/CopyText: Collected 47 text nodes from accessibility tree-D/CopyText: Processed 156 accessibility nodes, found 47 text regions-```--## Code Changes Summary--### Change 1: CircleToSearchAccessibilityService.kt (lines 750-810)--**Before** (broken):-```kotlin-// Filters out our own package → returns null when OverlayActivity is active-if (root?.packageName != ourPackage) {- return root-}-return null // ❌ BROKEN-```--**After** (fixed):-```kotlin-// Allows our package when it's TYPE_APPLICATION window-val nonOverlayWindows = allWindowsWithRoots.filter { (window, _) ->- window.type != android.view.accessibility.AccessibilityWindowInfo.TYPE_ACCESSIBILITY_OVERLAY-}-if (nonOverlayWindows.isNotEmpty()) {- return nonOverlayWindows.first().second // ✅ WORKS-}-```--### Change 2: CopyTextOverlayManager.kt (multiple locations)--**Added**:-- Null safety checks in scanNodes()-- Diagnostic logging in show() and collectTextNodes()-- Node counting and reporting-- Better exception handling--## Testing Required--### Quick Test-1. Build and deploy the fixed version-2. Open Chrome or any app with text-3. Double-tap status bar → "Copy Text"-4. **Verify**: Text regions appear with blue highlighting-5. **Verify**: Can select words and copy them--### Comprehensive Test-- See COPY_TEXT_TESTING_CHECKLIST.md for full test suite--## Files Provided--1. **COPY_TEXT_FIX_SUMMARY.md** - Detailed technical explanation-2. **COPY_TEXT_CODE_CHANGES.md** - Side-by-side code comparisons-3. **COPY_TEXT_TESTING_CHECKLIST.md** - Complete testing procedures-4. **This file** - Executive summary--## Impact Assessment--### Risk Level: **LOW**-- Changes are isolated to Copy Text feature-- Other features (image search, overlay rendering, etc.) unaffected-- No breaking changes to API or public interfaces-- Backward compatible with existing code--### Benefit: **HIGH**-- Fixes completely broken Copy Text feature-- Improves accessibility (no longer returns null)-- Better debugging with comprehensive logging-- Works across all Android versions (API 21+)--## Deployment Checklist--Before deploying to production:--- [ ] Build passes without errors-- [ ] No new lint warnings-- [ ] Quick smoke test passed (text appears when clicking Copy Text)-- [ ] Comprehensive test suite passed (see testing checklist)-- [ ] Logcat shows expected debug output-- [ ] No crashes in ErrorReporting-- [ ] Performance acceptable (text appears within 2 seconds)-- [ ] Accessibility service still functioning-- [ ] Other features (image search, etc.) still working--## Support Notes--### For Users-The Copy Text feature now works as intended! When you click the "Copy Text" button, you'll see text regions highlighted on your screen that you can select and copy.--### For Support Team-If users report ongoing issues:-1. Verify CircleToSearchAccessibilityService is enabled in Settings → Accessibility-2. Ask users to disable and re-enable the accessibility service-3. Check device Android version (should be Android 5.0+)-4. Collect logcat output with CTS_Node and CopyText tags-5. Reference this fix documentation-------**Status**: ✅ FIXED AND TESTED-**Commit**: See code changes in CircleToSearchAccessibilityService.kt and CopyTextOverlayManager.kt-**Deploy Date**: [To be determined]-**Version**: [To be updated with release number]diff --git a/COPY_TEXT_FIX_SUMMARY.md b/COPY_TEXT_FIX_SUMMARY.mddeleted file mode 100644index 6529b38..0000000--- a/COPY_TEXT_FIX_SUMMARY.md+++ /dev/null@@ -1,182 +0,0 @@-# Copy Text Feature - Bug Fix Summary--## Problem Identified--When users clicked the "Copy Text" button in the Circle to Search overlay, the following occurred:-- **Screen displayed**: Transparent overlay with 15% black dim and a close button-- **Expected behavior**: Text regions highlighted with selection handles-- **Actual behavior**: NO TEXT DETECTED, no highlights, no selectable text regions-- **Root cause**: The accessibility service was unable to retrieve the accessibility node tree--## Technical Root Cause Analysis--### Issue in `CircleToSearchAccessibilityService.getRootNode()` (lines 750-793)--The original implementation had critical logic flaw:--```kotlin-// OLD BUGGY CODE:-val candidateWindows = windows.filter { window ->- val root = try { window.root } catch (_: Exception) { null }- window.type != android.view.accessibility.AccessibilityWindowInfo.TYPE_ACCESSIBILITY_OVERLAY &&- root?.packageName != ourPackage && // ❌ FILTERS OUT OUR OWN PACKAGE- root != null-}--// Final fallback:-val root = service.rootInActiveWindow-if (root?.packageName != ourPackage) { // ❌ REJECTS IF OUR PACKAGE IS ACTIVE- return root-}-return null // ❌ RETURNS NULL when OverlayActivity is the active window-```--**The problem sequence**:-1. User clicks "Copy Text" → OverlayActivity becomes the active window-2. getRootNode() filters out all windows from our package (com.akslabs.circletosearch)-3. candidateWindows becomes empty-4. Both TYPE_APPLICATION lookup and fallback return null-5. Final fallback check fails because our package IS the active window-6. Function returns null-7. CopyTextOverlayManager.scanNodes() receives null getRoot()-8. collectTextNodes(null) returns empty list-9. No text nodes to display → transparent screen with no highlights--## Solution Implemented--### File: `CircleToSearchAccessibilityService.kt`--**Changed**: `getRootNode()` function (replacements in companion object)--**New Strategy** (with improved window priority):-```kotlin-// NEW FIXED CODE:-// 1. Prefer TYPE_APPLICATION windows from OTHER packages (real app content)-val otherPackageAppWindows = allWindowsWithRoots.filter { (window, root) ->- window.type == android.view.accessibility.AccessibilityWindowInfo.TYPE_APPLICATION &&- root?.packageName != ourPackage // ✅ Only filter OTHER packages-}-if (otherPackageAppWindows.isNotEmpty()) {- return otherPackageAppWindows.first().second // ✅ FOUND OTHER APP-}--// 2. Fall back to ANY non-overlay window (✅ INCLUDES OUR OVERLAYACTIVITY)-val nonOverlayWindows = allWindowsWithRoots.filter { (window, _) ->- window.type != android.view.accessibility.AccessibilityWindowInfo.TYPE_ACCESSIBILITY_OVERLAY-}-if (nonOverlayWindows.isNotEmpty()) {- return nonOverlayWindows.first().second // ✅ RETURNS OVERLAYACTIVITY-}--// 3. Last resort: rootInActiveWindow (✅ NO PACKAGE FILTERING)-val root = service.rootInActiveWindow-if (root != null) {- return root // ✅ RETURNS VALID NODE-}--return null // ✅ ONLY IF ABSOLUTELY NOTHING AVAILABLE-```--**Key improvements**:-- ✅ Allows OverlayActivity nodes when it's the active window-- ✅ Maintains priority for other apps' windows (when they're in focus)-- ✅ Proper fallback chain with multiple recovery points-- ✅ Added comprehensive debug logging for troubleshooting--### File: `CopyTextOverlayManager.kt`--**Enhanced**: Node scanning and error handling--**Improvements**:-1. Added null check logging in `scanNodes()`- - Logs when getRoot() returns null (helps diagnose getRootNode issues)- - Shows collected vs processed node counts--2. Rewritten `collectTextNodes()`- - Better error handling for null root- - Process counter for debugging- - Word count logging per region- - Exception handling per node with logging--3. Enhanced `show()` method- - Debug logging when overlay is activated- - Better error reporting for window manager operations- - Scan initiation logging--## Impact & Verification--### Before Fix-```-User taps "Copy Text" button- → getRootNode() returns null- → No text nodes found- → Transparent overlay with no highlights- → Copy button non-functional-```--### After Fix-```-User taps "Copy Text" button- → getRootNode() returns OverlayActivity's root AccessibilityNodeInfo- → Text nodes successfully extracted from accessibility tree- → Overlay displays:- - 15% black dim background- - Highlighted text regions with pulsing glow (blue outline)- - Selection handles on first/last word- - Floating toolbar with "Copy", "Select All", "Cancel" buttons- → User can tap text to select individual words or ranges- → Copy button copies selected text to clipboard-```--## Debug Logging Added--When troubleshooting, check logcat for these tags:-- `CTS_Node` - getRootNode() operations-- `CopyText` - Copy text overlay initialization and node scanning-- `CTS_Generic` - General service operations--Example log output showing fix working:-```-CTS_Node: getRootNode triggered. Our package: com.akslabs.circletosearch-CTS_Node: Window count: 3-CTS_Node: Found non-overlay window (fallback): com.akslabs.circletosearch-CopyText: show() called - setting up Copy Text overlay-CopyText: Overlay view added to window manager successfully-CopyText: Starting accessibility node scan...-CopyText: scanNodes: Root node = AccessibilityNodeInfo@..., package = com.akslabs.circletosearch-CopyText: Collected 47 text nodes from accessibility tree-CopyText: Processed 156 accessibility nodes, found 47 text regions-```--## Files Modified--1. **CircleToSearchAccessibilityService.kt** (lines 750-810)- - Rewrote getRootNode() function completely- - Added better window priority logic- - Removed problematic package filtering--2. **CopyTextOverlayManager.kt**- - Enhanced scanNodes() with error handling (lines ~140-155)- - Improved collectTextNodes() with logging (lines ~157-195)- - Better show() method with diagnostics (lines ~68-95)--## Testing Recommendations--1. **Copy From Any App**:- - Open various apps (WebView, Gmail, Chrome, etc.)- - Trigger overlay with status bar double-tap- - Click "Copy Text"- - Verify text regions appear with highlights- - Select different text ranges- - Copy and paste to confirm text captured correctly--2. **Edge Cases**:- - App with minimal/no text (should show dim overlay only)- - Rapidly switching between apps- - Copy text while device is in split-screen mode- - Copy text from scrollable content (should update on scroll)--3. **Log Verification**:- - Enable Android Studio Logcat filtering- - Filter for "CTS_Node" and "CopyText" tags- - Verify successful node retrieval and text region detectiondiff --git a/COPY_TEXT_PATCH.diff b/COPY_TEXT_PATCH.diffdeleted file mode 100644index b10d661..0000000--- a/COPY_TEXT_PATCH.diff+++ /dev/null@@ -1,269 +0,0 @@-# UNIFIED DIFF - Copy Text Feature Fix--## File: CircleToSearchAccessibilityService.kt-Location: `app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.kt`--```diff---- a/app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.kt-+++ b/app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.kt-@@ -750,47 +750,62 @@ class CircleToSearchAccessibilityService : AccessibilityService() {- }-- /**-- * Returns the current root AccessibilityNodeInfo for the active application window.-- * Skips TYPE_ACCESSIBILITY_OVERLAY windows (like our own UI) to find underlying text.-+ * Returns the current root AccessibilityNodeInfo for the active application window.-+ * Prioritizes TYPE_APPLICATION windows, filters out pure accessibility overlays,-+ * and returns our OverlayActivity if it's the active window (contains the dimmed screenshot).- */- fun getRootNode(): AccessibilityNodeInfo? {- val service = instance ?: return null- val ourPackage = service.packageName- android.util.Log.d("CTS_Node", "getRootNode triggered. Our package: $ourPackage")-- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {- val windows = service.windows- android.util.Log.d("CTS_Node", "Window count: ${windows.size}")--- // 1. Filter out accessibility overlays and our own windows-- // Sort by layer/id to usually get the top-most content window-- val candidateWindows = windows.filter { window ->-- val root = try { window.root } catch (_: Exception) { null }-- window.type != android.view.accessibility.AccessibilityWindowInfo.TYPE_ACCESSIBILITY_OVERLAY &&-- root?.packageName != ourPackage &&-- root != null-+ // Strategy:-+ // 1. Prefer TYPE_APPLICATION windows from OTHER packages (real content)-+ // 2. Fall back to any non-overlay window (including our OverlayActivity if it's TYPE_APPLICATION)-+ // 3. Last resort: use rootInActiveWindow-+-+ val allWindowsWithRoots = windows.map { window ->-+ try {-+ val root = window.root-+ Pair(window, root)-+ } catch (_: Exception) {-+ Pair(window, null)-+ }-+ }.filter { (_, root) -> root != null }-+-+ // Find other-package TYPE_APPLICATION windows (highest priority)-+ val otherPackageAppWindows = allWindowsWithRoots.filter { (window, root) ->-+ window.type == android.view.accessibility.AccessibilityWindowInfo.TYPE_APPLICATION &&-+ root?.packageName != ourPackage- }--- // prefer TYPE_APPLICATION-- val appWindow = candidateWindows.firstOrNull { it.type == android.view.accessibility.AccessibilityWindowInfo.TYPE_APPLICATION }-- if (appWindow != null) {-- android.util.Log.d("CTS_Node", "Found app window: ${appWindow.root?.packageName}")-- return appWindow.root-+ if (otherPackageAppWindows.isNotEmpty()) {-+ val window = otherPackageAppWindows.first()-+ val packageName = window.second?.packageName-+ android.util.Log.d("CTS_Node", "Found other-app TYPE_APPLICATION window: $packageName")-+ return window.second- }--- // fallback to any candidate-- val fallbackWindow = candidateWindows.firstOrNull()-- if (fallbackWindow != null) {-- android.util.Log.d("CTS_Node", "Fallback window: ${fallbackWindow.root?.packageName}")-- return fallbackWindow.root-+ // Fall back to any non-overlay window (includes our OverlayActivity TYPE_APPLICATION)-+ val nonOverlayWindows = allWindowsWithRoots.filter { (window, _) ->-+ window.type != android.view.accessibility.AccessibilityWindowInfo.TYPE_ACCESSIBILITY_OVERLAY-+ }-+-+ if (nonOverlayWindows.isNotEmpty()) {-+ val window = nonOverlayWindows.first()-+ val packageName = window.second?.packageName-+ android.util.Log.d("CTS_Node", "Found non-overlay window (fallback): $packageName")-+ return window.second- }- }--- // Final fallback logic-+ // Final fallback: use rootInActiveWindow (works for our OverlayActivity too)- val root = service.rootInActiveWindow-- if (root?.packageName != ourPackage) {-- android.util.Log.d("CTS_Node", "Defaulting to rootInActiveWindow: ${root?.packageName}")-+ if (root != null) {-+ android.util.Log.d("CTS_Node", "Using rootInActiveWindow fallback: ${root.packageName}")- return root- }--- android.util.Log.e("CTS_Node", "No suitable root node found (omitting our own package)")-+ android.util.Log.e("CTS_Node", "ERROR: No suitable root node found!")- return null- }-```-------## File: CopyTextOverlayManager.kt-Location: `app/src/main/java/com/akslabs/circletosearch/ui/components/CopyTextOverlayManager.kt`--### Change 1: Enhanced show() method--```diff- fun show(onDismiss: () -> Unit) {- if (dimView != null) return // Already visible-+ android.util.Log.d("CopyText", "show() called - setting up Copy Text overlay")- onDismissCallback = onDismiss-- val view = DimPunchOutView(context) { dismiss() }- dimView = view-@@ -83,13 +84,16 @@ class CopyTextOverlayManager(- try {- windowManager.addView(view, params)-+ android.util.Log.d("CopyText", "Overlay view added to window manager successfully")- } catch (e: Exception) {-+ android.util.Log.e("CopyText", "Failed to add overlay view: ${e.message}", e)- e.printStackTrace()- return- }-- // Kick off node scan-+ android.util.Log.d("CopyText", "Starting accessibility node scan...")- scanNodes(view)- }-```--### Change 2: Improved scanNodes() method--```diff- private fun scanNodes(view: DimPunchOutView) {- scanJob?.cancel()- scanJob = scope.launch {-+ val root = getRoot()-+ android.util.Log.d("CopyText", "scanNodes: Root node = $root, package = ${root?.packageName}")-+-+ if (root == null) {-+ android.util.Log.w("CopyText", "ERROR: getRoot() returned null! Cannot scan text nodes.")-+ detectedNodes.clear()-+ view.invalidate()-+ return@launch-+ }-+- val nodes = withContext(Dispatchers.Default) {-- collectTextNodes(getRoot())-+ collectTextNodes(root)- }-+ android.util.Log.d("CopyText", "Collected ${nodes.size} text nodes from accessibility tree")- detectedNodes.clear()- detectedNodes.addAll(nodes)- view.invalidate()- }- }-```--### Change 3: Rewritten collectTextNodes() method--```diff- private fun collectTextNodes(root: AccessibilityNodeInfo?): List<TextNode> {-- if (root == null) return emptyList()-+ if (root == null) {-+ android.util.Log.w("CopyText", "collectTextNodes called with null root!")-+ return emptyList()-+ }- val result = mutableListOf<TextNode>()- val queue = ArrayDeque<AccessibilityNodeInfo>()- queue.add(root)-+ var processedCount = 0-- while (queue.isNotEmpty()) {- val node = queue.removeFirst()-+ processedCount++- try {- val text = node.text ?: node.contentDescription- if (!text.isNullOrEmpty()) {- val rect = Rect()- node.getBoundsInScreen(rect)- if (!rect.isEmpty) {- val fullText = text.toString()- val words = splitIntoWords(fullText, rect)-- result.add(TextNode(-- id = java.util.UUID.randomUUID().toString(),-- fullText = fullText,-- bounds = rect,-- words = words-- ))-+ if (words.isNotEmpty()) {-+ result.add(TextNode(-+ id = java.util.UUID.randomUUID().toString(),-+ fullText = fullText,-+ bounds = rect,-+ words = words-+ ))-+ }- }- }-- for (i in 0 until node.childCount) {- node.getChild(i)?.let { queue.add(it) }- }-- } catch (_: Exception) {}-+ } catch (e: Exception) {-+ android.util.Log.e("CopyText", "Error processing accessibility node: ${e.message}")-+ }- }-+ android.util.Log.d("CopyText", "Processed $processedCount accessibility nodes, found ${result.size} text regions")- return result- }-```-------## Summary of Changes--### Files Modified: 2-1. CircleToSearchAccessibilityService.kt-2. CopyTextOverlayManager.kt--### Lines Changed-- CircleToSearchAccessibilityService.kt: ~60 lines (complete getRootNode rewrite)-- CopyTextOverlayManager.kt: ~40 lines added (logging and error handling)--### Breaking Changes: NONE-- All changes are backward compatible-- Only internal implementation details changed-- No API changes--### Performance Impact: NEGLIGIBLE-- Added logging (minimal overhead)-- Better error handling (prevents crashes)-- Same algorithmic complexity--### Testing Impact: POSITIVE-- Better diagnostics with enhanced logging-- Easier to debug future issues-- More robust error handling-------## Git Commands for Merge--```bash-# View the specific changes-git diff app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.kt-git diff app/src/main/java/com/akslabs/circletosearch/ui/components/CopyTextOverlayManager.kt--# Stage changes-git add app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.kt-git add app/src/main/java/com/akslabs/circletosearch/ui/components/CopyTextOverlayManager.kt--# Create commit-git commit -m "Fix: Copy Text feature - null accessibility node detection--- Replace getRootNode() logic to accept OverlayActivity windows-- Add proper fallback chain for window selection-- Enhance error handling and diagnostic logging in CopyTextOverlayManager-- Resolves issue where copy text button showed transparent screen only--Fixes: Copy Text not detecting or displaying any text-Ref: CircleToSearchAccessibilityService.kt + CopyTextOverlayManager.kt"--# Create branch for PR-git checkout -b fix/copy-text-accessibility-node-git push origin fix/copy-text-accessibility-node-```diff --git a/COPY_TEXT_TESTING_CHECKLIST.md b/COPY_TEXT_TESTING_CHECKLIST.mddeleted file mode 100644index 334f2af..0000000--- a/COPY_TEXT_TESTING_CHECKLIST.md+++ /dev/null@@ -1,288 +0,0 @@-# Copy Text Feature Fix - Verification Checklist--## Pre-Deployment Verification--### Code Changes-- [x] CircleToSearchAccessibilityService.kt - getRootNode() rewritten-- [x] CopyTextOverlayManager.kt - Enhanced error handling and logging-- [x] No syntax errors (verified with get_errors)-- [x] All changes in production code (not debug-only)--### Logic Verification-- [x] getRootNode() now returns valid nodes when OverlayActivity is active-- [x] Proper window priority: Other apps > Our non-overlay windows > fallback-- [x] Null safety improved at multiple levels-- [x] Debug logging added for troubleshooting-------## Post-Deployment Testing Checklist--### Test Environment Setup-```bash-Device: [Your Android Phone/Emulator]-Android Version: [e.g., Android 13, 14, 15]-App Version: [Build from fixed code]-Accessibility Service: [CircleToSearchAccessibilityService enabled]-```--### Test 1: Basic Copy Text Functionality-- [ ] Open Chrome and load a webpage with text-- [ ] Double-tap status bar to trigger Circle to Search-- [ ] Click "Copy Text" button in bottom bar-- [ ] Verify: Text regions appear with blue highlighting-- [ ] Verify: Pulsing glow animation on text regions-- [ ] Close the overlay (tap close button)-- [ ] Result: ✅ PASS / ❌ FAIL--### Test 2: Text Selection-- [ ] Repeat Test 1 up to step 4-- [ ] Tap on one text region to enter it-- [ ] Verify: Text becomes darker blue (selected word style)-- [ ] Verify: Selection handles appear at start and end-- [ ] Verify: Floating toolbar appears with Copy/SelectAll/Cancel buttons-- [ ] Result: ✅ PASS / ❌ FAIL--### Test 3: Word-by-Word Selection-- [ ] Repeat Test 2 up to step 5-- [ ] Tap on different words within the text region-- [ ] Verify: Selection expands/changes to include tapped word-- [ ] Verify: Handles move to new start/end positions-- [ ] Result: ✅ PASS / ❌ FAIL--### Test 4: Handle Dragging-- [ ] Repeat Test 2 up to step 5-- [ ] Drag the left (start) handle to different words-- [ ] Verify: Selection updates in real-time-- [ ] Verify: Haptic feedback triggers on handle move-- [ ] Drag the right (end) handle to extend selection-- [ ] Verify: Selection range updates correctly-- [ ] Result: ✅ PASS / ❌ FAIL--### Test 5: Select All Function-- [ ] Repeat Test 2 up to step 5-- [ ] Tap "Select All" in the floating toolbar-- [ ] Verify: All words in the region become selected-- [ ] Verify: Handles move to cover entire text region-- [ ] Result: ✅ PASS / ❌ FAIL--### Test 6: Copy to Clipboard-- [ ] Repeat Test 2 up to step 5-- [ ] Tap "Copy" button in floating toolbar-- [ ] Verify: Toast appears saying "Text copied ✓"-- [ ] Verify: Overlay automatically dismisses-- [ ] Open Notes app (or any text editor)-- [ ] Long-press to open paste menu-- [ ] Paste the content (Ctrl+V or app's paste button)-- [ ] Verify: Selected text appears in the app-- [ ] Result: ✅ PASS / ❌ FAIL--### Test 7: Different App Scenarios-Test with multiple apps to ensure broad compatibility:--#### Test 7A: Gmail-- [ ] Open Gmail and read an email-- [ ] Trigger Copy Text overlay-- [ ] Verify: Email text is highlighted-- [ ] Select and copy a sentence-- [ ] Verify: Copied text is accurate--#### Test 7B: WhatsApp/Messenger-- [ ] Open chat conversation-- [ ] Trigger Copy Text overlay-- [ ] Verify: Chat messages are highlighted-- [ ] Select and copy a message-- [ ] Verify: Copied text matches exactly--#### Test 7C: Settings App-- [ ] Open Settings app-- [ ] Trigger Copy Text overlay-- [ ] Verify: Settings text appears highlighted-- [ ] Copy a setting name/description--#### Test 7D: Web Browser-- [ ] Open any website-- [ ] Trigger Copy Text overlay-- [ ] Verify: Webpage text is highlighted (including headers, body, etc.)-- [ ] Copy multiple paragraphs--### Test 8: Scrollable Content-- [ ] Open long webpage or document-- [ ] Trigger Copy Text overlay when text is visible-- [ ] Scroll up/down in the app (below the overlay)-- [ ] Verify: Highlighted regions update as content scrolls-- [ ] Verify: New text regions appear as they scroll into view-- [ ] Result: ✅ PASS / ❌ FAIL--### Test 9: Edge Cases--#### Test 9A: App with No Text-- [ ] Open an app with mostly images/UI elements-- [ ] Trigger Copy Text overlay-- [ ] Verify: Overlay appears with dim background only-- [ ] Verify: No text highlights appear (expected)-- [ ] Verify: Close button is still functional--#### Test 9B: Rapid Activation/Deactivation-- [ ] Open Copy Text overlay-- [ ] Immediately close it (before scan completes)-- [ ] Verify: No crashes or error messages-- [ ] Verify: Overlay cleanly dismisses--#### Test 9C: Switching Between Apps-- [ ] Open Copy Text in App A-- [ ] While overlay is visible, switch to App B-- [ ] Verify: Overlay shows text from currently active app-- [ ] Verify: Text updates appropriately--### Test 10: Accessibility Service Status-- [ ] Go to Settings → Accessibility-- [ ] Verify: CircleToSearchAccessibilityService is enabled-- [ ] Grant any requested permissions if needed-- [ ] Disable and re-enable the service-- [ ] Verify: Copy Text still works after re-enabling-------## Logcat Verification--### Enable Logcat Filtering-```bash-adb logcat | grep -E "CTS_Node|CopyText"-```--### Expected Log Patterns--#### Successful Text Detection-```-D/CTS_Node: getRootNode triggered. Our package: com.akslabs.circletosearch-D/CTS_Node: Window count: 3-D/CTS_Node: Found non-overlay window (fallback): com.akslabs.circletosearch-D/CopyText: show() called - setting up Copy Text overlay-D/CopyText: Overlay view added to window manager successfully-D/CopyText: Starting accessibility node scan...-D/CopyText: scanNodes: Root node = AccessibilityNodeInfo@..., package = com.akslabs.circletosearch-D/CopyText: Collected 47 text nodes from accessibility tree-D/CopyText: Processed 156 accessibility nodes, found 47 text regions-```--#### No Text Found (Edge Case)-```-D/CopyText: show() called - setting up Copy Text overlay-D/CopyText: Overlay view added to window manager successfully-D/CopyText: Starting accessibility node scan...-D/CopyText: scanNodes: Root node = AccessibilityNodeInfo@..., package = com.someapp.package-D/CopyText: Collected 0 text nodes from accessibility tree-D/CopyText: Processed 23 accessibility nodes, found 0 text regions-```--#### Error Scenarios (Should NOT see these)-```-❌ ERROR: getRoot() returned null! Cannot scan text nodes.-❌ ERROR: getRootNode triggered. Our package: ...-❌ No suitable root node found (omitting our own package)-```-------## Performance Verification--### Metrics to Monitor--#### Overlay Appearance Time-- [ ] Overlay should appear within **500ms** of tapping "Copy Text"-- [ ] Measure: From button tap to first visual update--#### Text Detection Time-- [ ] Text regions should highlight within **1-2 seconds** for normal amount of text-- [ ] Measure: From overlay appearance to text highlights visible--#### Memory Usage-- [ ] No significant memory leak when repeatedly opening/closing overlay-- [ ] Monitor: adb shell dumpsys meminfo com.akslabs.circletosearch--### Acceptable Performance Ranges-| Operation | Target | Max Acceptable |-|-----------|--------|---|-| Overlay activation | 500ms | 1000ms |-| Text scanning | 1s | 3s |-| Selection update (drag) | <100ms | 200ms |-| Copy action | <100ms | 500ms |-------## Regression Testing--### Verify Existing Features Still Work-- [ ] Status bar overlay rendering-- [ ] Double-tap gesture detection-- [ ] Circle drawing and image selection-- [ ] Reverse image search (Google Lens)-- [ ] Search results display in bottom sheet-- [ ] WebView tab switching-- [ ] Dark mode toggle-- [ ] Desktop mode toggle-- [ ] Share functionality-- [ ] Other bottom bar buttons-------## Issue Reporting Template--If you encounter issues during testing, please report:--```-**Issue Title**: [Brief description]--**Device Info**:-- Phone Model: [e.g., Samsung Galaxy S24]-- Android Version: [e.g., Android 15]-- App Build: [Date/Version]--**Steps to Reproduce**:-1. [Step 1]-2. [Step 2]-3. ...--**Expected Behavior**:-[What should happen]--**Actual Behavior**:-[What actually happens]--**Logcat Output**:-[adb logcat output with CTS_ and CopyText tags]--**Screenshots/Videos**:-[If available]--**Severity**: [Critical/High/Medium/Low]-```-------## Sign-Off--- [ ] **QA Tester**: [Name] Date: [Date]-- [ ] **Developer**: [Name] Date: [Date]-- [ ] All tests passed-- [ ] No regressions found-- [ ] Ready for production deployment-------## Post-Deployment (Production)--### Monitor-- [ ] User reports of "Text not showing" issues-- [ ] Crash reports related to CopyTextOverlayManager-- [ ] Accessibility service crashes or disabling-- [ ] Performance issues (slow text detection)--### Support Troubleshooting-If users report issues:-1. Have them enable Settings → Accessibility logging-2. Collect logcat with CTS_ and CopyText filters-3. Check if CircleToSearchAccessibilityService is enabled-4. Try disabling and re-enabling the service-5. Check if device has newer Android version (compatibility)diff --git a/README_COPY_TEXT_FIX.md b/README_COPY_TEXT_FIX.mddeleted file mode 100644index 9f8287a..0000000--- a/README_COPY_TEXT_FIX.md+++ /dev/null@@ -1,321 +0,0 @@-# Circle to Search - Copy Text Feature Fix--## 🎯 What Was Fixed--The Copy Text feature was completely broken - when users clicked the "Copy Text" button, they saw only a transparent overlay with a close button, but NO text regions were detected or highlighted. This fix resolves the issue by properly retrieving the accessibility node tree.--### The Issue-- ❌ User clicks "Copy Text" button-- ❌ Transparent overlay appears-- ❌ NO text regions highlighted-- ❌ NO way to select or copy text-- ❌ Button seemed broken/non-functional--### The Fix-- ✅ getRootNode() now returns valid accessibility nodes-- ✅ Text regions properly detected and highlighted-- ✅ Full text selection workflow functional-- ✅ Copy to clipboard works as intended-- ✅ Better error handling and logging-------## 📋 Technical Summary--### Root Cause-The `CircleToSearchAccessibilityService.getRootNode()` function was returning `null` when the app's OverlayActivity became the active window, preventing text node detection.--### Solution-Rewrote the window selection logic to:-1. Prioritize other apps' TYPE_APPLICATION windows-2. Fall back to our OverlayActivity if no other app is active-3. Use rootInActiveWindow as final fallback (no filtering)-4. Added comprehensive logging for diagnostics--### Files Modified-| File | Changes | Lines |-|------|---------|-------|-| `CircleToSearchAccessibilityService.kt` | Complete getRootNode() rewrite | ~60 |-| `CopyTextOverlayManager.kt` | Enhanced error handling + logging | ~40 |-------## 🚀 How to Deploy--### 1. Apply Changes-The changes have been implemented in the fixed code at:-```-C:\Users\ashin\AndroidStudioProjects\CircleToSearch-```--### 2. Build-```bash-cd C:\Users\ashin\AndroidStudioProjects\CircleToSearch-./gradlew clean assembleDebug-# APK: app/build/outputs/apk/debug/app-debug.apk-```--### 3. Install-```bash-adb uninstall com.akslabs.circletosearch-adb install app/build/outputs/apk/debug/app-debug.apk-```--### 4. Verify Accessibility Service-- Settings → Accessibility → Circle to Search-- Enable "CircleToSearchAccessibilityService"-- Grant any required permissions-------## ✅ Quick Test--1. Open any app with text (Chrome, Gmail, Notes, etc.)-2. Double-tap the status bar-3. Click "Copy Text" button-4. **Expected**: Text regions appear with blue highlighting-5. Tap to select text → Copy button should work-------## 📊 Before & After Comparison--### Before (Broken)-```-User taps "Copy Text"- ↓-getRootNode() called- ↓-Filters out our package (bug!)- ↓-candidateWindows = []- ↓-Returns NULL- ↓-No text detected- ↓-Transparent overlay only ❌-```--### After (Fixed)-```-User taps "Copy Text"- ↓-getRootNode() called- ↓-Checks for other apps first- ↓-Falls back to our OverlayActivity- ↓-Returns valid AccessibilityNodeInfo- ↓-Text nodes detected & highlighted- ↓-Full copy workflow functional ✅-```-------## 🔍 Verification--### Check Logs-```bash-adb logcat | grep -E "CTS_Node|CopyText"-```--**Should see**:-```-D/CTS_Node: getRootNode triggered. Our package: com.akslabs.circletosearch-D/CTS_Node: Window count: 3-D/CTS_Node: Found non-overlay window (fallback): com.akslabs.circletosearch-D/CopyText: show() called - setting up Copy Text overlay-D/CopyText: Collected 47 text nodes from accessibility tree-```-------## 🧪 Testing Checklist--### Basic Functionality-- [ ] Text appears highlighted when Copy Text is activated-- [ ] Can select individual words-- [ ] Can extend selection with handles-- [ ] Copy button copies text to clipboard-- [ ] Toast shows "Text copied ✓"--### Edge Cases-- [ ] Works in Chrome/WebView-- [ ] Works in Gmail-- [ ] Works in WhatsApp-- [ ] Works with scrollable content-- [ ] Handles apps with no text gracefully-- [ ] No crashes when switching apps--### Performance-- [ ] Overlay appears within 1 second-- [ ] Text detected within 2 seconds-- [ ] No memory leaks on repeated use-- [ ] Smooth handle dragging-------## 📝 Code Changes at a Glance--### Change 1: Window Selection Logic-```kotlin-// OLD: Filters out our package entirely-val candidateWindows = windows.filter { window ->- root?.packageName != ourPackage // ❌ WRONG-}--// NEW: Prioritizes other apps, allows ours as fallback-val otherPackageAppWindows = allWindowsWithRoots.filter {- root?.packageName != ourPackage // Only exclude OTHER packages-}-// Then falls back to our OverlayActivity if needed-```--### Change 2: Null Safety-```kotlin-// OLD: No safety checks-val nodes = collectTextNodes(getRoot())--// NEW: Validates root before use-val root = getRoot()-if (root == null) {- android.util.Log.w("CopyText", "ERROR: getRoot() returned null!")- return // Handle gracefully-}-val nodes = collectTextNodes(root)-```--### Change 3: Diagnostic Logging-```kotlin-// Added throughout:-android.util.Log.d("CopyText", "Collected ${nodes.size} text nodes from accessibility tree")-android.util.Log.d("CopyText", "Processed $processedCount accessibility nodes, found ${result.size} text regions")-```-------## 🐛 Known Limitations--1. **OCR Not Available**: Copy Text uses accessibility nodes, not OCR. Works best with:- - Text in EditText, TextView components- - Web content from WebView/Chrome- - Most standard Android apps- - Not for: Image text, drawings, handwriting--2. **Scrollable Content**: Text updates as you scroll, but must scroll within the app (not in overlay)--3. **Android Version**: Requires Android 5.0+ (API level 21+)-------## 📚 Documentation Files--| File | Purpose |-|------|---------|-| `COPY_TEXT_FIX_COMPLETE.md` | Executive summary |-| `COPY_TEXT_FIX_SUMMARY.md` | Detailed technical explanation |-| `COPY_TEXT_CODE_CHANGES.md` | Side-by-side code comparison |-| `COPY_TEXT_TESTING_CHECKLIST.md` | Complete QA test suite |-| `COPY_TEXT_PATCH.diff` | Git-style unified diff |-| This README | Quick reference guide |-------## 🔧 Troubleshooting--### "Text still not showing"-1. Enable CircleToSearchAccessibilityService in Settings → Accessibility-2. Disable and re-enable the service-3. Check logcat: `adb logcat | grep CTS_Node`-4. Ensure app is not excluded from using accessibility--### "Copy button doesn't work"-1. Check if text is actually selected (should be darker blue)-2. Look for floating toolbar with Copy/SelectAll/Cancel buttons-3. Check app has clipboard access (should be granted)-4. Try copying to Notes app to verify-5. Check logcat for errors--### "Overlay not showing"-1. Verify STATUS_BAR_OVERLAY permission is granted-2. Check if another app is using the accessibility overlay-3. Restart device-4. Uninstall and reinstall app-5. Check Android version (needs 5.0+)-------## 🎓 How Copy Text Works--### User Flow-1. Double-tap status bar → Circle to Search activates-2. Click "Copy Text" button → OverlayActivity becomes active-3. **getRootNode()** retrieves accessibility tree of current window-4. **scanNodes()** traverses tree and extracts text regions-5. **collectTextNodes()** builds list of selectable text with bounds-6. **DimPunchOutView** renders:- - 15% black overlay across full screen- - Highlighted regions with pulsing blue glow- - Selection regions darker blue- - Floating toolbar for actions-7. User selects text → stored in clipboard-8. User pastes elsewhere--### Technical Architecture-```-OverlayActivity- ↓-CircleToSearchAccessibilityService.getRootNode()- ↓-CopyTextOverlayManager.show()- ↓-scanNodes() → collectTextNodes()- ↓-List<TextNode> with bounds and words- ↓-DimPunchOutView renders highlights- ↓-GestureDetector handles taps/drags- ↓-ClipboardManager copies selected text-```-------## ⚖️ License & Attribution--**Original Author**: AKS-Labs-**License**: GNU General Public License v3.0+-**This Fix**: Resolves accessibility node detection bug in Copy Text feature-------## 📞 Support--For issues or questions:-1. Check the testing checklist-2. Review logcat with CTS_Node and CopyText tags-3. Verify accessibility service is enabled-4. Check Android version compatibility-5. Reference the detailed documentation files-------## ✨ Summary--This fix enables the Copy Text feature to work as designed:-- **Detects** text from the accessibility tree-- **Highlights** selectable text regions-- **Allows** precise word selection with handles-- **Copies** selected text to clipboard-- **Works** across all Android apps--The implementation is robust, includes comprehensive error handling, and provides detailed logging for troubleshooting.--**Status**: ✅ Ready for deployment-**Risk**: Low (isolated changes, no API modifications)-**Benefit**: High (completely restores broken feature)diff --git a/SearchMethodSelector.kt.snippet b/SearchMethodSelector.kt.snippetdeleted file mode 100644index 8aa9873..0000000--- a/SearchMethodSelector.kt.snippet+++ /dev/null@@ -1,55 +0,0 @@-@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun SearchMethodSelector(- isLensOnly: Boolean,- onMethodChange: (Boolean) -> Unit-) {- Column {- Text(- text = "SEARCH METHOD",- style = MaterialTheme.typography.labelLarge.copy(- fontWeight = FontWeight.Bold,- letterSpacing = 1.sp- ),- color = MaterialTheme.colorScheme.primary,- modifier = Modifier.padding(bottom = 12.dp)- )-- SingleChoiceSegmentedButtonRow(- modifier = Modifier.fillMaxWidth()- ) {- SegmentedButton(- shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2),- onClick = { onMethodChange(false) },- selected = !isLensOnly,- icon = { SegmentedButtonDefaults.Icon(!isLensOnly) },- colors = SegmentedButtonDefaults.colors(- activeContainerColor = MaterialTheme.colorScheme.primaryContainer,- activeContentColor = MaterialTheme.colorScheme.onPrimaryContainer- )- ) {- Row(verticalAlignment = Alignment.CenterVertically) {- Icon(Icons.Default.ManageSearch, contentDescription = null, modifier = Modifier.size(18.dp))- Spacer(modifier = Modifier.width(8.dp))- Text("Multi-Search", style = MaterialTheme.typography.labelLarge)- }- }- SegmentedButton(- shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2),- onClick = { onMethodChange(true) },- selected = isLensOnly,- icon = { SegmentedButtonDefaults.Icon(isLensOnly) },- colors = SegmentedButtonDefaults.colors(- activeContainerColor = MaterialTheme.colorScheme.primaryContainer,- activeContentColor = MaterialTheme.colorScheme.onPrimaryContainer- )- ) {- Row(verticalAlignment = Alignment.CenterVertically) {- Icon(Icons.Default.AutoFixHigh, contentDescription = null, modifier = Modifier.size(18.dp))- Spacer(modifier = Modifier.width(8.dp))- Text("Google Lens", style = MaterialTheme.typography.labelLarge)- }- }- }- }-}diff --git a/app/src/main/java/com/akslabs/circletosearch/ocr/TesseractEngine.kt b/app/src/main/java/com/akslabs/circletosearch/ocr/TesseractEngine.ktindex 9d07391..dc72ee1 100644--- a/app/src/main/java/com/akslabs/circletosearch/ocr/TesseractEngine.kt+++ b/app/src/main/java/com/akslabs/circletosearch/ocr/TesseractEngine.kt@@ -67,83 +67,99 @@ object TesseractEngine {val fullAppText = tess.getUTF8Text()Log.d(TAG, "Tesseract recognition complete. Full text length: ${fullAppText?.length ?: 0}")- // We iterate over text lines so we can group words together into a TextNode,- // which gives the user a cleaner multi-word bounding box for copying blocks.val iterator = tess.resultIterator ?: run {Log.e(TAG, "ResultIterator is null after recognition!")tess.recycle()return@withContext emptyList()}-+ val allDetectedWords = mutableListOf<Word>()iterator.begin()do {- val blockText = iterator.getUTF8Text(TessBaseAPI.PageIteratorLevel.RIL_TEXTLINE)- if (blockText.isNullOrBlank()) continue+ val wordText = iterator.getUTF8Text(TessBaseAPI.PageIteratorLevel.RIL_WORD)+ if (wordText.isNullOrBlank()) continue- val blockRectParams = iterator.getBoundingRect(TessBaseAPI.PageIteratorLevel.RIL_TEXTLINE)- ?: iterator.getBoundingBox(TessBaseAPI.PageIteratorLevel.RIL_TEXTLINE)+ val wordRectParams = iterator.getBoundingRect(TessBaseAPI.PageIteratorLevel.RIL_WORD)+ ?: iterator.getBoundingBox(TessBaseAPI.PageIteratorLevel.RIL_WORD)- val parentRect = if (blockRectParams is Rect) {- blockRectParams- } else if (blockRectParams is IntArray) {- Rect(blockRectParams[0], blockRectParams[1], blockRectParams[2], blockRectParams[3])+ val wRect = if (wordRectParams is Rect) {+ wordRectParams+ } else if (wordRectParams is IntArray) {+ Rect(wordRectParams[0], wordRectParams[1], wordRectParams[2], wordRectParams[3])} else {continue}- if (parentRect.isEmpty || parentRect.width() < 5) continue+ if (wRect.isEmpty || wRect.width() < 2) continue- val words = mutableListOf<Word>()- // Standard Tesseract integration for Words within a block is complex via iterator if we don't restart iteration,- // so we just tokenize the line based on the bounding box proportionally as we used to do,- // or we treat the whole block as one word segment for now since Tesseract handles lines well.- // For optimal UX, we'll mimic the splitIntoWords logic.+ // We'll wrap each word in a Word object and put it in a single TextNode for now,+ // or group them by line if we want to maintain the "TextNode" structure.+ // For simplified global selection, a single TextNode per line or even per word is fine.+ // Let's group by line to keep the visual "block" grouping if needed.+ // Actually, the new global selection treats all words linearly, so we can just+ // create one TextNode per word or one per line.+ // Let's try to group them by the same line to keep the UI clean.- // Let's do simple proportional splitting- val segments = blockText.split(Regex("\\s+")).filter { it.isNotBlank() }- var startOffsetChars = 0- val totalChars = blockText.length.toFloat()+ val wordBounds = android.graphics.RectF(wRect)+ val wordObj = Word(+ text = wordText,+ index = allDetectedWords.size,+ startIndex = 0, // Not strictly needed for global selection+ endIndex = wordText.length,+ bounds = wordBounds+ )++ // Add to a generic list first, then group by Y-coordinate similarity to form lines+ allDetectedWords.add(wordObj)++ } while (iterator.next(TessBaseAPI.PageIteratorLevel.RIL_WORD))++ // Group words into lines based on Y-overlap for better UI grouping+ val sortedWords = allDetectedWords.sortedBy { it.bounds.top }+ val lines = mutableListOf<MutableList<Word>>()++ if (sortedWords.isNotEmpty()) {+ var currentLine = mutableListOf<Word>()+ currentLine.add(sortedWords[0])+ lines.add(currentLine)- segments.forEachIndexed { index, w ->- val wStartPct = startOffsetChars / totalChars- val wEndPct = (startOffsetChars + w.length) / totalChars-- val wLeft = parentRect.left + (parentRect.width() * wStartPct).toInt()- val wRight = parentRect.left + (parentRect.width() * wEndPct).toInt()-- val wordBounds = android.graphics.RectF(- wLeft.toFloat(),- parentRect.top.toFloat(),- wRight.toFloat(),- parentRect.bottom.toFloat()- )+ for (i in 1 until sortedWords.size) {+ val prev = currentLine.last()+ val curr = sortedWords[i]+ // If the vertical centers are close enough, they are likely on the same line+ // Increased tolerance (0.7f) to better capture slightly misaligned text+ val verticalOverlap = Math.abs(curr.bounds.centerY() - prev.bounds.centerY()) < (prev.bounds.height() * 0.7f)- words.add(- Word(- text = w,- index = index,- startIndex = startOffsetChars,- endIndex = startOffsetChars + w.length,- bounds = wordBounds- )- )-- startOffsetChars += w.length + 1 // +1 for the space (simplified)+ if (verticalOverlap) {+ currentLine.add(curr)+ } else {+ currentLine = mutableListOf(curr)+ lines.add(currentLine)+ }}+ }++ lines.forEach { lineWords ->+ // Sort words in line by X-coordinate+ val finalLineWords = lineWords.sortedBy { it.bounds.left }+ val fullText = finalLineWords.joinToString(" ") { it.text }- if (words.isNotEmpty()) {- result.add(- TextNode(- id = UUID.randomUUID().toString(),- fullText = blockText,- bounds = parentRect,- words = words- )- )+ val lineBounds = Rect()+ finalLineWords.forEach { w ->+ val r = Rect()+ w.bounds.roundOut(r)+ if (lineBounds.isEmpty()) lineBounds.set(r) else lineBounds.union(r)}- } while (iterator.next(TessBaseAPI.PageIteratorLevel.RIL_TEXTLINE))+ result.add(+ TextNode(+ id = UUID.randomUUID().toString(),+ fullText = fullText,+ bounds = lineBounds,+ words = finalLineWords+ )+ )+ }iterator.delete()tess.recycle()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.ktindex d10a31b..5cfa6ba 100644--- a/app/src/main/java/com/akslabs/circletosearch/ui/components/CopyTextOverlayManager.kt+++ b/app/src/main/java/com/akslabs/circletosearch/ui/components/CopyTextOverlayManager.kt@@ -24,24 +24,27 @@ import android.annotation.SuppressLintimport android.content.ClipDataimport android.content.ClipboardManagerimport android.content.Context-import android.graphics.Canvas-import android.graphics.Color-import android.graphics.Paint-import android.graphics.Rect-import android.graphics.RectF-import android.graphics.PorterDuff-import android.graphics.PorterDuffXfermode-import android.view.GestureDetector-import android.view.MotionEvent-import android.view.View-import android.view.accessibility.AccessibilityNodeInfo+import android.graphics.*+import android.view.*+import android.view.accessibility.*+import android.widget.FrameLayout+import android.widget.PopupMenuimport 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+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.ui.Alignment+import kotlinx.coroutines.*+import java.util.UUID/** Simple holder for a floating-toolbar button's label and screen hit-rect. */private class ToolbarButton(val label: String, val rect: Rect)@@ -66,7 +69,8 @@ class CopyTextOverlayManager(// Detected text nodes and flattened words (sorted by reading order)private val detectedNodes = mutableListOf<TextNode>()- private val allWords = mutableListOf<Word>()+ private var allWords: List<Word> = emptyList()+ private var startSelectionIdx = -1 // For dragging// Global selection state (indices into 'allWords')private var globalSelectionStart: Int = -1@@ -75,16 +79,111 @@ class CopyTextOverlayManager(// ── 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() }++ // Full Reset state for "fresh start"+ globalSelectionStart = -1+ globalSelectionEnd = -1+ startSelectionIdx = -1+ detectedNodes.clear()+ allWords = emptyList()++ 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() },+ onMenu = { showSettingsMenu() }+ )+ }+ }+ }+ }+ container.addView(topBar)android.util.Log.d("CopyText", "Starting accessibility node scan…")scanNodes(view)- return view+ return container+ }++ @Composable+ private fun TopBarUI(onClose: () -> Unit, onMenu: () -> Unit) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .statusBarsPadding()+ .padding(16.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ // Close Button (Exact match from main UI)+ IconButton(+ onClick = onClose,+ modifier = Modifier+ .background(android.graphics.Color.GRAY.toComposeColor().copy(alpha = 0.5f), CircleShape)+ .size(40.dp)+ ) {+ Icon(Icons.Default.Close, contentDescription = "Close", tint = ComposeColor.White)+ }++ // Menu Button (Exact match from main UI)+ IconButton(+ onClick = onMenu,+ modifier = Modifier+ .background(android.graphics.Color.GRAY.toComposeColor().copy(alpha = 0.5f), CircleShape)+ .size(40.dp)+ ) {+ Icon(Icons.Default.MoreVert, contentDescription = "Menu", tint = ComposeColor.White)+ }+ }+ }++ private fun Int.toComposeColor(): ComposeColor = ComposeColor(this)++ private fun showSettingsMenu() {+ val anchor = dimView ?: return+ val popup = PopupMenu(context, anchor, Gravity.END)+ popup.menu.add("Select Language")+ popup.menu.add("Import traineddata")++ popup.setOnMenuItemClickListener { item ->+ when (item.title) {+ "Select Language" -> showLanguageSelector()+ "Import traineddata" -> triggerImport()+ }+ true+ }+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {+ popup.setForceShowIcon(true)+ }+ popup.show()+ }++ private fun showLanguageSelector() {+ val languages = listOf("English", "Hindi", "French", "Spanish", "German", "Chinese", "Japanese")+ val codes = listOf("eng", "hin", "fra", "spa", "deu", "chi_sim", "jpn")++ android.app.AlertDialog.Builder(context)+ .setTitle("Select OCR Language")+ .setItems(languages.toTypedArray()) { _, which ->+ val code = codes[which]+ context.getSharedPreferences("OcrSettings", Context.MODE_PRIVATE)+ .edit().putString("selected_lang", code).apply()+ Toast.makeText(context, "Language changed to ${languages[which]}. Restarting scan...", Toast.LENGTH_SHORT).show()+ rescanNodes()+ }+ .show()+ }++ private fun triggerImport() {+ Toast.makeText(context, "Please place .traineddata files in /sdcard/Android/data/${context.packageName}/files/tessdata/", Toast.LENGTH_LONG).show()}fun dismiss() {@@ -123,18 +222,17 @@ class CopyTextOverlayManager(android.util.Log.d("CopyText", "Live OCR scan complete: ${sortedNodes.size} text nodes")detectedNodes.clear()- allWords.clear()+ val tempAllWords = mutableListOf<Word>()detectedNodes.addAll(sortedNodes)// Flatten words and update their global index- var globalIdx = 0sortedNodes.forEach { node ->node.words.forEach { word ->// We reuse the Word object but treat it globally- allWords.add(word)- globalIdx+++ tempAllWords.add(word)}}+ allWords = tempAllWordsview.invalidate()}@@ -146,11 +244,10 @@ class CopyTextOverlayManager(@SuppressLint("ClickableViewAccessibility")inner class DimPunchOutView(- context: Context,- private val onBackPress: () -> Unit+ context: Context) : View(context) {-+ private val density = resources.displayMetrics.density// ── Coordinate helpers ────────────────────────────────────────────────@@ -205,6 +302,12 @@ class CopyTextOverlayManager(isAntiAlias = false}+ private val textPaint = Paint().apply {+ color = Color.WHITE+ textSize = 32f+ isAntiAlias = true+ textAlign = Paint.Align.CENTER+ }private val selectedWordPaint = Paint().apply {@@ -308,44 +411,50 @@ class CopyTextOverlayManager(// We'll group selected words by their Word.bounds.centerY() (rounded)val selectedWords = (start..end).mapNotNull { allWords.getOrNull(it) }- selectedWords.groupBy { (it.bounds.centerY() / 10).toInt() }.forEach { (_, wordsInLine) ->+ // Group words by line segments+ val highlightPath = Path()+ selectedWords.groupBy { (it.bounds.centerY() / 20).toInt() }.forEach { (_, wordsInLine) ->if (wordsInLine.isEmpty()) return@forEach- // Create one unified Rect representing the entire highlight for this line segmentval first = wordsInLine.minBy { it.bounds.left }val last = wordsInLine.maxBy { it.bounds.right }- val combinedRect = RectF(+ val lineRect = RectF(first.bounds.left,wordsInLine.minOf { it.bounds.top },last.bounds.right,wordsInLine.maxOf { it.bounds.bottom })- val localLineHighlight = toLocal(combinedRect)- localLineHighlight.inset(-4f, -4f) // Slight overlap for smoothness- canvas.drawRoundRect(localLineHighlight, 12f, 12f, selectedWordPaint)+ val localLineHighlight = toLocal(lineRect)+ localLineHighlight.inset(-16f, -12f)+ highlightPath.addRoundRect(localLineHighlight, 12f, 12f, Path.Direction.CW)}+ // Draw all highlights IN ONE CALL to prevent alpha stacking (darker overlaps)+ canvas.drawPath(highlightPath, selectedWordPaint)- // 4. Handles & Toolbar (Anchor to the overall selection)+ // 4. Handles & Toolbarval firstWord = allWords[start]val lastWord = allWords[end]-val startLocal = toLocal(firstWord.bounds)val endLocal = toLocal(lastWord.bounds)drawHandle(canvas, startLocal.left, startLocal.top, isStart = true)drawHandle(canvas, endLocal.right, endLocal.bottom, isStart = false)- // Toolbar anchored to the encompassing rect of the whole selectionval encompassing = RectF(firstWord.bounds)selectedWords.forEach { encompassing.union(it.bounds) }drawFloatingToolbar(canvas, toLocal(encompassing))}+ // 5. Top Bar is now handled by ComposeView in the FrameLayout+ // so we don't draw it manually here anymore.+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)@@ -353,56 +462,71 @@ class CopyTextOverlayManager(}private fun drawFloatingToolbar(canvas: Canvas, anchor: RectF) {- val btnW = 170- val btnH = 80- val padding = 12- val gap = 8- val labels = listOf("Copy", "Share", "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 - 32- if (top < 0) top = anchor.bottom.toInt() + 32- if (left < 10) left = 10- if (left + totalW > width - 10) left = width - totalW - 10-- val barRect = RectF(left.toFloat(), top.toFloat(), (left + totalW).toFloat(), (top + totalH).toFloat())+ val buttonLabels = listOf("Copy", "Share", "All", "Cancel")+ val btnPadding = 16f * density // More compact+ val btnHeight = 36f * density // Match native pill height+ val btnSpacing = 6f * density+ val m = 10f * density- toolbarBgPaint.setShadowLayer(20f, 0f, 8f, Color.parseColor("#44000000"))- canvas.drawRoundRect(barRect, 40f, 40f, toolbarBgPaint)- toolbarBgPaint.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" || label == "Share") {- val pillPaint = Paint(toolbarActionPaint).apply { alpha = 35 }- canvas.drawRoundRect(bRectF, 40f, 40f, pillPaint)- canvas.drawText(label, bRectF.centerX(), bRectF.centerY() + 14f, toolbarActionPaint.apply { style = Paint.Style.FILL; textSize = 34f })- } else {- canvas.drawText(label, bRectF.centerX(), bRectF.centerY() + 14f, toolbarTextPaint.apply { textSize = 34f })- }+ toolbarActionPaint.textSize = 30f // Slightly smaller+ val labelWidths = buttonLabels.map { toolbarActionPaint.measureText(it) + btnPadding * 2 }+ val totalWidth = labelWidths.sum() + (buttonLabels.size - 1) * btnSpacing + m * 2++ val tx = (width - totalWidth) / 2+ var ty = anchor.bottom + 30f * density+ if (ty + btnHeight + m * 2 > height - 100f) ty = anchor.top - (btnHeight + m * 2) - 30f * density++ val toolbarRect = RectF(tx, ty, tx + totalWidth, ty + btnHeight + m * 2)++ // Dynamic Background with shadow+ 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)}- toolbarButtons = buttons+ canvas.drawRoundRect(toolbarRect, 22f * density, 22f * density, shadowPaint)+ canvas.drawRoundRect(toolbarRect, 22f * density, 22f * density, toolbarBgPaint.apply { color = dynamicSurface })++ var currentX = tx + m+ val newButtons = mutableListOf<ToolbarButton>()++ buttonLabels.forEachIndexed { i, label ->+ val bWidth = labelWidths[i]+ val bRect = RectF(currentX, ty + m, currentX + bWidth, ty + m + btnHeight)++ // M3 Pill for EVERY button with Dynamic Primary+ 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 })++ canvas.drawText(label, bRect.centerX(), bRect.centerY() + 10f, toolbarActionPaint.apply {+ color = Color.WHITE+ style = Paint.Style.FILL+ textSize = 30f+ typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)+ })++ newButtons.add(ToolbarButton(label, Rect(bRect.left.toInt(), bRect.top.toInt(), bRect.right.toInt(), bRect.bottom.toInt())))+ currentX += bWidth + btnSpacing+ }+ toolbarButtons = newButtons}// ── Touch handling ────────────────────────────────────────────────────- private var startSelectionIdx = -1-override fun onTouchEvent(event: MotionEvent): Boolean {val lx = event.xval ly = event.ywhen (event.action) {MotionEvent.ACTION_DOWN -> {+ // Clicks for Top Bar are now handled by ComposeView,+ // so we only check the floating toolbar and selection logic.+// 1. Check toolbar FIRST with 24px extra hit-padding for reliabilityfor (btn in toolbarButtons) {val touchRect = Rect(btn.rect).apply { inset(-24, -24) }@@ -434,7 +558,6 @@ class CopyTextOverlayManager(if (nearest != -1) {globalSelectionStart = nearestglobalSelectionEnd = nearest- startSelectionIdx = nearestperformHapticFeedback(android.view.HapticFeedbackConstants.LONG_PRESS)invalidate()return true@@ -455,7 +578,7 @@ class CopyTextOverlayManager(invalidate()}return true- } else if (startSelectionIdx != -1) {+ } else if (globalSelectionStart != -1 && globalSelectionEnd != -1) { // Continue selection if already activeval nearest = findNearestWordGlobal(sx, sy)if (nearest != -1) {globalSelectionEnd = nearest@@ -499,7 +622,6 @@ class CopyTextOverlayManager(- // ── Toolbar action handler ────────────────────────────────────────────private fun handleToolbarAction(label: String) {val start = globalSelectionStart.coerceAtMost(globalSelectionEnd)@@ -526,7 +648,7 @@ class CopyTextOverlayManager(})dismiss()}- "Select All" -> {+ "All", "Select All" -> {globalSelectionStart = 0globalSelectionEnd = allWords.lastIndexinvalidate()@@ -537,13 +659,19 @@ class CopyTextOverlayManager(}}++ private fun statusBarsHeight(): Int {+ val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")+ return if (resourceId > 0) resources.getDimensionPixelSize(resourceId) else 0+ }+// ── Misc ──────────────────────────────────────────────────────────────override fun isInEditMode(): Boolean = falseoverride fun onKeyDown(keyCode: Int, event: android.view.KeyEvent): Boolean {if (keyCode == android.view.KeyEvent.KEYCODE_BACK) {- onBackPress()+ dismiss()return true}return super.onKeyDown(keyCode, event)diff --git a/build_errors_8.txt b/build_errors_14.txtsimilarity index 72%rename from build_errors_8.txtrename to build_errors_14.txtindex 602bb2c..1db20d0 100644Binary files a/build_errors_8.txt and b/build_errors_14.txt differdiff --git a/build_errors_15.txt b/build_errors_15.txtnew file mode 100644index 0000000..36fc722Binary files /dev/null and b/build_errors_15.txt differdiff --git a/build_errors_16.txt b/build_errors_16.txtnew file mode 100644index 0000000..2208e25Binary files /dev/null and b/build_errors_16.txt differdiff --git a/build_errors.txt b/build_errors_17.txtsimilarity index 56%rename from build_errors.txtrename to build_errors_17.txtindex 1926670..f79f82b 100644Binary files a/build_errors.txt and b/build_errors_17.txt differdiff --git a/build_errors_9.txt b/build_errors_18.txtsimilarity index 78%rename from build_errors_9.txtrename to build_errors_18.txtindex 0dea047..eddf739 100644Binary files a/build_errors_9.txt and b/build_errors_18.txt differdiff --git a/build_errors_2.txt b/build_errors_2.txtdeleted file mode 100644index 60f0cef..0000000Binary files a/build_errors_2.txt and /dev/null differdiff --git a/build_errors_3.txt b/build_errors_3.txtdeleted file mode 100644index 5a384b5..0000000Binary files a/build_errors_3.txt and /dev/null differdiff --git a/build_errors_4.txt b/build_errors_4.txtdeleted file mode 100644index 7b0217d..0000000Binary files a/build_errors_4.txt and /dev/null differdiff --git a/build_errors_5.txt b/build_errors_5.txtdeleted file mode 100644index e8b7e27..0000000Binary files a/build_errors_5.txt and /dev/null differdiff --git a/build_errors_6.txt b/build_errors_6.txtdeleted file mode 100644index 46997ad..0000000Binary files a/build_errors_6.txt and /dev/null differdiff --git a/build_errors_7.txt b/build_errors_7.txtdeleted file mode 100644index f671046..0000000Binary files a/build_errors_7.txt and /dev/null differdiff --git a/build_errors_utf8.txt b/build_errors_utf8.txtdeleted file mode 100644index 8d931ae..0000000--- a/build_errors_utf8.txt+++ /dev/null@@ -1,88 +0,0 @@-> Task :app:clean-> Task :app:preBuild UP-TO-DATE-> Task :app:preDebugBuild UP-TO-DATE-> Task :app:mergeDebugNativeDebugMetadata NO-SOURCE-> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED-> Task :app:processDebugNavigationResources-> Task :app:compileDebugNavigationResources-> Task :app:generateDebugResValues-> Task :app:checkDebugAarMetadata-> Task :app:mapDebugSourceSetPaths-> Task :app:generateDebugResources-> Task :app:packageDebugResources-> Task :app:createDebugCompatibleScreenManifests-> Task :app:extractDeepLinksDebug-> Task :app:parseDebugLocalResources-> Task :app:mergeDebugResources-> Task :app:processDebugMainManifest-> Task :app:processDebugManifest-> Task :app:javaPreCompileDebug-> Task :app:mergeDebugShaders-> Task :app:compileDebugShaders NO-SOURCE-> Task :app:generateDebugAssets UP-TO-DATE-> Task :app:mergeDebugAssets-> Task :app:desugarDebugFileDependencies-> Task :app:mergeDebugJniLibFolders-> Task :app:validateSigningDebug-> Task :app:writeDebugAppMetadata-> Task :app:checkDebugDuplicateClasses-> Task :app:writeDebugSigningConfigVersions-> Task :app:compressDebugAssets-> Task :app:mergeDebugNativeLibs-> Task :app:mergeLibDexDebug-> Task :app:processDebugManifestForPackage-> Task :app:stripDebugDebugSymbols-> Task :app:mergeExtDexDebug-> Task :app:processDebugResources-> Task :app:compileDebugKotlin--> Task :app:compileDebugKotlin FAILED-.\gradlew.bat : e: file:///C:/Users/ashin/Androi-dStudioProjects/CircleToSearch/app/src/main/java-/com/akslabs/circletosearch/ocr/TesseractEngine.-kt:105:39 Argument type mismatch: actual type-is 'android.graphics.Rect', but 'kotlin.Int'-was expected.-At line:1 char:1-+ .\gradlew.bat clean assembleDebug---console=plain > build_errors.txt ...-+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-~~~~~~~~~~~~~~~~~~~~~~~- + CategoryInfo : NotSpecified: (e:-fil e:///C:/U...' was expected.:String) [],-RemoteE xception- + FullyQualifiedErrorId : NativeCommandError--e: file:///C:/Users/ashin/AndroidStudioProjects/-CircleToSearch/app/src/main/java/com/akslabs/cir-cletosearch/ocr/TesseractEngine.kt:105:39 No-value passed for parameter 'startIndex'.-e: file:///C:/Users/ashin/AndroidStudioProjects/-CircleToSearch/app/src/main/java/com/akslabs/cir-cletosearch/ocr/TesseractEngine.kt:105:39 No-value passed for parameter 'endIndex'.-e: file:///C:/Users/ashin/AndroidStudioProjects/-CircleToSearch/app/src/main/java/com/akslabs/cir-cletosearch/ocr/TesseractEngine.kt:105:39 No-value passed for parameter 'bounds'.--FAILURE: Build failed with an exception.--* What went wrong:-Execution failed for task-':app:compileDebugKotlin'.-> A failure occurred while executing org.jetbrai-ns.kotlin.compilerRunner.GradleCompilerRunnerWit-hWorkers$GradleKotlinCompilerWorkAction- > Compilation error. See log for more details--* Try:-> Run with --stacktrace option to get the stack-trace.-> Run with --info or --debug option to get more-log output.-> Run with --scan to get full insights.-> Get more help at https://help.gradle.org.--BUILD FAILED in 2m 20s-31 actionable tasks: 31 executeddiff --git a/build_output.txt b/build_output.txtdeleted file mode 100644index 5ab9a6f..0000000Binary files a/build_output.txt and /dev/null differdiff --git a/build_output2.txt b/build_output2.txtdeleted file mode 100644index 96e4ad6..0000000Binary files a/build_output2.txt and /dev/null differdiff --git a/deps.txt b/deps.txtdeleted file mode 100644index 475519f..0000000Binary files a/deps.txt and /dev/null differ