xiongzhu 1 năm trước cách đây
mục cha
commit
9a2045a6bf

+ 8 - 0
app/build.gradle

@@ -35,6 +35,9 @@ android {
                         "$projectDir/schemas"
             }
         }
+        ndk {
+            abiFilters 'arm64-v8a', 'armeabi-v7a', 'x86', 'x86_64'
+        }
     }
 
     signingConfigs {
@@ -66,6 +69,11 @@ android {
     kapt {
         correctErrorTypes = true
     }
+    packagingOptions {
+        jniLibs {
+            useLegacyPackaging = true
+        }
+    }
 }
 configurations {
     configureEach {

+ 1 - 0
app/src/main/AndroidManifest.xml

@@ -31,6 +31,7 @@
         android:name="android.permission.PACKAGE_USAGE_STATS"
         tools:ignore="ProtectedPermissions" />
     <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
+    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
 
 
     <queries>

+ 47 - 13
app/src/main/java/com/example/modifier/MainActivity.kt

@@ -3,10 +3,12 @@ package com.example.modifier
 import android.content.Context
 import android.content.DialogInterface
 import android.content.Intent
+import android.net.Uri
 import android.os.Bundle
 import android.provider.Settings
 import android.util.Log
 import androidx.activity.enableEdgeToEdge
+import androidx.activity.result.contract.ActivityResultContracts
 import androidx.appcompat.app.AppCompatActivity
 import androidx.navigation.fragment.NavHostFragment
 import androidx.navigation.ui.NavigationUI.setupWithNavController
@@ -26,6 +28,10 @@ import kotlinx.coroutines.withContext
 class MainActivity : AppCompatActivity() {
     private lateinit var mBinding: ActivityMainBinding
 
+    var r = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
+        requestSystemAlertWindowPermission()
+    }
+
     override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
         enableEdgeToEdge()
@@ -51,23 +57,51 @@ class MainActivity : AppCompatActivity() {
                     return@launch
                 }
 
+                //request system_alert permission
                 withContext(Dispatchers.Main) {
-                    MaterialAlertDialogBuilder(this@MainActivity)
-                        .setTitle("Access Required")
-                        .setMessage("Enable Accessibility Service")
-                        .setNegativeButton("Exit") { _: DialogInterface?, _: Int ->
-                            System.exit(0)
-                        }
-                        .setPositiveButton("Open Settings") { _: DialogInterface?, _: Int ->
-                            val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
-                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
-                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
-                            startActivity(intent)
-                        }
-                        .show()
+                    requestAccessibilityPermission()
                 }
             }
             Log.i("getIPAddress", getIPAddress().joinToString())
         }
     }
+
+    private fun requestSystemAlertWindowPermission(): Boolean {
+        if (!Settings.canDrawOverlays(this)) {
+            MaterialAlertDialogBuilder(this)
+                .setTitle("Operation Needed")
+                .setMessage("Enable System Alert Window Permission")
+                .setCancelable(false)
+                .setPositiveButton("OK") { _: DialogInterface?, _: Int ->
+                    val intent = Intent(
+                        Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
+                        Uri.parse("package:$packageName")
+                    )
+                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
+                    r.launch(intent)
+                }
+                .show()
+            return false
+        }
+        return true
+    }
+
+    private fun requestAccessibilityPermission(): Boolean {
+        if (ModifierService.instance == null) {
+            MaterialAlertDialogBuilder(this@MainActivity)
+                .setTitle("Operation Needed")
+                .setMessage("Enable Accessibility Service")
+                .setCancelable(false)
+                .setPositiveButton("Open Settings") { _: DialogInterface?, _: Int ->
+                    val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
+                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
+                    r.launch(intent)
+                }
+                .show()
+            return false
+        }
+        return true
+    }
 }

+ 6 - 0
app/src/main/java/com/example/modifier/repo/AppPrefsRepo.kt

@@ -144,4 +144,10 @@ class AppPrefsRepo private constructor(private val context: Context) {
             preferences[PreferencesKeys.STORE_NUM] = storeNum
         }
     }
+
+    suspend fun updateAdbPaired(b: Boolean) {
+        context.appPreferencesDataStore.edit { preferences ->
+            preferences[PreferencesKeys.ADB_PAIRED] = b
+        }
+    }
 }

