StatusFragment.kt 8.57 KB
package ai.lemon.phoneuse

import android.accessibilityservice.AccessibilityServiceInfo
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.accessibility.AccessibilityManager
import android.widget.Button
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.fragment.app.Fragment
import ai.lemon.phoneuse.service.AgentRuntimeService
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class StatusFragment : Fragment() {

    private lateinit var tvUptime: TextView
    private lateinit var tvRuntimeStatus: TextView
    private lateinit var btnToggleRuntime: Button
    private lateinit var btnOpenSettings: Button
    private lateinit var tvEventLog: TextView

    private lateinit var cardAccessibility: CardView
    private lateinit var cardNotification: CardView
    private lateinit var cardRoot: CardView
    private lateinit var cardMcp: CardView

    private val handler = Handler(Looper.getMainLooper())
    private val logLines = ArrayDeque<String>(10)
    private var startTime = System.currentTimeMillis()
    private var runtimeRunning = false

    private val eventReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                MainActivity.ACTION_RUNTIME_STARTED -> onRuntimeStarted()
                MainActivity.ACTION_RUNTIME_STOPPED -> onRuntimeStopped()
                MainActivity.ACTION_EVENT_LOG -> {
                    val msg = intent.getStringExtra(MainActivity.EXTRA_LOG_MESSAGE) ?: return
                    appendLog(msg)
                }
            }
        }
    }

    private val tickRunnable = object : Runnable {
        override fun run() {
            if (isAdded) refreshStatus()
            handler.postDelayed(this, TICK_MS)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View = inflater.inflate(R.layout.fragment_status, container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        tvUptime = view.findViewById(R.id.tvUptime)
        tvRuntimeStatus = view.findViewById(R.id.tvRuntimeStatus)
        btnToggleRuntime = view.findViewById(R.id.btnToggleRuntime)
        btnOpenSettings = view.findViewById(R.id.btnOpenSettings)
        tvEventLog = view.findViewById(R.id.tvEventLog)

        cardAccessibility = view.findViewById(R.id.cardAccessibility)
        cardNotification = view.findViewById(R.id.cardNotification)
        cardRoot = view.findViewById(R.id.cardRoot)
        cardMcp = view.findViewById(R.id.cardMcp)

        setupCard(cardAccessibility, "Accessibility", "UI event capture")
        setupCard(cardNotification, "Notifications", "Message listener")
        setupCard(cardRoot, "Root Access", "Shell executor")
        setupCard(cardMcp, "MCP Server", "Semantic tools")

        btnToggleRuntime.setOnClickListener { toggleRuntime() }
        btnOpenSettings.setOnClickListener {
            startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS))
        }

        appendLog("Runtime initialised")
        appendLog("Device: ${Build.MODEL} (API ${Build.VERSION.SDK_INT})")
    }

    override fun onResume() {
        super.onResume()
        val filter = IntentFilter().apply {
            addAction(MainActivity.ACTION_RUNTIME_STARTED)
            addAction(MainActivity.ACTION_RUNTIME_STOPPED)
            addAction(MainActivity.ACTION_EVENT_LOG)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requireContext().registerReceiver(eventReceiver, filter, Context.RECEIVER_NOT_EXPORTED)
        } else {
            @Suppress("UnspecifiedRegisterReceiverFlag")
            requireContext().registerReceiver(eventReceiver, filter)
        }
        handler.post(tickRunnable)
    }

    override fun onPause() {
        super.onPause()
        requireContext().unregisterReceiver(eventReceiver)
        handler.removeCallbacks(tickRunnable)
    }

    // -------------------------------------------------------------------------

    private fun toggleRuntime() {
        if (runtimeRunning) {
            requireContext().stopService(Intent(requireContext(), AgentRuntimeService::class.java))
        } else {
            requireContext().startForegroundService(Intent(requireContext(), AgentRuntimeService::class.java))
        }
    }

    private fun onRuntimeStarted() {
        runtimeRunning = true
        startTime = System.currentTimeMillis()
        tvRuntimeStatus.text = "Running"
        tvRuntimeStatus.setTextColor(0xFF55FF7A.toInt())
        btnToggleRuntime.text = "Stop"
        appendLog("Runtime service started")
    }

    private fun onRuntimeStopped() {
        runtimeRunning = false
        tvRuntimeStatus.text = "Stopped"
        tvRuntimeStatus.setTextColor(0xFFFF5555.toInt())
        btnToggleRuntime.text = "Start"
        appendLog("Runtime service stopped")
    }

    private fun refreshStatus() {
        val elapsedSec = (System.currentTimeMillis() - startTime) / 1000
        val h = elapsedSec / 3600
        val m = (elapsedSec % 3600) / 60
        val s = elapsedSec % 60
        tvUptime.text = if (runtimeRunning) "Uptime  %02d:%02d:%02d".format(h, m, s)
                        else "Last run: —"

        val accessEnabled = isAccessibilityServiceEnabled()
        updateCard(cardAccessibility, accessEnabled, if (accessEnabled) "Active" else "Disabled")

        val notifEnabled = isNotificationListenerEnabled()
        updateCard(cardNotification, notifEnabled, if (notifEnabled) "Active" else "Disabled")

        val rootAvail = isRootAvailable()
        updateCard(cardRoot, rootAvail, if (rootAvail) "Available" else "Not found")

        updateCard(cardMcp, runtimeRunning, if (runtimeRunning) "Listening :8765" else "Stopped")
    }

    private fun appendLog(msg: String) {
        val ts = SimpleDateFormat("HH:mm:ss", Locale.US).format(Date())
        logLines.addFirst("$ts  $msg")
        if (logLines.size > MAX_LOG_LINES) logLines.removeLast()
        tvEventLog.text = logLines.joinToString("\n")
    }

    // -------------------------------------------------------------------------

    private fun setupCard(card: CardView, title: String, subtitle: String) {
        card.findViewById<TextView>(R.id.tvCardTitle).text = title
        card.findViewById<TextView>(R.id.tvCardStatus).text = subtitle
    }

    private fun updateCard(card: CardView, active: Boolean, statusText: String) {
        val dot = card.findViewById<View>(R.id.statusDot)
        val tv = card.findViewById<TextView>(R.id.tvCardStatus)
        dot.backgroundTintList = android.content.res.ColorStateList.valueOf(
            if (active) 0xFF55FF7A.toInt() else 0xFFFF5555.toInt()
        )
        tv.text = statusText
        tv.setTextColor(if (active) 0xFF55FF7A.toInt() else 0xFF888888.toInt())
    }

    // -------------------------------------------------------------------------

    private fun isAccessibilityServiceEnabled(): Boolean {
        val am = requireContext().getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager
        val enabledServices = am.getEnabledAccessibilityServiceList(
            AccessibilityServiceInfo.FEEDBACK_ALL_MASK
        )
        val target = ComponentName(requireContext(), "ai.lemon.phoneuse.service.AgentAccessibilityService")
        return enabledServices.any {
            it.resolveInfo.serviceInfo.packageName == target.packageName &&
            it.resolveInfo.serviceInfo.name == target.className
        }
    }

    private fun isNotificationListenerEnabled(): Boolean {
        val flat = Settings.Secure.getString(requireContext().contentResolver, "enabled_notification_listeners")
            ?: return false
        return flat.contains(requireContext().packageName)
    }

    private fun isRootAvailable(): Boolean {
        return try {
            listOf("/sbin/su", "/system/bin/su", "/system/xbin/su",
                   "/data/local/xbin/su", "/data/local/bin/su", "/data/local/su")
                .any { File(it).exists() }
        } catch (_: Exception) { false }
    }

    companion object {
        private const val TICK_MS = 1_000L
        private const val MAX_LOG_LINES = 8
    }
}