Skip to content

CircleToSearch with multi search engine support for all android

Kotlin

added advance overlay settings

AKS Labse5d312cdff4b
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 8be3147..ec843f0 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -27,6 +27,8 @@
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28" />
+ <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
+ <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage" />
<application
android:allowBackup="true"
diff --git a/app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.kt b/app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.kt
index e01ed6c..8810ed1 100644
--- a/app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.kt
+++ b/app/src/main/java/com/akslabs/circletosearch/CircleToSearchAccessibilityService.kt
@@ -44,6 +44,7 @@ import com.akslabs.circletosearch.data.ActionType
import com.akslabs.circletosearch.data.BitmapRepository
import com.akslabs.circletosearch.data.GestureType
import com.akslabs.circletosearch.data.OverlayConfigurationManager
+import com.akslabs.circletosearch.data.OverlaySegment
import java.util.concurrent.Executor
import java.util.concurrent.Executors
@@ -167,137 +168,222 @@ class CircleToSearchAccessibilityService : AccessibilityService() {
}
private fun updateOverlay() {
- // Remove existing views
- overlayViews.forEach { view ->
- try {
- windowManager?.removeView(view)
- } catch (e: Exception) {
- e.printStackTrace()
- }
- }
- overlayViews.clear()
-
val config = configManager.getConfig()
- if (!config.isEnabled) return
+ if (!config.isEnabled) {
+ overlayViews.forEach {
+ try { windowManager?.removeView(it) } catch(e: Exception) {}
+ }
+ overlayViews.clear()
+ return
+ }
- // Check Landscape Mode
+ // Landscape check
val currentOrientation = resources.configuration.orientation
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE && !config.isEnabledInLandscape) {
+ overlayViews.forEach {
+ try { windowManager?.removeView(it) } catch(e: Exception) {}
+ }
+ overlayViews.clear()
return
}
- val screenWidth = resources.displayMetrics.widthPixels
+ // --- OPTIMIZATION: Diff Update to prevent flashing ---
+ // If the number of segments matches, we try to update existing views' LayoutParams
+ // If not, we rebuild.
- // Create views for each segment
- config.segments.forEach { segment ->
- val segmentWidth = (screenWidth * segment.widthFraction).toInt()
- val segmentX = (screenWidth * segment.startFraction).toInt()
-
- val view = View(this)
-
- // Visual debug or transparent
- if (config.isVisible) {
- view.setBackgroundColor(Color.argb(100, 255, 0, 0)) // Semi-transparent red for debug
- } else {
- view.setBackgroundColor(Color.TRANSPARENT)
+ if (overlayViews.size == config.segments.size) {
+ // Update mode
+ config.segments.forEachIndexed { index, segment ->
+ val view = overlayViews[index]
+ val params = view.layoutParams as WindowManager.LayoutParams
+
+ // Update params
+ var changed = false
+ if (params.width != segment.width) { params.width = segment.width; changed = true }
+ if (params.height != segment.height) { params.height = segment.height; changed = true }
+ if (params.x != segment.xOffset) { params.x = segment.xOffset; changed = true }
+ if (params.y != segment.yOffset) { params.y = segment.yOffset; changed = true }
+
+ if (changed) {
+ try {
+ windowManager?.updateViewLayout(view, params)
+ } catch (e: Exception) {
+ // Fallback implies view might be detached, shouldn't happen commonly
+ }
+ }
+
+ // Update Color (Debug)
+ if (config.isVisible) {
+ val colors = listOf(Color.parseColor("#80FF0000"), Color.parseColor("#8000FF00"), Color.parseColor("#800000FF"), Color.parseColor("#80FFFF00"), Color.parseColor("#80FF00FF")) // Red, Green, Blue, Yellow, Magenta
+ view.setBackgroundColor(colors[index % colors.size])
+ } else {
+ view.setBackgroundColor(Color.TRANSPARENT)
+ }
+
+ // Update gesture listener
+ // Since we created the detector in the loop, we can't easily "update" its inner logic if it closes over the *old* segment.
+ // WE MUST re-attach the listener or make the listener dynamic.
+ // The cleanest way is to just attach a NEW listener wrapper that reads the LATEST segment config.
+ // But `segment` here is from the new config.
+ // Creating a new detector is cheap.
+ attachTouchListener(view, segment)
}
+ } else {
+ // Rebuild mode (Count changed)
+ overlayViews.forEach {
+ try { windowManager?.removeView(it) } catch(e: Exception) {}
+ }
+ overlayViews.clear()
- val params = WindowManager.LayoutParams(
- segmentWidth,
- config.height,
- WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY,
- WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
- WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
- WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
- WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
- PixelFormat.TRANSLUCENT
- )
-
- params.gravity = Gravity.TOP or Gravity.START
- params.x = segmentX
- params.y = config.verticalOffset
-
- // GestureDetector for this segment
- val gestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
- override fun onDoubleTap(e: MotionEvent): Boolean {
- val action = segment.gestures[GestureType.DOUBLE_TAP] ?: ActionType.NONE
- performAction(action)
- return true
- }
+ config.segments.forEachIndexed { index, segment ->
+ val view = View(this)
+ val params = WindowManager.LayoutParams(
+ segment.width,
+ segment.height,
+ WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY,
+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
+ WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
+ WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
+ WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
+ PixelFormat.TRANSLUCENT
+ )
+
+ params.gravity = Gravity.TOP or Gravity.START
+ params.x = segment.xOffset
+ params.y = segment.yOffset
- override fun onLongPress(e: MotionEvent) {
- val action = segment.gestures[GestureType.LONG_PRESS] ?: ActionType.NONE
- performAction(action)
+ if (config.isVisible) {
+ val colors = listOf(Color.parseColor("#80FF0000"), Color.parseColor("#8000FF00"), Color.parseColor("#800000FF"), Color.parseColor("#80FFFF00"), Color.parseColor("#80FF00FF"))
+ view.setBackgroundColor(colors[index % colors.size])
+ } else {
+ view.setBackgroundColor(Color.TRANSPARENT)
}
- override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
- // Possible triple tap logic here if needed, but Triple Tap usually handled by onDoubleTapEvent or custom logic.
- // For simplicity, we stick to Double and Long for now, or Tripple via custom counter if GestureDetector doesn't support it directly easily.
- // Standard GestureDetector doesn't have explicit onTripleTap.
- // We can check previous tap times if we want triple tap.
- // For now, let's just stick to what GestureDetector offers cleanly.
- return false
+ attachTouchListener(view, segment)
+
+ try {
+ windowManager?.addView(view, params)
+ overlayViews.add(view)
+ } catch (e: Exception) {
+ e.printStackTrace()
}
- }).apply {
- // Triple tap workaround could be added here
- setOnDoubleTapListener(object : GestureDetector.OnDoubleTapListener {
- override fun onSingleTapConfirmed(e: MotionEvent): Boolean = false
-
- override fun onDoubleTap(e: MotionEvent): Boolean {
- // Check for Triple Tap (very crude implementation concept, but standard is double)
- // Implementing strict double tap mapped action
- val action = segment.gestures[GestureType.DOUBLE_TAP] ?: ActionType.NONE
- if (action != ActionType.NONE) {
- performAction(action)
- return true
- }
- return false
- }
-
- override fun onDoubleTapEvent(e: MotionEvent): Boolean = false
- })
+ }
+ }
+ }
+
+ @SuppressLint("ClickableViewAccessibility")
+ private fun attachTouchListener(view: View, segment: OverlaySegment) {
+ val gestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
+ override fun onDoubleTap(e: MotionEvent): Boolean {
+ val action = segment.gestures[GestureType.DOUBLE_TAP] ?: ActionType.NONE
+ if (action != ActionType.NONE) { performAction(action, segment); return true }
+ return false
}
- // Triple tap helper
- var lastTapTime: Long = 0
- var tapCount = 0
+ override fun onLongPress(e: MotionEvent) {
+ val action = segment.gestures[GestureType.LONG_PRESS] ?: ActionType.NONE
+ if (action != ActionType.NONE) performAction(action, segment)
+ }
+
+ override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
+ // User wants "buttons behind to be clickable"
+ // We temporarily disable touch on our window and dispatch the click through.
+ propagateSingleTap(view, e.rawX, e.rawY)
+ return false
+ }
- @SuppressLint("ClickableViewAccessibility")
- view.setOnTouchListener { _, event ->
- if (event.action == MotionEvent.ACTION_DOWN) {
- val currentTime = System.currentTimeMillis()
- if (currentTime - lastTapTime < 400) {
- tapCount++
- } else {
- tapCount = 1
+ override fun onFling(e1: MotionEvent?, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
+ if (e1 == null) return false
+ val diffY = e2.y - e1.y
+ val diffX = e2.x - e1.x
+
+ if (Math.abs(diffX) > Math.abs(diffY)) {
+ if (Math.abs(diffX) > 100 && Math.abs(velocityX) > 100) {
+ if (diffX > 0) {
+ // Swipe Right
+ val action = segment.gestures[GestureType.SWIPE_RIGHT] ?: ActionType.NONE
+ if (action != ActionType.NONE) { performAction(action, segment); return true }
+ } else {
+ // Swipe Left
+ val action = segment.gestures[GestureType.SWIPE_LEFT] ?: ActionType.NONE
+ if (action != ActionType.NONE) { performAction(action, segment); return true }
+ }
}
- lastTapTime = currentTime
-
- if (tapCount == 3) {
- val action = segment.gestures[GestureType.TRIPLE_TAP] ?: ActionType.NONE
- if (action != ActionType.NONE) {
- performAction(action)
- tapCount = 0 // Reset
- return@setOnTouchListener true
- }
+ } else {
+ if (Math.abs(diffY) > 100 && Math.abs(velocityY) > 100) {
+ if (diffY > 0) {
+ // Swipe Down
+ val action = segment.gestures[GestureType.SWIPE_DOWN] ?: ActionType.NONE
+ if (action != ActionType.NONE) {
+ performAction(action, segment)
+ } else {
+ // Smart Scroll Down Logic (Default)
+ // If overlay is on LEFT side (< screenWidth/2), open Notifications.
+ // If overlay is on RIGHT side (> screenWidth/2), open Quick Settings.
+
+ // We need to calculate the CENTER of this segment.
+ // segment.xOffset is the left edge.
+ // segment.width is width.
+ val segmentCenterX = segment.xOffset + (segment.width / 2)
+ val screenWidth = resources.displayMetrics.widthPixels
+
+ if (segmentCenterX < (screenWidth / 2)) {
+ performGlobalAction(GLOBAL_ACTION_NOTIFICATIONS)
+ } else {
+ performGlobalAction(GLOBAL_ACTION_QUICK_SETTINGS)
+ }
+ }
+ return true
+ } else {
+ // Swipe Up
+ val action = segment.gestures[GestureType.SWIPE_UP] ?: ActionType.NONE
+ if (action != ActionType.NONE) { performAction(action, segment); return true }
+ }
}
}
-
- gestureDetector.onTouchEvent(event)
- true
+ return false
}
-
- try {
- windowManager?.addView(view, params)
- overlayViews.add(view)
- } catch (e: Exception) {
- e.printStackTrace()
+ }).apply {
+ setOnDoubleTapListener(object : GestureDetector.OnDoubleTapListener {
+ override fun onSingleTapConfirmed(e: MotionEvent): Boolean = false
+ override fun onDoubleTap(e: MotionEvent): Boolean {
+ val action = segment.gestures[GestureType.DOUBLE_TAP] ?: ActionType.NONE
+ if (action != ActionType.NONE) { performAction(action, segment); return true }
+ return false
+ }
+ override fun onDoubleTapEvent(e: MotionEvent): Boolean = false
+ })
+ }
+
+ var lastTapTime: Long = 0
+ var tapCount = 0
+
+ view.setOnTouchListener { _, event ->
+ if (event.action == MotionEvent.ACTION_DOWN) {
+ val currentTime = System.currentTimeMillis()
+ if (currentTime - lastTapTime < 400) {
+ tapCount++
+ } else {
+ tapCount = 1
+ }
+ lastTapTime = currentTime
+
+ if (tapCount == 3) {
+ val action = segment.gestures[GestureType.TRIPLE_TAP] ?: ActionType.NONE
+ if (action != ActionType.NONE) {
+ performAction(action, segment)
+ tapCount = 0
+ return@setOnTouchListener true
+ }
+ }
}
+ gestureDetector.onTouchEvent(event)
+ true
}
}
- private fun performAction(action: ActionType) {
+ private fun performAction(action: ActionType, segment: OverlaySegment) {
if (action == ActionType.NONE) return
// Haptic feedback for action trigger
@@ -310,7 +396,7 @@ class CircleToSearchAccessibilityService : AccessibilityService() {
}
when(action) {
- ActionType.SCREENSHOT -> performCapture()
+ ActionType.SCREENSHOT -> performGlobalAction(GLOBAL_ACTION_TAKE_SCREENSHOT)
ActionType.FLASHLIGHT -> toggleFlashlight()
ActionType.HOME -> performGlobalAction(GLOBAL_ACTION_HOME)
ActionType.BACK -> performGlobalAction(GLOBAL_ACTION_BACK)
@@ -321,12 +407,86 @@ class CircleToSearchAccessibilityService : AccessibilityService() {
ActionType.OPEN_NOTIFICATIONS -> performGlobalAction(GLOBAL_ACTION_NOTIFICATIONS)
ActionType.OPEN_QUICK_SETTINGS -> performGlobalAction(GLOBAL_ACTION_QUICK_SETTINGS)
ActionType.OPEN_APP -> {
- // TODO: Implement open app logic if package name provided
+ // Open App Logic
+ val packageName = segment.gestureData[findGestureForAction(segment, ActionType.OPEN_APP)]
+ if (!packageName.isNullOrEmpty()) {
+ val launchIntent = packageManager.getLaunchIntentForPackage(packageName)
+ if (launchIntent != null) {
+ launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ startActivity(launchIntent)
+ }
+ }
+ }
+ ActionType.CTS_LENS -> {
+ // Force Lens Mode
+ val uiPrefs = com.akslabs.circletosearch.utils.UIPreferences(this)
+ uiPrefs.setUseGoogleLensOnly(true)
+ performCapture()
+ }
+ ActionType.CTS_MULTI -> {
+ // Force Multi Mode
+ val uiPrefs = com.akslabs.circletosearch.utils.UIPreferences(this)
+ uiPrefs.setUseGoogleLensOnly(false)
+ performCapture()
+ }
+ ActionType.SPLIT_SCREEN -> {
+ val success = performGlobalAction(GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN)
+ if (!success) {
+ android.widget.Toast.makeText(this, "Split Screen not supported or failed", android.widget.Toast.LENGTH_SHORT).show()
+ }
}
else -> {}
}
}
+ private fun findGestureForAction(segment: OverlaySegment, action: ActionType): GestureType {
+ return segment.gestures.entries.firstOrNull { it.value == action }?.key ?: GestureType.DOUBLE_TAP
+ }
+
+ // Pass-through Logic for Single Tap
+ // We must temporarily make the window UNTOUCHABLE so the injected gesture falls through to the app below.
+ // Otherwise, the injected tap hits our own overlay (loop/blocked).
+ private fun propagateSingleTap(view: View, x: Float, y: Float) {
+ val params = view.layoutParams as WindowManager.LayoutParams
+ val originalFlags = params.flags
+
+ // Make untouchable
+ params.flags = params.flags or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
+ windowManager?.updateViewLayout(view, params)
+
+ val path = android.graphics.Path().apply { moveTo(x, y) }
+ val stroke = android.accessibilityservice.GestureDescription.StrokeDescription(path, 0, 50) // 50ms tap duration (more standard)
+ val gesture = android.accessibilityservice.GestureDescription.Builder().addStroke(stroke).build()
+
+ // Wait for WindowManager to update input focus before dispatching
+ val handler = android.os.Handler(android.os.Looper.getMainLooper())
+ handler.postDelayed({
+ dispatchGesture(gesture, object : android.accessibilityservice.AccessibilityService.GestureResultCallback() {
+ override fun onCompleted(gestureDescription: android.accessibilityservice.GestureDescription?) {
+ super.onCompleted(gestureDescription)
+ restoreFlags()
+ }
+
+ override fun onCancelled(gestureDescription: android.accessibilityservice.GestureDescription?) {
+ super.onCancelled(gestureDescription)
+ restoreFlags()
+ }
+
+ fun restoreFlags() {
+ // Restore original flags (Touchable) using main thread to be safe with UI
+ handler.post {
+ params.flags = originalFlags
+ try {
+ windowManager?.updateViewLayout(view, params)
+ } catch (e: Exception) {
+ // View might be removed
+ }
+ }
+ }
+ }, null)
+ }, 100) // 100ms Delay to ensure 'untouchable' takes effect solidly
+ }
+
private fun toggleFlashlight() {
try {
val cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
diff --git a/app/src/main/java/com/akslabs/circletosearch/MainActivity.kt b/app/src/main/java/com/akslabs/circletosearch/MainActivity.kt
index 2dbc618..a8dc97b 100644
--- a/app/src/main/java/com/akslabs/circletosearch/MainActivity.kt
+++ b/app/src/main/java/com/akslabs/circletosearch/MainActivity.kt
@@ -62,11 +62,12 @@ class MainActivity : ComponentActivity() {
color = MaterialTheme.colorScheme.background
) {
var currentScreen by remember { mutableStateOf("home") }
-
- if (currentScreen == "settings") {
- com.akslabs.circletosearch.ui.OverlaySettingsScreen(onBack = { currentScreen = "home" })
- } else {
- SetupScreen(onSettingsClick = { currentScreen = "settings" })
+ androidx.compose.animation.Crossfade(targetState = currentScreen) { screen ->
+ if (screen == "settings") {
+ com.akslabs.circletosearch.ui.OverlaySettingsScreen(onBack = { currentScreen = "home" })
+ } else {
+ SetupScreen(onSettingsClick = { currentScreen = "settings" })
+ }
}
}
}
@@ -132,17 +133,28 @@ fun SetupScreen(onSettingsClick: () -> Unit) {
Spacer(modifier = Modifier.height(32.dp))
// 1. Header
- Text(
- text = "Circle to Search",
- style = MaterialTheme.typography.displaySmall.copy(fontWeight = FontWeight.Bold),
- color = MaterialTheme.colorScheme.primary
- )
+ Box(
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text(
+ text = "Circle to Search",
+ style = MaterialTheme.typography.displaySmall.copy(fontWeight = FontWeight.Bold),
+ color = MaterialTheme.colorScheme.primary,
+ modifier = Modifier.align(Alignment.Center)
+ )
+ IconButton(
+ onClick = onSettingsClick,
+ modifier = Modifier.align(Alignment.CenterEnd)
+ ) {
+ Icon(Icons.Default.Settings, contentDescription = "Overlay Settings", tint = MaterialTheme.colorScheme.primary)
+ }
+ }
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "Search anything on your screen instantly.",
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
- textAlign = TextAlign.Center
+ textAlign = TextAlign.Start
)
Spacer(modifier = Modifier.height(32.dp))
@@ -318,44 +330,6 @@ fun SetupScreen(onSettingsClick: () -> Unit) {
)
BubbleSwitch(context)
LensOnlySwitch(context)
-
- Spacer(modifier = Modifier.height(12.dp))
-
- // Advanced Overlay Settings Button
- Card(
- onClick = onSettingsClick,
- colors = CardDefaults.cardColors(
- containerColor = MaterialTheme.colorScheme.tertiaryContainer
- ),
- shape = androidx.compose.foundation.shape.RoundedCornerShape(24.dp),
- modifier = Modifier.fillMaxWidth()
- ) {
- Row(
- modifier = Modifier.padding(16.dp),
- verticalAlignment = Alignment.CenterVertically
- ) {
- Icon(
- imageVector = Icons.Default.Settings,
- contentDescription = null,
- modifier = Modifier.size(24.dp),
- tint = MaterialTheme.colorScheme.onTertiaryContainer
- )
- Spacer(modifier = Modifier.width(16.dp))
- Column {
- Text(
- text = "Advanced Status Bar Settings",
- style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
- color = MaterialTheme.colorScheme.onTertiaryContainer
- )
- Text(
- text = "Customize overlay size, gestures & segments",
- style = MaterialTheme.typography.bodySmall,
- color = MaterialTheme.colorScheme.onTertiaryContainer.copy(alpha = 0.8f)
- )
- }
- }
- }
-
Spacer(modifier = Modifier.height(25.dp))
// Privacy Note
diff --git a/app/src/main/java/com/akslabs/circletosearch/data/OverlayConfig.kt b/app/src/main/java/com/akslabs/circletosearch/data/OverlayConfig.kt
index 245b895..27c4fac 100644
--- a/app/src/main/java/com/akslabs/circletosearch/data/OverlayConfig.kt
+++ b/app/src/main/java/com/akslabs/circletosearch/data/OverlayConfig.kt
@@ -7,27 +7,32 @@ package com.akslabs.circletosearch.data
import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
-import com.google.gson.reflect.TypeToken
+import com.akslabs.circletosearch.data.OverlaySegment
data class OverlayConfig(
val isEnabled: Boolean = true,
val isEnabledInLandscape: Boolean = false,
- val height: Int = 100, // Pixels
- val verticalOffset: Int = 0, // Pixels from top
val isVisible: Boolean = false, // Debug visibility (colored)
- val segments: List<OverlaySegment> = listOf(OverlaySegment(0f, 1f)) // Default single full-width segment
+ val segments: List<OverlaySegment> = listOf(OverlaySegment(width = 1080)) // Default to a common large width
)
data class OverlaySegment(
- val startFraction: Float, // 0.0 to 1.0
- val widthFraction: Float, // 0.0 to 1.0
- val gestures: MutableMap<GestureType, ActionType> = mutableMapOf(GestureType.DOUBLE_TAP to ActionType.SCREENSHOT)
+ val width: Int = 150, // Pixels
+ val height: Int = 60, // Pixels
+ val xOffset: Int = 0, // Pixels from left
+ val yOffset: Int = 0, // Pixels from top
+ val gestures: MutableMap<GestureType, ActionType> = mutableMapOf(GestureType.DOUBLE_TAP to ActionType.SCREENSHOT),
+ val gestureData: MutableMap<GestureType, String> = mutableMapOf() // Stores extra data like package name for OPEN_APP
)
enum class GestureType {
DOUBLE_TAP,
LONG_PRESS,
- TRIPLE_TAP
+ TRIPLE_TAP,
+ SWIPE_UP,
+ SWIPE_DOWN,
+ SWIPE_LEFT,
+ SWIPE_RIGHT
}
enum class ActionType {
@@ -38,9 +43,12 @@ enum class ActionType {
BACK,
RECENTS,
LOCK_SCREEN,
- OPEN_APP, // Requires extra data, maybe simple string for package name later
+ OPEN_APP,
OPEN_NOTIFICATIONS,
- OPEN_QUICK_SETTINGS
+ OPEN_QUICK_SETTINGS,
+ CTS_LENS,
+ CTS_MULTI,
+ SPLIT_SCREEN
}
class OverlayConfigurationManager(context: Context) {
@@ -53,14 +61,21 @@ class OverlayConfigurationManager(context: Context) {
fun getConfig(): OverlayConfig {
val json = prefs.getString(KEY_CONFIG, null)
- return if (json != null) {
+ if (json != null) {
try {
- gson.fromJson(json, OverlayConfig::class.java)
+ val config = gson.fromJson(json, OverlayConfig::class.java)
+ // Sanitize: Gson might result in null keys in maps if enum values are missing
+ val sanitizedSegments = config.segments.map { segment ->
+ val cleanGestures = segment.gestures.filterKeys { it != null }.toMutableMap()
+ segment.copy(gestures = cleanGestures)
+ }
+ return config.copy(segments = sanitizedSegments)
} catch (e: Exception) {
- OverlayConfig()
+ // If deep failure, return default
+ return OverlayConfig()
}
} else {
- OverlayConfig()
+ return OverlayConfig()
}
}
diff --git a/app/src/main/java/com/akslabs/circletosearch/ui/OverlaySettingsScreen.kt b/app/src/main/java/com/akslabs/circletosearch/ui/OverlaySettingsScreen.kt
index da28e9a..9642046 100644
--- a/app/src/main/java/com/akslabs/circletosearch/ui/OverlaySettingsScreen.kt
+++ b/app/src/main/java/com/akslabs/circletosearch/ui/OverlaySettingsScreen.kt
@@ -5,13 +5,11 @@
package com.akslabs.circletosearch.ui
import android.content.Context
-import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
-import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
-import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
@@ -20,16 +18,13 @@ import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
-import androidx.compose.ui.draw.clip
-import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
-import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
-import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
+import androidx.compose.ui.window.DialogProperties
import com.akslabs.circletosearch.data.*
@OptIn(ExperimentalMaterial3Api::class)
@@ -37,11 +32,14 @@ import com.akslabs.circletosearch.data.*
fun OverlaySettingsScreen(
onBack: () -> Unit
) {
+ // Handle system back press
+ androidx.activity.compose.BackHandler(onBack = onBack)
+
val context = LocalContext.current
val configManager = remember { OverlayConfigurationManager(context) }
var config by remember { mutableStateOf(configManager.getConfig()) }
- // Save on changes
+ // Save on changes - Updates in REALTIME
fun updateConfig(newConfig: OverlayConfig) {
config = newConfig
configManager.saveConfig(newConfig)
@@ -73,13 +71,7 @@ fun OverlaySettingsScreen(
.verticalScroll(rememberScrollState())
.padding(16.dp)
) {
- // 1. Visualizer
- Text("PREVIEW", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.primary)
- Spacer(modifier = Modifier.height(8.dp))
- OverlayVisualizer(config = config)
- Spacer(modifier = Modifier.height(24.dp))
-
- // 2. Main Toggles
+ // 1. Main Toggles
SettingsSectionHeader(title = "General")
SettingsToggleItem(
title = "Enable Overlay",
@@ -99,7 +91,7 @@ fun OverlaySettingsScreen(
Spacer(modifier = Modifier.height(12.dp))
SettingsToggleItem(
title = "Debug Visibility",
- subtitle = "Show colored overlay for testing",
+ subtitle = "Show color to adjust position",
icon = Icons.Default.Visibility,
checked = config.isVisible,
onCheckedChange = { updateConfig(config.copy(isVisible = it)) }
@@ -107,59 +99,31 @@ fun OverlaySettingsScreen(
Spacer(modifier = Modifier.height(24.dp))
- // 3. Dimensions
- SettingsSectionHeader(title = "Dimensions")
- Text("Height: ${config.height}px", style = MaterialTheme.typography.bodySmall)
- Slider(
- value = config.height.toFloat(),
- onValueChange = { updateConfig(config.copy(height = it.toInt())) },
- valueRange = 20f..300f
- )
-
- Text("Vertical Offset: ${config.verticalOffset}px", style = MaterialTheme.typography.bodySmall)
- Slider(
- value = config.verticalOffset.toFloat(),
- onValueChange = { updateConfig(config.copy(verticalOffset = it.toInt())) },
- valueRange = 0f..200f
- )
-
- Spacer(modifier = Modifier.height(24.dp))
-
- // 4. Segments
+ // 2. Overlays List
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
- SettingsSectionHeader(title = "Segments & Gestures")
+ SettingsSectionHeader(title = "Overlays")
TextButton(onClick = {
- // Add split logic: Split the last segment in half or add new one
+ // Add new overlay segment
val currentSegments = config.segments.toMutableList()
- if (currentSegments.isNotEmpty()) {
- // Redistribution logic: reset to equal parts for simplicity when adding
- val newCount = currentSegments.size + 1
- val newWidth = 1f / newCount
- val newSegments = mutableListOf<OverlaySegment>()
- for (i in 0 until newCount) {
- newSegments.add(OverlaySegment(startFraction = i * newWidth, widthFraction = newWidth))
- }
- updateConfig(config.copy(segments = newSegments))
- } else {
- updateConfig(config.copy(segments = listOf(OverlaySegment(0f, 1f))))
- }
+ currentSegments.add(OverlaySegment(xOffset = 300)) // Add with some offset so it doesn't overlap perfectly if 0
+ updateConfig(config.copy(segments = currentSegments))
}) {
- Text("+ Add Split")
+ Icon(Icons.Default.Add, contentDescription = null, modifier = Modifier.size(18.dp))
+ Spacer(modifier = Modifier.width(4.dp))
+ Text("Add Overlay")
}
}
- // Re-distribute/Clear
- if (config.segments.size > 1) {
- TextButton(
- onClick = { updateConfig(config.copy(segments = listOf(OverlaySegment(0f, 1f)))) },
- modifier = Modifier.align(Alignment.End)
- ) {
- Text("Reset to Single", color = MaterialTheme.colorScheme.error)
- }
+ if (config.segments.isEmpty()) {
+ Text(
+ "No overlays added. Click Add Overlay to start.",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
}
config.segments.forEachIndexed { index, segment ->
@@ -170,79 +134,15 @@ fun OverlaySettingsScreen(
val newSegments = config.segments.toMutableList()
newSegments[index] = updatedSegment
updateConfig(config.copy(segments = newSegments))
+ },
+ onDelete = {
+ val newSegments = config.segments.toMutableList()
+ newSegments.removeAt(index)
+ updateConfig(config.copy(segments = newSegments))
}
)
- Spacer(modifier = Modifier.height(8.dp))
- }
- }
- }
-}
-
-@Composable
-fun OverlayVisualizer(config: OverlayConfig) {
- Box(
- modifier = Modifier
- .fillMaxWidth()
- .height(60.dp) // Scaled down verification
- .clip(RoundedCornerShape(8.dp))
- .background(Color.Black)
- .border(1.dp, Color.DarkGray, RoundedCornerShape(8.dp))
- ) {
- // Draw Status Bar hints
- Row(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = 12.dp),
- horizontalArrangement = Arrangement.SpaceBetween,
- verticalAlignment = Alignment.CenterVertically
- ) {
- Text("9:41", color = Color.White, fontSize = 10.sp)
- Row {
- Icon(Icons.Default.Wifi, contentDescription = null, tint = Color.White, modifier = Modifier.size(10.dp))
- Spacer(modifier = Modifier.width(4.dp))
- Icon(Icons.Default.BatteryFull, contentDescription = null, tint = Color.White, modifier = Modifier.size(10.dp))
- }
- }
-
- // Draw Overlay Segments
- Box(modifier = Modifier.fillMaxSize()) {
- config.segments.forEachIndexed { index, segment ->
- Box(
- modifier = Modifier
- .fillMaxHeight()
- .fillMaxWidth(fraction = segment.widthFraction)
- // Align based on start fraction.
- // Note: fillMaxWidth(fraction) takes fraction of PARENT.
- // To allow arbitrary positioning we might need offsets or a Row with weights.
- // Or easier: Custom Layout or simple Offset.
- // Since segments are usually sequential, Row is best visually. But we support config.
- // Let's use alignment bias or Offset.
- )
+ Spacer(modifier = Modifier.height(16.dp))
}
-
- // Better Visualizer: Canvas
- Canvas(modifier = Modifier.fillMaxSize()) {
- val totalWidth = size.width
- val height = if (config.height > size.height) size.height else config.height.toFloat() // Clamp for visual
- val yOffset = 0f // In visualizer, always top
-
- config.segments.forEachIndexed { index, segment ->
- val x = totalWidth * segment.startFraction
- val w = totalWidth * segment.widthFraction
-
- // Colors
- val colors = listOf(Color.Red, Color.Blue, Color.Green, Color.Yellow, Color.Magenta)
- val color = colors[index % colors.size].copy(alpha = 0.5f)
-
- drawRect(
- color = color,
- topLeft = Offset(x, yOffset),
- size = androidx.compose.ui.geometry.Size(w, 20f) // Fixed visual height
- )
-
- // Draw Borders
- }
- }
}
}
}
@@ -252,37 +152,121 @@ fun OverlayVisualizer(config: OverlayConfig) {
fun SegmentEditorItem(
index: Int,
segment: OverlaySegment,
- onUpdate: (OverlaySegment) -> Unit
+ onUpdate: (OverlaySegment) -> Unit,
+ onDelete: () -> Unit
) {
+ var isExpanded by remember { mutableStateOf(false) }
var showGestureDialog by remember { mutableStateOf(false) }
+
+ // Get screen dimensions for sliders
+ val configuration = androidx.compose.ui.platform.LocalConfiguration.current
+ val screenWidth = configuration.screenWidthDp.toFloat() * 3 // Rough dp to px.
+ val screenHeight = configuration.screenHeightDp.toFloat() * 3
+ // Use actual resource metrics if possible, but LocalConfiguration is easiest in Compose.
+ // To be safer and strictly follow "screen boundaries", we can clamp.
+ // But since pixels vary by density, let's allow a generous but bounded range based on config.
+ // 3.0 density is common (XXHDPI).
+ // We will just use a reasonably high cap matching probable max resolution (e.g. 1440p width -> ~1500, height -> ~3000)
+ // Actually, user said "limit sliders to screen boundaries".
+ // I should probably pass exact screen metrics from MainActivity or Context.
+ val metrics = LocalContext.current.resources.displayMetrics
+ val maxWidth = metrics.widthPixels.toFloat()
+ val maxHeight = metrics.heightPixels.toFloat()
Card(
- modifier = Modifier.fillMaxWidth().clickable { showGestureDialog = true },
- colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha=0.5f))
+ modifier = Modifier.fillMaxWidth(),
+ colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha=0.3f)),
+ shape = RoundedCornerShape(16.dp)
) {
Column(modifier = Modifier.padding(12.dp)) {
- Row(verticalAlignment = Alignment.CenterVertically) {
+ // Header
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.clickable { isExpanded = !isExpanded }
+ ) {
Box(
modifier = Modifier.size(16.dp).background(
listOf(Color.Red, Color.Blue, Color.Green, Color.Yellow, Color.Magenta)[index % 5],
- shape = androidx.compose.foundation.shape.CircleShape
+ shape = CircleShape
)
)
Spacer(modifier = Modifier.width(8.dp))
- Text("Segment ${index + 1}", fontWeight = FontWeight.Bold)
+ Text("Overlay ${index + 1}", fontWeight = FontWeight.Bold)
Spacer(modifier = Modifier.weight(1f))
- Icon(Icons.Default.Edit, contentDescription = "Edit", modifier = Modifier.size(16.dp))
+
+ IconButton(onClick = onDelete) {
+ Icon(Icons.Default.Delete, contentDescription = "Delete", tint = MaterialTheme.colorScheme.error, modifier = Modifier.size(20.dp))
+ }
+ Icon(
+ if (isExpanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore,
+ contentDescription = null
+ )
}
- Spacer(modifier = Modifier.height(8.dp))
-
- // Readout of gestures
- segment.gestures.forEach { (type, action) ->
- Text(
- "${type.name}: ${action.name}",
- style = MaterialTheme.typography.bodySmall,
- color = MaterialTheme.colorScheme.onSurfaceVariant
+ if (isExpanded) {
+ Spacer(modifier = Modifier.height(16.dp))
+
+ // Dimensions Sliders - Limited to Screen
+ Text("Horizontal Position (X): ${segment.xOffset}px", style = MaterialTheme.typography.labelMedium)
+ Slider(
+ value = segment.xOffset.toFloat().coerceIn(0f, maxWidth),
+ onValueChange = { onUpdate(segment.copy(xOffset = it.toInt())) },
+ valueRange = 0f..maxWidth
+ )
+
+ Text("Vertical Position (Y): ${segment.yOffset}px", style = MaterialTheme.typography.labelMedium)
+ Slider(
+ value = segment.yOffset.toFloat().coerceIn(0f, maxHeight),
+ onValueChange = { onUpdate(segment.copy(yOffset = it.toInt())) },
+ valueRange = 0f..maxHeight
)
+
+ Text("Width: ${segment.width}px", style = MaterialTheme.typography.labelMedium)
+ Slider(
+ value = segment.width.toFloat().coerceIn(0f, maxWidth),
+ onValueChange = { onUpdate(segment.copy(width = it.toInt())) },
+ valueRange = 10f..maxWidth
+ )
+
+ Text("Height: ${segment.height}px", style = MaterialTheme.typography.labelMedium)
+ Slider(
+ value = segment.height.toFloat().coerceIn(0f, 400f),
+ onValueChange = { onUpdate(segment.copy(height = it.toInt())) },
+ valueRange = 10f..400f // Limited to 400px as per verification request
+ )
+
+
+ Spacer(modifier = Modifier.height(16.dp))
+ Divider(color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha=0.1f))
+ Spacer(modifier = Modifier.height(12.dp))
+
+ // Gestures
+ Row(
+ modifier = Modifier.fillMaxWidth().clickable { showGestureDialog = true },
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Icon(Icons.Default.TouchApp, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
+ Spacer(modifier = Modifier.width(12.dp))
+ Column {
+ Text("Gestures", fontWeight = FontWeight.Bold)
+ Text("Configure taps, long press & swipes", style = MaterialTheme.typography.bodySmall)
+ }
+ Spacer(modifier = Modifier.weight(1f))
+ Icon(Icons.Default.ArrowForwardIos, contentDescription = null, modifier = Modifier.size(16.dp))
+ }
+
+ Spacer(modifier = Modifier.height(8.dp))
+
+ // Gesture Summary (first 2 non-none)
+ Column {
+ segment.gestures.entries.filter { it.value != ActionType.NONE }.take(2).forEach {
+ Text(
+ "${it.key.name}: ${it.value.name}",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.secondary
+ )
+ }
+ }
}
}
}
@@ -302,13 +286,37 @@ fun GestureConfigDialog(
onDismiss: () -> Unit,
onUpdate: (OverlaySegment) -> Unit
) {
- // We only support configuring specific gestures.
- // Let's just list them.
+ var showAppPicker by remember { mutableStateOf<GestureType?>(null) }
+ val context = LocalContext.current
- Dialog(onDismissRequest = onDismiss) {
+ if (showAppPicker != null) {
+ AppPickerDialog(
+ onDismiss = { showAppPicker = null },
+ onAppSelected = { pkg ->
+ val gesture = showAppPicker!!
+ val newGestures = segment.gestures.toMutableMap()
+ newGestures[gesture] = ActionType.OPEN_APP
+
+ val newData = segment.gestureData.toMutableMap()
+ newData[gesture] = pkg
+
+ onUpdate(segment.copy(gestures = newGestures, gestureData = newData))
+ showAppPicker = null
+ }
+ )
+ }
+
+ Dialog(
+ onDismissRequest = onDismiss,
+ properties = DialogProperties(usePlatformDefaultWidth = false) // Allow full width control
+ ) {
Card(
shape = RoundedCornerShape(24.dp),
- colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
+ colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(24.dp) // Screen padding
+ .fillMaxHeight(0.85f)
) {
Column(
modifier = Modifier.padding(24.dp).verticalScroll(rememberScrollState())
@@ -327,23 +335,38 @@ fun GestureConfigDialog(
onClick = { expanded = true },
modifier = Modifier.fillMaxWidth()
) {
- Text(currentAction.name)
+ var label = currentAction.name
+ if (currentAction == ActionType.OPEN_APP) {
+ val pkg = segment.gestureData[gesture]
+ val appName = runCatching {
+ val info = context.packageManager.getApplicationInfo(pkg ?: "", 0)
+ context.packageManager.getApplicationLabel(info).toString()
+ }.getOrDefault(pkg ?: "Unknown App")
+ label = "Open: $appName"
+ }
+ Text(label, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)
Spacer(modifier = Modifier.weight(1f))
Icon(Icons.Default.ArrowDropDown, contentDescription = null)
}
DropdownMenu(
expanded = expanded,
- onDismissRequest = { expanded = false }
+ onDismissRequest = { expanded = false },
+ modifier = Modifier.heightIn(max = 300.dp)
) {
ActionType.values().forEach { action ->
DropdownMenuItem(
text = { Text(action.name) },
onClick = {
- val newGestures = segment.gestures.toMutableMap()
- newGestures[gesture] = action
- onUpdate(segment.copy(gestures = newGestures))
- expanded = false
+ if (action == ActionType.OPEN_APP) {
+ showAppPicker = gesture
+ expanded = false
+ } else {
+ val newGestures = segment.gestures.toMutableMap()
+ newGestures[gesture] = action
+ onUpdate(segment.copy(gestures = newGestures))
+ expanded = false
+ }
}
)
}
@@ -363,3 +386,72 @@ fun GestureConfigDialog(
}
}
}
+
+@Composable
+fun AppPickerDialog(onDismiss: () -> Unit, onAppSelected: (String) -> Unit) {
+ val context = LocalContext.current
+ data class AppItem(val label: String, val packageName: String)
+ var apps by remember { mutableStateOf<List<AppItem>>(emptyList()) }
+ var isLoading by remember { mutableStateOf(true) }
+
+ LaunchedEffect(Unit) {
+ kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ val pm = context.packageManager
+ // Use getInstalledPackages to get EVERYTHING, then filter by launchability
+ val allPackages = pm.getInstalledPackages(0)
+ val list = allPackages.mapNotNull { pkg ->
+ val intent = pm.getLaunchIntentForPackage(pkg.packageName)
+ if (intent != null) {
+ val label = pkg.applicationInfo?.loadLabel(pm).toString()
+ AppItem(label, pkg.packageName)
+ } else null
+ }.sortedBy { it.label.lowercase() } // Case-insensitive sort
+
+ apps = list
+ isLoading = false
+ }
+ }
+
+ Dialog(
+ onDismissRequest = onDismiss,
+ properties = DialogProperties(usePlatformDefaultWidth = false)
+ ) {
+ Card(
+ shape = RoundedCornerShape(24.dp), // Consistent 24dp corner
+ colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(24.dp)
+ .fillMaxHeight(0.85f)
+ ) {
+ Column(modifier = Modifier.padding(24.dp)) { // Interior padding
+ Text("Select App", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
+ Spacer(modifier = Modifier.height(12.dp))
+
+ if (isLoading) {
+ Box(modifier = Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
+ CircularProgressIndicator()
+ }
+ } else {
+ androidx.compose.foundation.lazy.LazyColumn(modifier = Modifier.weight(1f)) {
+ items(apps.size) { index ->
+ val app = apps[index]
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable { onAppSelected(app.packageName) }
+ .padding(vertical = 12.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(app.label, style = MaterialTheme.typography.bodyLarge)
+ Spacer(modifier = Modifier.width(8.dp))
+ Text(app.packageName, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ }
+ Divider(color = MaterialTheme.colorScheme.surfaceVariant)
+ }
+ }
+ }
+ }
+ }
+ }
+}