+ 124 - 82
app/src/main/java/com/example/modifier/service/ModifierService.kt

@@ -3,8 +3,11 @@ package com.example.modifier.service
 import android.accessibilityservice.AccessibilityService
 import android.annotation.SuppressLint
 import android.content.Context
+import android.content.Intent
 import android.graphics.PixelFormat
+import android.net.Uri
 import android.os.Build
+import android.provider.Settings
 import android.util.DisplayMetrics
 import android.util.Log
 import android.view.Gravity
@@ -34,7 +37,6 @@ import com.example.modifier.repo.AppStateRepo
 import com.example.modifier.repo.BackupRepository
 import com.example.modifier.repo.GmsgStateRepo
 import com.example.modifier.repo.SpoofedSimInfoRepo
-import com.example.modifier.service.TaskRunner.Companion
 import com.example.modifier.utils.checkPif
 import com.example.modifier.utils.clearConv
 import com.example.modifier.utils.findFirstByDesc
@@ -44,7 +46,6 @@ import com.example.modifier.utils.killPhoneProcess
 import com.example.modifier.utils.optimize
 import com.example.modifier.utils.restartSelf
 import com.example.modifier.utils.setBatteryLevel
-import com.example.modifier.utils.smsIntent
 import com.example.modifier.utils.syncTime
 import com.google.android.material.color.DynamicColors
 import kotlinx.coroutines.CoroutineScope
