diff --git a/app/src/main/java/com/glowled/app/core/LedController.kt b/app/src/main/java/com/glowled/app/core/LedController.kt index dadc951..5be4eea 100644 --- a/app/src/main/java/com/glowled/app/core/LedController.kt +++ b/app/src/main/java/com/glowled/app/core/LedController.kt @@ -143,6 +143,9 @@ object LedController { main.postDelayed({ if (NotificationStore.remove(key)) onNotificationsChanged(false) }, 60_000) } + private var pendingDropletColor: Int? = null + private var pendingDropletUntil = 0L + fun onNotificationsChanged(newPost: Boolean) = main.post { if (newPost) { suppressed = false @@ -152,12 +155,24 @@ object LedController { if (NotificationStore.isEmpty()) { cancelPulse() disarmMotion() + pendingDropletColor = null } else if (newPost && !isInteractive() && prefs.aodOnNew) { startAod(pulse = false) } updateOverlay() if (newPost && prefs.droplet && isInteractive() && !aodVisible) { - NotificationStore.apps().firstOrNull()?.let { OverlayHost.droplet(it.color) } + val app = NotificationStore.apps().firstOrNull() + if (app != null) { + DebugLog.add("Droplet triggered for ${app.pkg}") + OverlayHost.droplet(app.color) + // If overlay wasn't ready (e.g. app in foreground), retry shortly when it appears. + pendingDropletColor = app.color + pendingDropletUntil = SystemClock.uptimeMillis() + 6000 + } else { + DebugLog.add("Droplet skipped: no app") + } + } else if (newPost) { + DebugLog.add("Droplet skipped: droplet=${prefs.droplet} interactive=${isInteractive()} aod=$aodVisible") } } @@ -549,11 +564,26 @@ object LedController { fun updateOverlay() { if (!initialized) return val launching = SystemClock.uptimeMillis() < ourWakeUntil - val canShow = prefs.enabled && !aodVisible && !launching && !appInForeground && isInteractive() && - (prefs.style.isEdge || CutoutGeometry.isPortrait(app)) + val portrait = prefs.style.isEdge || CutoutGeometry.isPortrait(app) + val canShow = prefs.enabled && !aodVisible && !launching && !appInForeground && isInteractive() && portrait val notifRing = prefs.overlayEnabled && !NotificationStore.isEmpty() && (!prefs.overlayLockOnly || isLocked()) overlayMeter = if (canShow) computeMeter(notifRing) else null - if (canShow && (notifRing || overlayMeter != null || prefs.batteryIndicator)) OverlayHost.show(app) else OverlayHost.hide() + val show = canShow && (notifRing || overlayMeter != null || prefs.batteryIndicator) + if (!show && isInteractive() && !isLocked() && !NotificationStore.isEmpty()) { + DebugLog.add("Overlay off: can=$canShow enabled=${prefs.enabled} aod=$aodVisible fg=$appInForeground portrait=$portrait oE=${prefs.overlayEnabled} lockOnly=${prefs.overlayLockOnly} meter=${overlayMeter != null} batt=${prefs.batteryIndicator}") + } + if (show) { + OverlayHost.show(app) + val pending = pendingDropletColor + if (pending != null && SystemClock.uptimeMillis() <= pendingDropletUntil) { + pendingDropletColor = null + main.postDelayed({ OverlayHost.droplet(pending) }, 150) + } else if (pending != null) { + pendingDropletColor = null + } + } else { + OverlayHost.hide() + } } // ---- charging ring and transfer ring (both views) ---------------------------------------------- diff --git a/app/src/main/java/com/glowled/app/core/Prefs.kt b/app/src/main/java/com/glowled/app/core/Prefs.kt index 9c5d549..2ba6951 100644 --- a/app/src/main/java/com/glowled/app/core/Prefs.kt +++ b/app/src/main/java/com/glowled/app/core/Prefs.kt @@ -57,6 +57,10 @@ class Prefs(context: Context) { val showContent get() = bool("show_content", true) /** Liquid droplet from the camera when a notification arrives. */ val droplet get() = bool("droplet", true) + /** Droplet size (radius) in dp for the camera droplet animation. */ + val dropletSizeDp get() = int("droplet_size", 10).coerceIn(4, 28) + /** App icon size in dp in the notification icon row (screen-on / AOD). */ + val appIconDp get() = int("app_icon_size", 36).coerceIn(24, 72) /** Reply / Mark as read buttons on the message peek. */ val peekActions get() = bool("peek_actions", true) /** Always-on icons as monochrome glyphs (One UI AOD style) instead of full-colour app icons. */ @@ -79,6 +83,13 @@ class Prefs(context: Context) { // Screen-on overlay val overlayEnabled get() = bool("overlay_enabled", true) val overlayLockOnly get() = bool("overlay_lock_only", false) + /** Tap the ring on the unlocked screen to expand app icons and read messages. */ + val onTapMessages get() = bool("overlay_tap_messages", true) + // Screen-on tap response zone (collapsed ring). Offsets/sizes in dp; 0 width/height = automatic. + val tapZoneOffsetXDp get() = int("tap_zone_dx", 0).coerceIn(-300, 300) + val tapZoneOffsetYDp get() = int("tap_zone_dy", 0).coerceIn(-300, 500) + val tapZoneWidthDp get() = int("tap_zone_w", 0).coerceIn(0, 500) + val tapZoneHeightDp get() = int("tap_zone_h", 0).coerceIn(0, 800) // Charging and download rings (screen on, also over the lock screen) /** diff --git a/app/src/main/java/com/glowled/app/service/OverlayHost.kt b/app/src/main/java/com/glowled/app/service/OverlayHost.kt index 13812b6..3d3a9cd 100644 --- a/app/src/main/java/com/glowled/app/service/OverlayHost.kt +++ b/app/src/main/java/com/glowled/app/service/OverlayHost.kt @@ -18,7 +18,7 @@ import com.glowled.app.view.LedView * Screen-on indicator window. Over apps it is a "display over other apps" window, which apps that * guard against overlays (banking, payments) can hide; the accessibility overlay is only used on * the lock screen, or when there is no overlay permission. - * The window is sized tightly around the camera so the compositor has almost nothing to blend. + * The passive window is sized tightly around the camera; the interactive message view uses its own window. */ object OverlayHost { @@ -27,7 +27,18 @@ object OverlayHost { private var usingA11y = false private val listener: () -> Unit = { refresh() } + private fun shouldUseInteractive(): Boolean = ScreenOnOverlay.shouldBeInteractive() + fun show(context: Context) { + if (shouldUseInteractive()) { + hidePassive() + if (ScreenOnOverlay.isShowing()) ScreenOnOverlay.refresh() else ScreenOnOverlay.show(context) + if (ScreenOnOverlay.isShowing()) return + com.glowled.app.core.DebugLog.add("Screen-on interactive unavailable, using passive") + // Interactive failed to show; fall back to passive so the ring still appears. + } else { + if (ScreenOnOverlay.isShowing()) ScreenOnOverlay.hide() + } val a11y = LedAccessibilityService.instance?.takeIf { !Settings.canDrawOverlays(context) || LedController.isLocked() } @@ -35,7 +46,7 @@ object OverlayHost { refresh() return } - hide() + hidePassive() val ctx: Context val type: Int if (a11y != null) { @@ -71,6 +82,7 @@ object OverlayHost { val m = LedController.overlayMeter v.setMeter(m?.fraction, m?.color ?: 0, m?.icon ?: MeterIcon.NONE, m?.indeterminate ?: false) v.setBattery(LedController.batteryPercent()) + v.dropletRadiusDp = prefs.dropletSizeDp.toFloat() val flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or @@ -109,7 +121,19 @@ object OverlayHost { /** Re-applies settings, colours and the gauge; repositions the window if geometry or style changed. */ fun refresh() { - val v = view ?: return + if (shouldUseInteractive()) { + hidePassive() + if (ScreenOnOverlay.isShowing()) ScreenOnOverlay.refresh() else ScreenOnOverlay.show(LedController.app) + if (ScreenOnOverlay.isShowing()) return + // fell back to passive below if interactive couldn't be shown + } else if (ScreenOnOverlay.isShowing()) { + ScreenOnOverlay.hide() + } + val v = view ?: run { + // No passive view yet (e.g. after interactive fallback) - let show() create it. + runCatching { LedController.app }.getOrNull()?.let { show(it) } + return + } val manager = wm ?: return val type = (v.layoutParams as? WindowManager.LayoutParams)?.type ?: return val old = v.layoutParams as? WindowManager.LayoutParams ?: return @@ -125,22 +149,32 @@ object OverlayHost { /** New notification while the screen is on: a drop stretches out of the camera and springs back. */ fun droplet(color: Int) { - val v = view ?: return + if (ScreenOnOverlay.isShowing()) { + ScreenOnOverlay.droplet(color) + return + } + val v = view ?: run { + com.glowled.app.core.DebugLog.add("Droplet skipped: no overlay") + return + } + com.glowled.app.core.DebugLog.add("Droplet on passive ring") // Post: the window may have just been added and not laid out yet. v.post { v.playDropletBelow(color, DROP_DP * v.resources.displayMetrics.density, retract = true) } } private const val DROP_DP = 26f - fun hide() { + private fun hidePassive() { val v = view ?: return - LedController.removeListener(listener) + try { LedController.removeListener(listener) } catch (_: Exception) {} v.visibility = View.GONE - try { - wm?.removeViewImmediate(v) - } catch (_: Exception) { - } + try { wm?.removeViewImmediate(v) } catch (_: Exception) {} view = null wm = null } + + fun hide() { + hidePassive() + if (ScreenOnOverlay.isShowing()) ScreenOnOverlay.hide() + } } diff --git a/app/src/main/java/com/glowled/app/service/ScreenOnOverlay.kt b/app/src/main/java/com/glowled/app/service/ScreenOnOverlay.kt new file mode 100644 index 0000000..b1f62e8 --- /dev/null +++ b/app/src/main/java/com/glowled/app/service/ScreenOnOverlay.kt @@ -0,0 +1,527 @@ +package com.glowled.app.service + +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.Color +import android.graphics.PixelFormat +import android.graphics.Rect +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.provider.Settings +import android.util.Log +import android.view.Gravity +import android.view.MotionEvent +import android.view.View +import android.view.WindowManager +import android.widget.FrameLayout +import androidx.core.view.doOnLayout +import com.glowled.app.core.CutoutGeometry +import com.glowled.app.core.DebugLog +import com.glowled.app.core.Geometry +import com.glowled.app.core.LedController +import com.glowled.app.core.MeterIcon +import com.glowled.app.core.NotificationStore +import com.glowled.app.ui.ReplyActivity +import com.glowled.app.view.AppInfoView +import com.glowled.app.view.LedView +import com.glowled.app.view.NotificationPeekView +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.roundToInt + +/** + * Interactive notification overlay for screen-on (unlocked) use. + * + * - collapsed: ring around the camera only; tap the ring to expand; + * - icons: one circle/icon per source app below the camera; tap an icon to read; + * - peek: message card for the selected app, with reply / mark-as-read / open. + * + * Actions mirror the screen-off message view. The window is sized to the visible UI so touches + * outside it reach the apps below. + */ +@SuppressLint("ClickableViewAccessibility") +object ScreenOnOverlay { + + private enum class State { COLLAPSED, ICONS, PEEK } + + private var state = State.COLLAPSED + private var root: RootLayout? = null + private var led: LedView? = null + private var info: AppInfoView? = null + private var peek: NotificationPeekView? = null + private var wm: WindowManager? = null + private var windowCtx: Context? = null + private var usingA11y = false + + private val main = Handler(Looper.getMainLooper()) + private val hidePeekRunnable = Runnable { hidePeek(showIconsAfter = true) } + + private var peekPkg: String? = null + private var newestTime = 0L + + private val listener: () -> Unit = { main.post { onStoreChanged() } } + + private open class RootLayout(context: Context) : FrameLayout(context) { + var onLaidOut: (() -> Unit)? = null + + override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { + super.onLayout(changed, l, t, r, b) + onLaidOut?.invoke() + } + } + + fun isShowing(): Boolean = root != null + + /** True when the screen-on overlay should be the interactive (tappable) one. */ + fun shouldBeInteractive(): Boolean { + val p = LedController.prefs + return p.overlayEnabled && p.onTapMessages && !NotificationStore.isEmpty() && + !LedController.isLocked() && !p.overlayLockOnly && !p.style.isEdge + } + + fun show(context: Context) { + val prefs = LedController.prefs + if (!prefs.enabled) return hide() + // Prefer accessibility overlay for interactive/touch input (better cutout touch behavior on some devices). + val a11y = LedAccessibilityService.instance + val wantA11y = a11y != null + if (root != null && usingA11y == wantA11y) { + refresh() + return + } + hide() + val ctx: Context + val type: Int + if (a11y != null) { + ctx = a11y; type = WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY + } else if (Settings.canDrawOverlays(context)) { + ctx = context.applicationContext; type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY + } else { + DebugLog.add("Screen-on overlay: no permission/service") + return + } + + val r = object : RootLayout(ctx) { + private var downX = 0f; private var downY = 0f; private var downT = 0L + override fun dispatchTouchEvent(ev: MotionEvent): Boolean { + if (ev.actionMasked == MotionEvent.ACTION_DOWN) { + downX = ev.rawX; downY = ev.rawY; downT = ev.eventTime + val loc = IntArray(2); getLocationOnScreen(loc) + DebugLog.add("Screen-on touch down ($state) at ${ev.rawX.toInt()},${ev.rawY.toInt()} win=${loc[0]},${loc[1]} ${width}x${height}") + } + val handled = super.dispatchTouchEvent(ev) + if (ev.actionMasked == MotionEvent.ACTION_UP) { + val slop = 48 * resources.displayMetrics.density + val isTap = ev.eventTime - downT < 400 && abs(ev.rawX - downX) < slop && abs(ev.rawY - downY) < slop + if (isTap && !hitInteractive(ev)) { + DebugLog.add("Screen-on ring tapped ($state)") + onBackgroundTap() + } + } + if (ev.actionMasked == MotionEvent.ACTION_DOWN) return true + return handled || ev.actionMasked == MotionEvent.ACTION_UP || ev.actionMasked == MotionEvent.ACTION_CANCEL + } + private fun hitInteractive(ev: MotionEvent): Boolean { + val i = info + if (i != null && i.visibility == View.VISIBLE && pointInView(i, ev.rawX, ev.rawY)) return true + val p = peek + if (p != null && p.isShowing() && pointInView(p, ev.rawX, ev.rawY)) return true + return false + } + private fun pointInView(v: View, rawX: Float, rawY: Float): Boolean { + val loc = IntArray(2); v.getLocationOnScreen(loc) + return rawX >= loc[0] && rawX <= loc[0] + v.width && rawY >= loc[1] && rawY <= loc[1] + v.height + } + }.apply { + setBackgroundColor(Color.TRANSPARENT) + isForceDarkAllowed = false + clipChildren = false + clipToPadding = false + isClickable = true + isFocusable = false + } + + val ledView = LedView(ctx).apply { useScreenCoords = true; intro = 1f; dropletRadiusDp = prefs.dropletSizeDp.toFloat() } + val infoView = AppInfoView(ctx).apply { + monochrome = prefs.aodIcons + iconDp = prefs.appIconDp + onAppTap = { pkg -> onAppTapped(pkg) } + } + val d = ctx.resources.displayMetrics.density + val peekWidth = (ctx.resources.displayMetrics.widthPixels - (48 * d).toInt()).coerceAtMost((380 * d).toInt()) + val peekView = NotificationPeekView(ctx).apply { + onOpen = { e -> openNotification(e) } + onReply = { e -> replyTo(e) } + onMarkRead = { e -> markRead(e) } + } + + r.addView(ledView, FrameLayout.LayoutParams(-1, -1)) + r.addView(infoView, FrameLayout.LayoutParams(-2, -2)) + r.addView(peekView, FrameLayout.LayoutParams(peekWidth, -2)) + r.onLaidOut = { positionChildren() } + + root = r; led = ledView; info = infoView; peek = peekView + windowCtx = ctx; usingA11y = wantA11y + wm = ctx.getSystemService(WindowManager::class.java) + state = State.COLLAPSED; peekPkg = null + newestTime = NotificationStore.newestTime() + + applyWindow(type) + if (root == null) return + LedController.addListener(listener) + DebugLog.add("Screen-on interactive overlay shown (${if (wantA11y) "a11y" else "app"})") + refresh() + } + + private fun geometry(ctx: Context): Geometry = CutoutGeometry.resolve(ctx, LedController.prefs) + + private fun extentPx(g: Geometry, prefs: com.glowled.app.core.Prefs, d: Float): Int { + val thickness = prefs.thicknessDp * d + val gap = prefs.gapDp * d + val glowRadius = if (prefs.glow) thickness * 1.6f + 3 * d else 0f + val half = max(g.w, g.h) / 2f + gap + thickness + return (half + thickness * 7 + glowRadius * 2 + 4 * d).toInt() + } + + /** Screen-space tap/response zone for the collapsed screen-on ring. */ + fun tapZoneRect(ctx: Context): android.graphics.Rect { + val prefs = LedController.prefs + val g = geometry(ctx) + val d = ctx.resources.displayMetrics.density + val e = extentPx(g, prefs, d) + val ringW = maxOf(e * 2, (120 * d).toInt()) + val autoW = ringW + val autoH = (g.cy.toInt() + e + (DROP_DP * d).toInt() * 2 + (120 * d).toInt()) + .coerceAtLeast(e * 2 + (DROP_DP * d).toInt() * 2) + val w = if (prefs.tapZoneWidthDp > 0) (prefs.tapZoneWidthDp * d).toInt().coerceAtLeast((40 * d).toInt()) else autoW + val h = if (prefs.tapZoneHeightDp > 0) (prefs.tapZoneHeightDp * d).toInt().coerceAtLeast((40 * d).toInt()) else autoH + val dm = ctx.resources.displayMetrics + var x = (g.cx - w / 2f).toInt() + (prefs.tapZoneOffsetXDp * d).toInt() + var y = 0 + (prefs.tapZoneOffsetYDp * d).toInt() + // Keep on screen. + x = x.coerceIn(0, (dm.widthPixels - w).coerceAtLeast(0)) + y = y.coerceIn(0, (dm.heightPixels - h).coerceAtLeast(0)) + return android.graphics.Rect(x, y, x + w, y + h) + } + + private fun currentParams(): WindowManager.LayoutParams? = root?.layoutParams as? WindowManager.LayoutParams + private fun windowType(): Int = currentParams()?.type ?: 0 + + private fun applyWindow(type: Int) { + val r = root ?: return + val ctx = windowCtx ?: return + val manager = wm ?: return + val p = buildParams(ctx, type) + if (r.parent == null) { + try { manager.addView(r, p) } catch (e: Exception) { + Log.w("GlowLED", "interactive overlay add failed", e); cleanupRefs(); return + } + } else { + try { manager.updateViewLayout(r, p) } catch (e: Exception) { + Log.w("GlowLED", "interactive overlay update failed", e) + } + } + } + + private fun buildParams(ctx: Context, type: Int): WindowManager.LayoutParams { + val prefs = LedController.prefs + val g = geometry(ctx) + val ledView = led!! + val d = ctx.resources.displayMetrics.density + ledView.configure(prefs, g, NotificationStore.colors()) + ledView.notificationRingVisible = prefs.overlayEnabled && !NotificationStore.isEmpty() && + (!prefs.overlayLockOnly || LedController.isLocked()) + val m = LedController.overlayMeter + ledView.setMeter(m?.fraction, m?.color ?: 0, m?.icon ?: MeterIcon.NONE, m?.indeterminate ?: false) + ledView.setBattery(LedController.batteryPercent()) + + val flags = 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 or + WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED + val p: WindowManager.LayoutParams + if (prefs.style.isEdge) { + p = WindowManager.LayoutParams( + WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, + type, flags, PixelFormat.TRANSLUCENT, + ) + p.gravity = Gravity.TOP or Gravity.START + } else { + val e = ledView.extentPx(g) + val peekW = (ctx.resources.displayMetrics.widthPixels - (48 * d).toInt()).coerceAtMost((380 * d).toInt()) + val ringW = maxOf(e * 2, (120 * d).toInt()) + val expandedW = maxOf(ringW, peekW + (24 * d).toInt(), (220 * d).toInt()) + if (state == State.COLLAPSED) { + val tz = tapZoneRect(ctx) + p = WindowManager.LayoutParams(tz.width(), tz.height(), type, flags, PixelFormat.TRANSLUCENT) + p.gravity = Gravity.TOP or Gravity.START + p.x = tz.left; p.y = tz.top + } else { + val w = expandedW + val x = (g.cx - w / 2f).toInt() + val y = (g.cy - e).toInt() + val h = when (state) { + State.ICONS -> e + (300 * d).toInt() + State.PEEK -> (ctx.resources.displayMetrics.heightPixels - y).coerceAtLeast(e + (520 * d).toInt()) + else -> e * 2 + } + p = WindowManager.LayoutParams(w, h, type, flags, PixelFormat.TRANSLUCENT) + p.gravity = Gravity.TOP or Gravity.START + p.x = x; p.y = y + } + } + p.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) p.fitInsetsTypes = 0 + if (type == WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + p.alpha = 0.8f + } + p.title = "GlowLED" + return p + } + + fun refresh() { + val r = root ?: return + val ctx = windowCtx ?: return + val prefs = LedController.prefs + val ledView = led ?: return + val g = geometry(ctx) + ledView.configure(prefs, g, NotificationStore.colors()) + ledView.notificationRingVisible = prefs.overlayEnabled && !NotificationStore.isEmpty() && + (!prefs.overlayLockOnly || LedController.isLocked()) + val m = LedController.overlayMeter + ledView.setMeter(m?.fraction, m?.color ?: 0, m?.icon ?: MeterIcon.NONE, m?.indeterminate ?: false) + ledView.setBattery(LedController.batteryPercent()) + ledView.dropletRadiusDp = prefs.dropletSizeDp.toFloat() + info?.monochrome = prefs.aodIcons + info?.iconDp = prefs.appIconDp + val type = windowType() + if (type != 0) applyWindow(type) + r.requestLayout() + r.post { positionChildren() } + } + + private fun positionChildren() { + val r = root ?: return + val ctx = windowCtx ?: return + val ledView = led ?: return + val infoView = info ?: return + val peekView = peek ?: return + if (!r.isAttachedToWindow) return + val loc = IntArray(2) + r.getLocationOnScreen(loc) + val g = geometry(ctx) + val d = ctx.resources.displayMetrics.density + val safeTop = max(ledView.indicatorBottom() + 16 * d, 8 * d) + val infoX = g.cx - loc[0] - infoView.measuredWidth / 2f + val infoY = safeTop + place(infoView, infoX, infoY) + val peekY = infoY + (if (infoView.visibility == View.VISIBLE) infoView.measuredHeight + 14 * d else 0f) + place(peekView, g.cx - loc[0] - peekView.measuredWidth / 2f, peekY) + } + + private fun place(v: View, x: Float, y: Float) { + val l = x.roundToInt(); val t = y.roundToInt() + v.layout(l, t, l + v.measuredWidth, t + v.measuredHeight) + } + + private fun setState(newState: State) { + if (state == newState && root != null) return + state = newState + val type = windowType() + if (type != 0) applyWindow(type) + root?.requestLayout() + root?.post { positionChildren() } + } + + private fun bindApps() { info?.bind(NotificationStore.apps()) } + + private fun expandToIcons(withDroplet: Boolean = false) { + val prefs = LedController.prefs + bindApps() + // show icons (even if one app) to satisfy "раскрывается несколько кружков" + if (state == State.COLLAPSED) setState(State.ICONS) else setState(State.ICONS) + main.removeCallbacks(hidePeekRunnable) + val newest = NotificationStore.apps().firstOrNull() + if (withDroplet && prefs.droplet && newest != null) { + info?.visibility = View.VISIBLE + info?.alpha = 1f + info?.doOnLayout { + if (root == null) return@doOnLayout + info?.prepareDrop() + val ctx = windowCtx ?: return@doOnLayout + val loc = IntArray(2); root!!.getLocationOnScreen(loc) + val g = geometry(ctx) + val infoView = info ?: return@doOnLayout + val infoX = g.cx - loc[0] - infoView.measuredWidth / 2f + val tx = infoX + infoView.newestCenterX() + val ty = infoView.top.toFloat() + infoView.iconCenterY() + led?.playDroplet(newest.color, ty, targetX = tx) { info?.popNewest() } + } + } else { + info?.show() + } + } + + private fun collapseToRing() { + main.removeCallbacks(hidePeekRunnable) + hidePeek(showIconsAfter = false) + info?.clearSelection() + info?.hide() + setState(State.COLLAPSED) + } + + private fun onAppTapped(pkg: String) { + val prefs = LedController.prefs + main.removeCallbacks(hidePeekRunnable) + if (!prefs.showContent) { + info?.clearSelection() + return + } + val entries = NotificationStore.entriesFor(pkg) + if (entries.isEmpty() || (peek?.isShowing() == true && peekPkg == pkg)) { + hidePeek(showIconsAfter = true) + return + } + peekPkg = pkg + peek?.actionsEnabled = prefs.peekActions + peek?.bind(entries) + peek?.show() + setState(State.PEEK) + root?.post { positionChildren() } + main.postDelayed(hidePeekRunnable, PEEK_MS) + } + + private fun hidePeek(showIconsAfter: Boolean) { + main.removeCallbacks(hidePeekRunnable) + peekPkg = null + peek?.hide() + info?.clearSelection() + if (state == State.PEEK) setState(State.ICONS) + } + + private fun onBackgroundTap() { + when (state) { + State.PEEK -> hidePeek(showIconsAfter = true) + State.ICONS -> collapseToRing() + State.COLLAPSED -> { + if (!NotificationStore.isEmpty()) expandToIcons(withDroplet = true) + else DebugLog.add("Screen-on tap: no notifications") + } + } + } + + // ---- actions (same as AOD, but on unlocked screen) ---- + + private fun openNotification(e: NotificationStore.Entry) { + val pi = e.intent ?: return + root?.performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY) + try { + val opts = android.app.ActivityOptions.makeBasic() + if (Build.VERSION.SDK_INT >= 34) { + opts.setPendingIntentBackgroundActivityStartMode( + android.app.ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED, + ) + } + pi.send(windowCtx ?: LedController.app, 0, null, null, null, null, opts.toBundle()) + } catch (ex: Exception) { + DebugLog.add("Could not open notification: ${ex.javaClass.simpleName}") + } + collapseToRing() + } + + private fun replyTo(e: NotificationStore.Entry) { + root?.performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY) + if (ReplyActivity.start(LedController.app, e.key)) collapseToRing() + } + + private fun markRead(e: NotificationStore.Entry) { + root?.performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY) + val action = e.readAction + if (action != null) { + try { action.actionIntent.send() } catch (ex: Exception) { + DebugLog.add("Mark as read failed: ${ex.javaClass.simpleName}") + } + NotificationStore.markSeen(e.key) + LedController.refreshAll() + } else { + NotifyListenerService.instance?.cancelNotification(e.key) + } + DebugLog.add("Marked as read from screen-on overlay") + // store change will update; keep UX responsive + if (NotificationStore.isEmpty()) collapseToRing() else { + if (NotificationStore.entriesFor(peekPkg ?: "").isEmpty()) hidePeek(true) + } + } + + private fun onStoreChanged() { + if (root == null) return + if (NotificationStore.isEmpty()) { + // let controller decide (may keep overlay for meter/battery) -> will hide interactive + LedController.updateOverlay() + return + } + val apps = NotificationStore.apps() + if (apps.isEmpty()) { LedController.updateOverlay(); return } + bindApps() + val newest = NotificationStore.newestTime() + if (newest > newestTime) { + val newestApp = apps.firstOrNull() + newestTime = newest + if (state != State.COLLAPSED && newestApp != null && LedController.prefs.droplet) { + info?.doOnLayout { + if (root == null) return@doOnLayout + info?.prepareDrop() + val ctx = windowCtx ?: return@doOnLayout + val loc = IntArray(2); root!!.getLocationOnScreen(loc) + val g = geometry(ctx) + val infoView = info ?: return@doOnLayout + val infoX = g.cx - loc[0] - infoView.measuredWidth / 2f + val tx = infoX + infoView.newestCenterX() + val ty = infoView.top.toFloat() + infoView.iconCenterY() + led?.playDroplet(newestApp.color, ty, targetX = tx) { info?.popNewest() } + } + } else if (state != State.COLLAPSED) { + info?.show() + } + // collapsed: ring droplet handled by LedController/OverlayHost path + } + peekPkg?.let { pkg -> + val entries = NotificationStore.entriesFor(pkg) + if (entries.isEmpty()) hidePeek(showIconsAfter = true) else peek?.bind(entries) + } + refresh() + root?.post { positionChildren() } + } + + /** Droplet on the ring while collapsed. */ + fun droplet(color: Int) { + val ledView = led ?: run { + DebugLog.add("Droplet skipped: no overlay view") + return + } + if (state == State.COLLAPSED) { + DebugLog.add("Droplet on screen-on ring") + ledView.post { ledView.playDropletBelow(color, DROP_DP * ledView.resources.displayMetrics.density, retract = true) } + } else { + DebugLog.add("Droplet skipped: state=$state") + } + } + + fun hide() { + val r = root ?: return + try { LedController.removeListener(listener) } catch (_: Exception) {} + main.removeCallbacksAndMessages(null) + try { wm?.removeViewImmediate(r) } catch (_: Exception) {} + cleanupRefs() + } + + private fun cleanupRefs() { + root = null; led = null; info = null; peek = null; wm = null; windowCtx = null + usingA11y = false; state = State.COLLAPSED; peekPkg = null + } + + private const val DROP_DP = 26f + private const val PEEK_MS = 12_000L +} diff --git a/app/src/main/java/com/glowled/app/ui/AodSession.kt b/app/src/main/java/com/glowled/app/ui/AodSession.kt index e2aa29d..7856bb3 100644 --- a/app/src/main/java/com/glowled/app/ui/AodSession.kt +++ b/app/src/main/java/com/glowled/app/ui/AodSession.kt @@ -193,10 +193,13 @@ class AodSession( } // No overlay available: keep the ring visible right under the window's top edge. val g = CutoutGeometry.resolve(context, prefs) - val ringTop = g.cy - led.ringBottom() + g.cy // mirror of the bottom around the centre + val ledLoc = IntArray(2); led.getLocationOnScreen(ledLoc) + val ringBottomScreen = ledLoc[1] + led.ringBottom() + val ringTop = g.cy - (ringBottomScreen - g.cy) // mirror of the bottom around the centre if (ringTop < loc[1]) { yShift = loc[1] - ringTop + 6 * density led.configure(prefs, geometry(), currentColors()) + led.dropletRadiusDp = prefs.dropletSizeDp.toFloat() } } val g = geometry() @@ -236,6 +239,7 @@ class AodSession( private fun bindInfo() { if (!prefs.showAppInfo) return info.monochrome = prefs.aodIcons + info.iconDp = prefs.appIconDp var apps = NotificationStore.apps() if (preview && apps.isEmpty()) apps = sampleApps info.bind(apps) @@ -421,7 +425,8 @@ class AodSession( } fun restartAnimation() { - led.configure(prefs, geometry(), currentColors()) // undoes an eco still ring + led.configure(prefs, geometry(), currentColors()) + led.dropletRadiusDp = prefs.dropletSizeDp.toFloat() // undoes an eco still ring updateMeters() updateAgeFade() led.restartAnimation() @@ -522,6 +527,7 @@ class AodSession( return } led.configure(prefs, geometry(), currentColors()) + led.dropletRadiusDp = prefs.dropletSizeDp.toFloat() updateMeters() updateAgeFade() armSettle() @@ -567,6 +573,7 @@ class AodSession( init { led.useScreenCoords = true led.configure(prefs, geometry(), currentColors()) + led.dropletRadiusDp = prefs.dropletSizeDp.toFloat() led.intro = 0f updateAgeFade() root.addView(info, FrameLayout.LayoutParams(-2, -2)) diff --git a/app/src/main/java/com/glowled/app/ui/MainActivity.kt b/app/src/main/java/com/glowled/app/ui/MainActivity.kt index 3a36aea..7c70e10 100644 --- a/app/src/main/java/com/glowled/app/ui/MainActivity.kt +++ b/app/src/main/java/com/glowled/app/ui/MainActivity.kt @@ -62,6 +62,7 @@ import com.glowled.app.core.PowerGuard import com.glowled.app.core.Prefs import com.glowled.app.service.LedAccessibilityService import com.glowled.app.service.NotifyListenerService +import com.glowled.app.service.ScreenOnOverlay import com.glowled.app.ui.SettingsUi.Range import com.glowled.app.ui.SettingsUi.Toggle import com.glowled.app.ui.SettingsUi.ColorItem @@ -90,6 +91,8 @@ class MainActivity : AppCompatActivity() { /** Full-screen, touch-through layer that draws the ring on the phone's real camera cutout. */ private lateinit var cameraLed: LedView private var introAnim: ValueAnimator? = null + /** Outline of the screen-on tap/response zone, shown while configuring it. */ + private var tapZoneOutline: TapZoneOutlineView? = null private lateinit var pager: ViewPager2 private lateinit var tabs: TabLayout private lateinit var ui: SettingsUi @@ -132,6 +135,7 @@ class MainActivity : AppCompatActivity() { if (key in REPLAY_KEYS) playCameraIntro() if (key != null && (key.startsWith("charge_") || key.startsWith("progress_") || key == "upload_color" || key == "download_color")) previewMeter(key) if (key == "style" || key == Prefs.K_ENABLED) ui.refresh() + if (key != null && key.startsWith("tap_zone_")) updateTapZoneOutline() } override fun onCreate(savedInstanceState: Bundle?) { @@ -156,6 +160,13 @@ class MainActivity : AppCompatActivity() { importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO } findViewById(android.R.id.content).addView(cameraLed, FrameLayout.LayoutParams(-1, -1)) + tapZoneOutline = TapZoneOutlineView(this).apply { + isClickable = false + isFocusable = false + importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO + visibility = View.GONE + } + findViewById(android.R.id.content).addView(tapZoneOutline, FrameLayout.LayoutParams(-1, -1)) cameraLed.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> configureCameraLed() } master = findViewById(R.id.master) @@ -294,6 +305,7 @@ class MainActivity : AppCompatActivity() { cameraLed.visibility = if (show) View.VISIBLE else View.INVISIBLE if (!show) return cameraLed.configure(prefs, CutoutGeometry.resolve(this, prefs), cameraColors()) + updateTapZoneOutline() } /** The ring grows out of the camera and fades in (same entrance as the always-on screen). */ @@ -369,7 +381,13 @@ class MainActivity : AppCompatActivity() { pager.adapter = PagesAdapter(pageViews) pager.offscreenPageLimit = pages.size TabLayoutMediator(tabs, pager) { tab, i -> tab.text = pages[i].first }.attach() + pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { + override fun onPageSelected(position: Int) { + updateTapZoneOutline() + } + }) ui.refresh() + updateTapZoneOutline() } private class PagesAdapter(val pages: List) : RecyclerView.Adapter() { @@ -524,10 +542,39 @@ class MainActivity : AppCompatActivity() { private fun pageScreenOn(): View { val (page, col) = ui.page() + val ringOn = { prefs.overlayEnabled } + val tapOn = { prefs.overlayEnabled && prefs.onTapMessages && !prefs.overlayLockOnly } section(col, R.string.sec_ring_on, first = true) ui.toggles(col, listOf( Toggle(getString(R.string.t_ring_on), "overlay_enabled", true), - Toggle(getString(R.string.t_lock_only), "overlay_lock_only", false) { prefs.overlayEnabled }, + Toggle(getString(R.string.t_lock_only), "overlay_lock_only", false, ringOn), + Toggle(getString(R.string.t_overlay_tap_messages), "overlay_tap_messages", true) { prefs.overlayEnabled && !prefs.overlayLockOnly }, + Toggle(getString(R.string.t_droplet), "droplet", true, ringOn), + )) + val ringCard = ui.card(col) + ui.sliders(ringCard, + Range(getString(R.string.s_droplet_size), "droplet_size", 4, 28, 10, "dp"), + Range(getString(R.string.s_icon_size), "app_icon_size", 24, 72, 36, "dp"), + dependsOn = ringOn) + section(col, R.string.sec_tap_zone) + val tz = ui.card(col) + ui.sliders(tz, + Range(getString(R.string.s_tap_zone_x), "tap_zone_dx", -300, 300, 0, "dp"), + Range(getString(R.string.s_tap_zone_y), "tap_zone_dy", -300, 500, 0, "dp"), + dependsOn = tapOn) + ui.sliders(tz, + Range(getString(R.string.s_tap_zone_w), "tap_zone_w", 0, 500, 0, "dp"), + Range(getString(R.string.s_tap_zone_h), "tap_zone_h", 0, 800, 0, "dp"), + dependsOn = tapOn) + val tzHint = hint(getString(R.string.tap_zone_hint)) + col.addView(tzHint) + ui.dependOn(tzHint, tapOn) + ui.dependOn(tz.parent as View, tapOn) + section(col, R.string.sec_messages) + ui.toggles(col, listOf( + Toggle(getString(R.string.t_aod_icons), "aod_icons", true, tapOn), + Toggle(getString(R.string.t_tap_read), "show_content", true, tapOn), + Toggle(getString(R.string.t_peek_actions), "peek_actions", true) { tapOn() && prefs.showContent }, )) section(col, R.string.sec_charging) ui.toggles(col, listOf( @@ -1025,6 +1072,39 @@ class MainActivity : AppCompatActivity() { buildSetup() } + // ---- tap zone outline --------------------------------------------------------------------- + + private fun updateTapZoneOutline() { + val v = tapZoneOutline ?: return + val onScreenOnTab = ::pager.isInitialized && pager.currentItem == 3 + if (!onScreenOnTab) { + v.visibility = View.GONE + return + } + v.zoneRect = try { ScreenOnOverlay.tapZoneRect(this) } catch (_: Exception) { null } + v.visibility = if (v.zoneRect != null) View.VISIBLE else View.GONE + } + + private inner class TapZoneOutlineView(context: android.content.Context) : View(context) { + private val strokePaint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply { + style = android.graphics.Paint.Style.STROKE + strokeWidth = 3f * resources.displayMetrics.density + color = context.getColor(R.color.accent) + } + private val fillPaint = android.graphics.Paint().apply { + style = android.graphics.Paint.Style.FILL + color = (context.getColor(R.color.accent) and 0x00FFFFFF) or 0x2A000000 + } + var zoneRect: android.graphics.Rect? = null + set(value) { field = value; invalidate() } + + override fun onDraw(c: android.graphics.Canvas) { + val r = zoneRect ?: return + c.drawRect(r, fillPaint) + c.drawRect(r, strokePaint) + } + } + // ---- test notification --------------------------------------------------------------------- private var pillTucked = false diff --git a/app/src/main/java/com/glowled/app/view/AppInfoView.kt b/app/src/main/java/com/glowled/app/view/AppInfoView.kt index 895c847..04bc96b 100644 --- a/app/src/main/java/com/glowled/app/view/AppInfoView.kt +++ b/app/src/main/java/com/glowled/app/view/AppInfoView.kt @@ -32,6 +32,10 @@ class AppInfoView(context: Context) : LinearLayout(context) { /** AOD-style monochrome glyphs instead of full-colour app icons (set before [bind]). */ var monochrome = true + /** Icon diameter in dp. */ + var iconDp: Int = 36 + set(v) { field = v.coerceIn(24, 72) } + private val d = resources.displayMetrics.density private fun dp(v: Float) = (v * d).toInt() private val icons = LinearLayout(context).apply { @@ -54,7 +58,7 @@ class AppInfoView(context: Context) : LinearLayout(context) { } /** Vertical centre of the icon row, relative to this view (where the droplet should land). */ - fun iconCenterY(): Float = icons.top + dp(ICON_DP / 2f).toFloat() + fun iconCenterY(): Float = icons.top + dp(iconDp / 2f).toFloat() /** Horizontal centre of the newest app's icon, relative to this view. */ fun newestCenterX(): Float { @@ -72,7 +76,7 @@ class AppInfoView(context: Context) : LinearLayout(context) { centreOut(shownApps).forEachIndexed { i, app -> val chip = iconChip(pm, app) chips[app.pkg] = chip - icons.addView(chip, LayoutParams(dp(ICON_DP), dp(ICON_DP)).apply { if (i > 0) marginStart = dp(16f) }) + icons.addView(chip, LayoutParams(dp(iconDp.toFloat()), dp(iconDp.toFloat())).apply { if (i > 0) marginStart = dp(16f) }) } if (selected != null && shownApps.none { it.pkg == selected }) selected = null applySelection() @@ -216,7 +220,6 @@ class AppInfoView(context: Context) : LinearLayout(context) { companion object { private const val MAX_ICONS = 5 - private const val ICON_DP = 36f private const val GLYPH_PAD_DP = 7f private const val MONO_GREY = 0xFFB4B4B4.toInt() private val GREYSCALE = ColorMatrixColorFilter( diff --git a/app/src/main/java/com/glowled/app/view/LedView.kt b/app/src/main/java/com/glowled/app/view/LedView.kt index 334423c..36d0304 100644 --- a/app/src/main/java/com/glowled/app/view/LedView.kt +++ b/app/src/main/java/com/glowled/app/view/LedView.kt @@ -183,7 +183,7 @@ class LedView @JvmOverloads constructor( fun indicatorBottom(): Float = ringBottom() + (if (batteryLabel != null) indicatorLineHeight else 0f) private fun drawLabels(c: Canvas) { - val y = ringBottom() - (geometry?.cy ?: cy) + cy + indicatorLineHeight - labelPaint.descent() + val y = ringBottom() + indicatorLineHeight - labelPaint.descent() batteryLabel?.let { labelPaint.color = Color.WHITE labelPaint.alpha = (220 * alphaMul * intro).toInt() @@ -328,11 +328,11 @@ class LedView @JvmOverloads constructor( private fun glowRadius() = if (glow) thickness * 1.6f + 3 * density else 0f - /** Lowest point of the drawn ring, in the geometry's coordinates (to place content under it). */ + /** Lowest point of the drawn ring, in view-local coordinates (to place content under it). */ fun ringBottom(): Float { val g = geometry ?: return 0f val r = if (g.shape == CutoutShape.DOT) max(g.w, g.h) / 2f else g.h / 2f + gap + thickness - return g.cy + r + glowRadius() + return cy + r + glowRadius() } // ---- droplet: liquid drop that stretches out of the camera, detaches, falls and splashes ------ @@ -346,6 +346,8 @@ class LedView @JvmOverloads constructor( private var dropTargetY = 0f private var dropTargetX = Float.NaN // NaN = straight below the camera private var dropRetract = false + /** Droplet radius in dp. */ + var dropletRadiusDp: Float = 10f /** * Plays the droplet in [color] from the bottom of the ring down to [targetY] (view coordinates). @@ -411,8 +413,7 @@ class LedView @JvmOverloads constructor( val x = cx val top = cy + ringR // bottom edge of the ring: where the liquid comes out val dist = max(dropTargetY - top, ringR * 2f) - // Big enough to read as a drop on a real phone (~5-7 dp radius). - val rb = max(max(thickness * 2.2f, ringR * 0.45f), 5f * density) + val rb = max(dropletRadiusDp * density, thickness * 1.8f) dropPaint.color = dropColor if (glow) dropPaint.setShadowLayer(glowRadius(), 0f, 0f, dropColor) else dropPaint.clearShadowLayer() diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 0d844cd..c6caaa9 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -342,4 +342,13 @@ Загрузка заполняет кольцо, со стрелкой ↓. Отправка Отправка заполняет кольцо, со стрелкой ↑. + Нажатие на кольцо — читать сообщения + Размер капли + Размер иконок приложений + Зона нажатия на кольцо + Смещение зоны по X + Смещение зоны по Y + Ширина зоны (0 = авто) + Высота зоны (0 = авто) + Настройте, если нажатия не попадают по кольцу. Во время настройки показывается граница зоны. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 454b3f2..afa3ba1 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -343,4 +343,13 @@ A download fills the ring, with a ↓ arrow. Uploading An upload fills the ring, with a ↑ arrow. + Tap ring to read messages + Droplet size + App icon size + Tap response zone + Tap zone offset X + Tap zone offset Y + Tap zone width (0 = auto) + Tap zone height (0 = auto) + Adjust if taps don\'t reach the ring. A border shows the tap zone while you configure it here. diff --git a/releases/GlowLED-v2.10.1-screen-on-messages-debug.apk b/releases/GlowLED-v2.10.1-screen-on-messages-debug.apk new file mode 100644 index 0000000..607c832 Binary files /dev/null and b/releases/GlowLED-v2.10.1-screen-on-messages-debug.apk differ