@@ -81,11 +82,21 @@ class ModifierService : AccessibilityService() {
     private val screenController by lazy { ScreenController(this, screenInspector) }
     private val spoofedSimInfoRepo = SpoofedSimInfoRepo.instance
     private val backupRepository by lazy { BackupRepository(this, backupItemDao) }
+    private val adb by lazy { ADB.getInstance(applicationContext) }
     private lateinit var socketClient: SocketClient
     lateinit var taskRunner: TaskRunner
     private lateinit var uiContext: Context
 
-    override fun onAccessibilityEvent(event: AccessibilityEvent) {}
+    override fun onAccessibilityEvent(event: AccessibilityEvent) {
+//        Log.w(TAG, "AccessibilityEvent: type=${event.eventType} text=${event.text}")
+        if (event.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
+            if (event.text.any { it.contains("允许 USB 调试吗?") || it.contains("Allow USB debugging?") }) {
+                CoroutineScope(Dispatchers.IO).launch {
+                    screenController.allowDebugging()
+                }
+            }
+        }
+    }
 
     override fun onInterrupt() {
         Log.e(TAG, "onInterrupt")
@@ -95,78 +106,7 @@ class ModifierService : AccessibilityService() {
     @SuppressLint("ClickableViewAccessibility")
     override fun onServiceConnected() {
         super.onServiceConnected()
-        Log.i(TAG, "onServiceConnected")
-        instance = this
-
-        val displayMetrics = DisplayMetrics()
-        val windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
-        windowManager.defaultDisplay.getMetrics(displayMetrics)
-        val height = displayMetrics.heightPixels
-        val width = displayMetrics.widthPixels
-
-        val mLayout = FrameLayout(this)
-        val layoutParams = WindowManager.LayoutParams()
-        layoutParams.type = WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY
-        layoutParams.format = PixelFormat.TRANSLUCENT
-        layoutParams.flags = layoutParams.flags or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
-        layoutParams.flags = layoutParams.flags or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
-        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT
-        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT
-        layoutParams.x = 0
-        layoutParams.y = 800
-        layoutParams.gravity = Gravity.START or Gravity.TOP
-
-        uiContext = DynamicColors.wrapContextIfAvailable(applicationContext, R.style.AppTheme)
-        val inflater = LayoutInflater.from(uiContext)
-        binding = FloatingWindowBinding.inflate(inflater, mLayout, true)
-        binding.tvVersion.text = "v${BuildConfig.VERSION_CODE}"
-        windowManager.addView(mLayout, layoutParams)
-
-
-        var maxX = 0
-        var maxY = 0
-        binding.root.measure(View.MeasureSpec.EXACTLY, View.MeasureSpec.EXACTLY)
-        binding.root.post {
-            maxX = width - binding.root.measuredWidth
-            maxY = height - binding.root.measuredHeight
-            layoutParams.x = maxX
-            windowManager.updateViewLayout(mLayout, layoutParams)
-        }
 
-        val downX = AtomicReference(0f)
-        val downY = AtomicReference(0f)
-        val downParamX = AtomicReference(0)
-        val downParamY = AtomicReference(0)
-
-        val touchListener = OnTouchListener { v, event ->
-            when (event.action) {
-                MotionEvent.ACTION_DOWN -> {
-                    downX.set(event.rawX)
-                    downY.set(event.rawY)
-                    downParamX.set(layoutParams.x)
-                    downParamY.set(layoutParams.y)
-                }
-
-                MotionEvent.ACTION_MOVE -> {
-                    layoutParams.x = min(
-                        max((downParamX.get() + (event.rawX - downX.get())).toDouble(), 0.0),
-                        maxX.toDouble()
-                    )
-                        .toInt()
-                    layoutParams.y = min(
-                        max((downParamY.get() + (event.rawY - downY.get())).toDouble(), 0.0),
-                        maxY.toDouble()
-                    )
-                        .toInt()
-                    windowManager.updateViewLayout(mLayout, layoutParams)
-                }
-
-                MotionEvent.ACTION_UP -> {
-                    return@OnTouchListener event.eventTime - event.downTime >= 200
-                }
-            }
-            false
-        }
         CoroutineScope(Dispatchers.IO).launch {
             taskRunner = TaskRunner(
                 this@ModifierService,
@@ -251,7 +191,6 @@ class ModifierService : AccessibilityService() {
                     }
                 }
             }
-
             launch {
                 appPrefsRepo.appPrefs.collect {
                     withContext(Dispatchers.Main) {
@@ -282,20 +221,15 @@ class ModifierService : AccessibilityService() {
 
             appStateRepo.updateRuntimeFlags(preparing = true)
             val hasRoot = run checkRoot@{
-                repeat(3) {
+                repeat(5) {
                     if (hasRootAccess()) {
                         return@checkRoot true
                     }
-                    delay(1000)
+                    delay(500)
                 }
                 false
             }
             if (!hasRoot) {
-                if (appPrefsRepo.appPrefs.value.adbPaired) {
-                    ADB.getInstance(applicationContext).initServer()
-                } else {
-                    screenController.adbPair()
-                }
             }
             if (isRebooted()) {
                 delay(2.minutes)
@@ -327,6 +261,79 @@ class ModifierService : AccessibilityService() {
                 }, 0, 5.minutes.inWholeMilliseconds)
             }
         }
+
+        instance = this
+
+        val displayMetrics = DisplayMetrics()
+        val windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
+        windowManager.defaultDisplay.getMetrics(displayMetrics)
+        val height = displayMetrics.heightPixels
+        val width = displayMetrics.widthPixels
+
+        val mLayout = FrameLayout(this)
+        val layoutParams = WindowManager.LayoutParams()
+        layoutParams.type = WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY
+        layoutParams.format = PixelFormat.TRANSLUCENT
+        layoutParams.flags = layoutParams.flags or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
+        layoutParams.flags = layoutParams.flags or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
+        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT
+        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT
+        layoutParams.x = 0
+        layoutParams.y = 800
+        layoutParams.gravity = Gravity.START or Gravity.TOP
+
+        uiContext = DynamicColors.wrapContextIfAvailable(applicationContext, R.style.AppTheme)
+        val inflater = LayoutInflater.from(uiContext)
+        binding = FloatingWindowBinding.inflate(inflater, mLayout, true)
+        binding.tvVersion.text = "v${BuildConfig.VERSION_CODE}"
+        windowManager.addView(mLayout, layoutParams)
+
+
+        var maxX = 0
+        var maxY = 0
+        binding.root.measure(View.MeasureSpec.EXACTLY, View.MeasureSpec.EXACTLY)
+        binding.root.post {
+            maxX = width - binding.root.measuredWidth
+            maxY = height - binding.root.measuredHeight
+            layoutParams.x = maxX
+            windowManager.updateViewLayout(mLayout, layoutParams)
+        }
+
+        val downX = AtomicReference(0f)
+        val downY = AtomicReference(0f)
+        val downParamX = AtomicReference(0)
+        val downParamY = AtomicReference(0)
+
+        val touchListener = OnTouchListener { v, event ->
+            when (event.action) {
+                MotionEvent.ACTION_DOWN -> {
+                    downX.set(event.rawX)
+                    downY.set(event.rawY)
+                    downParamX.set(layoutParams.x)
+                    downParamY.set(layoutParams.y)
+                }
+
+                MotionEvent.ACTION_MOVE -> {
+                    layoutParams.x = min(
+                        max((downParamX.get() + (event.rawX - downX.get())).toDouble(), 0.0),
+                        maxX.toDouble()
+                    )
+                        .toInt()
+                    layoutParams.y = min(
+                        max((downParamY.get() + (event.rawY - downY.get())).toDouble(), 0.0),
+                        maxY.toDouble()
+                    )
+                        .toInt()
+                    windowManager.updateViewLayout(mLayout, layoutParams)
+                }
+
+                MotionEvent.ACTION_UP -> {
+                    return@OnTouchListener event.eventTime - event.downTime >= 200
+                }
+            }
+            false
+        }
+
         binding.swSend.setOnTouchListener(touchListener)
         binding.swSend.setOnCheckedChangeListener { buttonView: CompoundButton?, isChecked: Boolean ->
             CoroutineScope(Dispatchers.IO).launch {
@@ -376,6 +383,41 @@ class ModifierService : AccessibilityService() {
         popup.setOnMenuItemClickListener { item ->
             CoroutineScope(Dispatchers.IO).launch {
                 when (item.itemId) {
+                    R.id.adb -> {
+                        if (adb.connect()) {
+                            Log.i(TAG, "adb connected")
+                            adb.adb(
+                                listOf(
+                                    "shell",
+                                    "am",
+                                    "start",
+                                    "com.google.android.apps.messaging"
+                                )
+                            )
+                            delay(2000)
+                            adb.adb(
+                                listOf(
+                                    "shell",
+                                    "am",
+                                    "force-stop",
+                                    "com.google.android.apps.messaging"
+                                )
+                            )
+                        } else {
+                            Log.i(TAG, "adb not connected")
+                        }
+                    }
+
+                    R.id.settings -> {
+                        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
+                        val uri: Uri =
+                            Uri.fromParts("package", "com.google.android.apps.messaging", null)
+                        intent.setData(uri)
+                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
+                        startActivity(intent)
+                    }
+
                     R.id.inspect -> {
                         delay(1500)
                         screenInspector.traverseNode(TraverseResult(), true)

+ 62 - 38
app/src/main/java/com/example/modifier/service/ScreenController.kt

@@ -14,9 +14,7 @@ import com.example.modifier.constants.CMD_BACK
 import com.example.modifier.constants.CMD_RCS_SETTINGS_ACTIVITY
 import com.example.modifier.utils.currentActivity
 import com.example.modifier.utils.findAllScrollable
-import com.example.modifier.utils.findFirstByDesc
 import com.example.modifier.utils.findFirstByIdAndText
-import com.example.modifier.utils.findFirstScrollable
 import com.example.modifier.utils.shellRun
 import kotlinx.coroutines.delay
 import kotlinx.coroutines.withTimeoutOrNull
@@ -103,56 +101,72 @@ class ScreenController(val context: AccessibilityService, private val inspector:
         return success
     }
 
-    suspend fun adbPair(): Pair<String, String>? {
+    suspend fun enableAdbWifi(): Boolean {
         val i = Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)
         i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
         i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
         context.startActivity(i)
         delay(500)
-        withTimeoutOrNull(10000) {
-            while (true) {
-                val node = context.rootInActiveWindow.findFirstByIdAndText(
+        var node: AccessibilityNodeInfo? = withTimeoutOrNull(10000) {
+            repeat(999) {
+                var n = context.rootInActiveWindow.findFirstByIdAndText(
                     "android:id/title",
-                    "Wireless debugging"
+                    "Wireless debugging", "无线调试"
                 )
-                if (node != null) {
-                    Log.i(TAG, "found wireless debugging")
-                    delay(500)
-                    tapNode(node)
-                    delay(1000)
-                 return@withTimeoutOrNull   context.rootInActiveWindow.findFirstByIdAndText(
-                        "android:id/title",
-                        "Pair device with pairing code"
-                    )?.let {
-                        Log.i(TAG, "found pair device with pairing code")
-                        it.parent.parent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
-
-                        delay(1000)
-                        val code = context.rootInActiveWindow.findAccessibilityNodeInfosByViewId(
-                            "com.android.settings:id/pairing_code"
-                        ).firstOrNull()?.text?.toString()
-                        val ip = context.rootInActiveWindow.findAccessibilityNodeInfosByViewId(
-                            "com.android.settings:id/ip_addr"
-                        ).firstOrNull()?.text?.toString()
-                        Log.i(TAG, "pairing code: $code, ip: $ip")
-
-                        if (code != null && ip != null) {
-                            return@let Pair(code, ip)
-                        } else {
-
-                        }
-                    }
-                    return@withTimeoutOrNull
+                if (n != null) {
+                    return@withTimeoutOrNull n
                 }
                 context.rootInActiveWindow.findAllScrollable().forEach {
-                    Log.i(TAG, "scrolling ${it.viewIdResourceName}")
-                    it.performAction(AccessibilityNodeInfo.ACTION_FOCUS)
                     it.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)
                 }
                 delay(500)
             }
-            null
+            return@withTimeoutOrNull null
+        }
+        if (node == null) {
+            Log.e(TAG, "not found wireless debugging menu")
+            return false
+        }
+        Log.i(TAG, "found wireless debugging menu")
+        tapNode(node)
+        delay(1000)
+
+        val switchParent = context.rootInActiveWindow
+            .findAccessibilityNodeInfosByViewId("com.android.settings:id/switch_bar")
+            .firstOrNull()
+        if (switchParent == null) {
+            Log.e(TAG, "not found wireless debugging switch")
+            return false
+        }
+
+        val switch = switchParent
+            .findAccessibilityNodeInfosByViewId("android:id/switch_widget").firstOrNull()
+        if (switch == null) {
+            Log.e(TAG, "not found wireless debugging switch")
+            return false
         }
+
+        if (switch.isChecked) {
+            Log.i(TAG, "wireless debugging is already enabled")
+        } else {
+            Log.i(TAG, "wireless debugging is disabled")
+            switchParent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
+            delay(1000)
+        }
+
+        node = context.rootInActiveWindow.findFirstByIdAndText(
+            "android:id/title",
+            "Pair device with pairing code", "使用配对码配对设备"
+        )
+        if (node == null) {
+            Log.e(TAG, "not found pair device with pairing code")
+            return false
+        }
+        Log.i(TAG, "found pair device with pairing code")
+        node.parent.parent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
+
+        delay(1000)
+        context.rootInActiveWindow.findFirstByIdAndText("android:id/title","IP address & Port")
     }
 
     fun tapNode(node: AccessibilityNodeInfo) {
@@ -166,4 +180,14 @@ class ScreenController(val context: AccessibilityService, private val inspector:
             ).build(), null, null
         )
     }
+
+    suspend fun allowDebugging() {
+        delay(500)
+        context.rootInActiveWindow.findAccessibilityNodeInfosByViewId("android:id/alwaysUse")
+            .find { !it.isChecked }?.performAction(AccessibilityNodeInfo.ACTION_CLICK)
+        delay(500)
+        context.rootInActiveWindow.findAccessibilityNodeInfosByViewId("android:id/button1")
+            .firstOrNull()?.performAction(AccessibilityNodeInfo.ACTION_CLICK)
+        delay(500)
+    }
 }

+ 1 - 1
app/src/main/java/com/example/modifier/service/ScreenInspector.kt

@@ -32,7 +32,7 @@ class ScreenInspector(val context: AccessibilityService) {
         val desc = node.contentDescription?.toString() ?: ""
 
         if (log) {
-            Log.d(TAG, "Node: class=$className, text=$text, desc=$desc, name=$name, id=$id")
+            Log.d(TAG, "Node: class=$className, text=$text, desc=$desc, name=$name, id=$id, checkable=${node.isCheckable}, checked=${node.isChecked}")
         }
 
         if ("Compose:Draft:Send" == name) {

+ 42 - 193
app/src/main/java/com/example/modifier/utils/ADB.kt

@@ -1,20 +1,21 @@
 package com.draco.ladb.utils
 
-import android.Manifest
 import android.annotation.SuppressLint
 import android.content.Context
-import android.content.pm.PackageManager
-import android.os.Build
 import android.provider.Settings
+import android.util.Log
 import androidx.lifecycle.LiveData
 import androidx.lifecycle.MutableLiveData
-import com.example.modifier.BuildConfig
-import java.io.File
-import java.io.PrintStream
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
 import java.util.concurrent.TimeUnit
 
 class ADB(private val context: Context) {
     companion object {
+        const val TAG = "ADB"
         const val MAX_OUTPUT_BUFFER_SIZE = 1024 * 16
         const val OUTPUT_BUFFER_DELAY_MS = 100L
 
@@ -44,124 +45,6 @@ class ADB(private val context: Context) {
     private val _closed = MutableLiveData(false)
     val closed: LiveData<Boolean> = _closed
 
-    /**
-     * Where shell output is stored
-     */
-    val outputBufferFile: File = File.createTempFile("buffer", ".txt").also {
-        it.deleteOnExit()
-    }
-
-    /**
-     * Single shell instance where we can pipe commands to
-     */
-    private var shellProcess: Process? = null
-
-    /**
-     * Returns the user buffer size if valid, else the default
-     */
-    fun getOutputBufferSize(): Int {
-        return 16384
-    }
-
-    /**
-     * Start the ADB server
-     */
-    fun initServer(): Boolean {
-        if (_started.value == true || tryingToPair)
-            return true
-
-        tryingToPair = true
-
-        val autoShell = true
-
-        val secureSettingsGranted =
-            context.checkSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS) == PackageManager.PERMISSION_GRANTED
-
-        if (autoShell) {
-            /* Only do wireless debugging steps on compatible versions */
-            if (secureSettingsGranted) {
-                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !isWirelessDebuggingEnabled()) {
-                    Settings.Global.putInt(
-                        context.contentResolver,
-                        "adb_wifi_enabled",
-                        1
-                    )
-
-                    Thread.sleep(2_000)
-                } else if (!isUSBDebuggingEnabled()) {
-                    Settings.Global.putInt(
-                        context.contentResolver,
-                        Settings.Global.ADB_ENABLED,
-                        1
-                    )
-
-                    Thread.sleep(2_000)
-                }
-            }
-
-            /* Check again... */
-            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !isWirelessDebuggingEnabled()) {
-                debug("Wireless debugging is not enabled!")
-                debug("Settings -> Developer options -> Wireless debugging")
-                debug("Waiting for wireless debugging...")
-
-                while (!isWirelessDebuggingEnabled()) {
-                    Thread.sleep(1_000)
-                }
-            } else if (!isUSBDebuggingEnabled()) {
-                debug("USB debugging is not enabled!")
-                debug("Settings -> Developer options -> USB debugging")
-                debug("Waiting for USB debugging...")
-
-                while (!isUSBDebuggingEnabled()) {
-                    Thread.sleep(1_000)
-                }
-            }
-
-            adb(false, listOf("start-server")).waitFor()
-            debug("Waiting for device to connect...")
-            debug("This may take a minute")
-            val waitProcess = adb(false, listOf("wait-for-device")).waitFor(1, TimeUnit.MINUTES)
-            if (!waitProcess) {
-                debug("Your device didn't connect to LADB")
-                debug("If a reboot doesn't work, please contact support")
-
-                tryingToPair = false
-                return false
-            }
-        }
-
-        shellProcess = if (autoShell) {
-            val argList = if (Build.SUPPORTED_ABIS[0] == "arm64-v8a")
-                listOf("-t", "1", "shell")
-            else
-                listOf("shell")
-
-            adb(true, argList)
-        } else {
-            shell(true, listOf("sh", "-l"))
-        }
-
-        sendToShellProcess("alias adb=\"$adbPath\"")
-
-        if (!secureSettingsGranted) {
-            sendToShellProcess("pm grant ${BuildConfig.APPLICATION_ID} android.permission.WRITE_SECURE_SETTINGS &> /dev/null")
-        }
-
-        if (autoShell)
-            sendToShellProcess("echo 'Entered adb shell'")
-        else
-            sendToShellProcess("echo 'Entered non-adb shell'")
-
-        val startupCommand = "echo 'Success! ※\\(^o^)/※'"
-        if (startupCommand.isNotEmpty())
-            sendToShellProcess(startupCommand)
-
-        _started.postValue(true)
-        tryingToPair = false
-
-        return true
-    }
 
     private fun isWirelessDebuggingEnabled() =
         Settings.Global.getInt(context.contentResolver, "adb_wifi_enabled", 0) == 1
@@ -169,96 +52,62 @@ class ADB(private val context: Context) {
     private fun isUSBDebuggingEnabled() =
         Settings.Global.getInt(context.contentResolver, Settings.Global.ADB_ENABLED, 0) == 1
 
-    /**
-     * Wait restart the shell once it dies
-     */
-    fun waitForDeathAndReset() {
-        while (true) {
-            shellProcess?.waitFor()
-            _started.postValue(false)
-            debug("Shell is dead, resetting")
-            adb(false, listOf("kill-server")).waitFor()
-            Thread.sleep(3_000)
-            initServer()
-        }
-    }
-
-    /**
-     * Ask the device to pair on Android 11+ devices
-     */
-    fun pair(port: String, pairingCode: String): Boolean {
-        val pairShell = adb(false, listOf("pair", "localhost:$port"))
-
-        /* Sleep to allow shell to catch up */
-        Thread.sleep(5000)
-
-        /* Pipe pairing code */
-        PrintStream(pairShell.outputStream).apply {
-            println(pairingCode)
-            flush()
-        }
 
-        /* Continue once finished pairing (or 10s elapses) */
-        pairShell.waitFor(10, TimeUnit.SECONDS)
-        pairShell.destroyForcibly().waitFor()
+    suspend fun connect(): Boolean {
+//        adb(listOf("connect", "localhost:5555"))
+        delay(5000)
 
-        val killShell = adb(false, listOf("kill-server"))
-        killShell.waitFor(3, TimeUnit.SECONDS)
-        killShell.destroyForcibly()
+        adb(listOf("devices"))
 
-        return pairShell.exitValue() == 0
+        val shell2 = adb(listOf("shell", "ls"))
+        return shell2.exitValue() == 0
     }
 
     /**
      * Send a raw ADB command
      */
-    private fun adb(redirect: Boolean, command: List<String>): Process {
+    suspend fun adb(command: List<String>): Process {
         val commandList = command.toMutableList().also {
             it.add(0, adbPath)
         }
-        return shell(redirect, commandList)
+        return shell(commandList)
     }
 
     /**
      * Send a raw shell command
      */
-    private fun shell(redirect: Boolean, command: List<String>): Process {
-        val processBuilder = ProcessBuilder(command)
-            .directory(context.filesDir)
-            .apply {
-                if (redirect) {
+    private suspend fun shell(command: List<String>): Process {
+        val process = withContext(Dispatchers.IO) {
+            ProcessBuilder(command)
+                .directory(context.filesDir)
+                .apply {
                     redirectErrorStream(true)
-                    redirectOutput(outputBufferFile)
+                    environment().apply {
+                        put("HOME", context.filesDir.path)
+                        put("TMPDIR", context.cacheDir.path)
+                    }
                 }
-
-                environment().apply {
-                    put("HOME", context.filesDir.path)
-                    put("TMPDIR", context.cacheDir.path)
+                .start()
+        }
+        coroutineScope {
+            launch {
+                process.inputStream.bufferedReader().useLines { line ->
+                    line.forEach {
+                        Log.i(TAG, "ADB out: $it")
+                    }
+                }
+            }
+            launch {
+                process.errorStream.bufferedReader().useLines { line ->
+                    line.forEach {
+                        Log.e(TAG, "ADB err: $it")
+                    }
                 }
             }
-
-        return processBuilder.start()!!
-    }
-
-    /**
-     * Send commands directly to the shell process
-     */
-    fun sendToShellProcess(msg: String) {
-        if (shellProcess == null || shellProcess?.outputStream == null)
-            return
-        PrintStream(shellProcess!!.outputStream!!).apply {
-            println(msg)
-            flush()
         }
-    }
-
-    /**
-     * Write a debug message to the user
-     */
-    fun debug(msg: String) {
-        synchronized(outputBufferFile) {
-            if (outputBufferFile.exists())
-                outputBufferFile.appendText("* $msg" + System.lineSeparator())
+        withContext(Dispatchers.IO) {
+            process.waitFor()
         }
+        return process
     }
 }

+ 6 - 3
app/src/main/java/com/example/modifier/utils/AccessibilityNodeInfo.kt

@@ -24,18 +24,21 @@ fun AccessibilityNodeInfo?.findFirstByDesc(desc: String): AccessibilityNodeInfo?
     return null
 }
 
-fun AccessibilityNodeInfo?.findFirstByIdAndText(id: String, text: String): AccessibilityNodeInfo? {
+fun AccessibilityNodeInfo?.findFirstByIdAndText(
+    id: String,
+    vararg text: String
+): AccessibilityNodeInfo? {
     if (this == null) {
         return null
     }
     if (this.viewIdResourceName?.toString()?.lowercase()?.contains(id.lowercase()) == true
-        && this.text?.toString()?.lowercase()?.contains(text.lowercase()) == true
+        && text.any { this.text?.toString()?.lowercase()?.contains(it.lowercase()) == true }
     ) {
         return this
     }
     for (i in 0 until this.childCount) {
         val child = this.getChild(i)
-        val result = child.findFirstByIdAndText(id, text)
+        val result = child.findFirstByIdAndText(id, *text)
         if (result != null) {
             return result
         }

+ 26 - 21
app/src/main/java/com/example/modifier/utils/Root.kt

@@ -12,34 +12,39 @@ suspend fun shellRun(vararg commands: String): Pair<String, String> {
     var output = ""
     var error = ""
     Log.i(shellTag, "shellRun: \t${commands.joinToString("\n\t\t\t")}")
-    withContext(Dispatchers.IO) {
-        val p = ProcessBuilder("su", "-M").start()
-        p.outputStream.bufferedWriter().use { writer ->
-            commands.forEach { command ->
-                writer.write(command)
-                writer.newLine()
-                writer.flush()
+    runCatching {
+        withContext(Dispatchers.IO) {
+            val p = ProcessBuilder("su", "-M").start()
+            p.outputStream.bufferedWriter().use { writer ->
+                commands.forEach { command ->
+                    writer.write(command)
+                    writer.newLine()
+                    writer.flush()
+                }
             }
-        }
-        coroutineScope {
-            launch {
-                p.inputStream.bufferedReader().useLines { line ->
-                    line.forEach {
-                        output += it + "\n"
-                        Log.i(shellTag, "shellRunOut: $it")
+            coroutineScope {
+                launch {
+                    p.inputStream.bufferedReader().useLines { line ->
+                        line.forEach {
+                            output += it + "\n"
+                            Log.i(shellTag, "shellRunOut: $it")
+                        }
                     }
                 }
-            }
-            launch {
-                p.errorStream.bufferedReader().useLines { line ->
-                    line.forEach {
-                        error += it + "\n"
-                        Log.e(shellTag, "shellRunErr: $it")
+                launch {
+                    p.errorStream.bufferedReader().useLines { line ->
+                        line.forEach {
+                            error += it + "\n"
+                            Log.e(shellTag, "shellRunErr: $it")
+                        }
                     }
                 }
             }
+            p.waitFor()
         }
-        p.waitFor()
+    }.onFailure {
+        error = it.message ?: "Unknown error"
+        Log.e(shellTag, "shellRun: $error")
     }
     return Pair(output, error)
 }

+ 201 - 0
app/src/main/jniLibs/LICENSE

@@ -0,0 +1,201 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.

BIN
app/src/main/jniLibs/arm64-v8a/libadb.so


BIN
app/src/main/jniLibs/armeabi-v7a/libadb.so


BIN
app/src/main/jniLibs/x86/libadb.so


BIN
app/src/main/jniLibs/x86_64/libadb.so


+ 6 - 0
app/src/main/res/menu/more.xml

@@ -1,5 +1,11 @@
 <?xml version="1.0" encoding="utf-8"?>
 <menu xmlns:android="http://schemas.android.com/apk/res/android">
+    <item
+        android:id="@+id/adb"
+        android:title="ADB" />
+    <item
+        android:id="@+id/settings"
+        android:title="settings" />
     <item
         android:id="@+id/inspect"
         android:title="Inspect"