فهرست منبع

feat(module): Auto-start emulator feature from SRC sync

huangrunheng 1 سال پیش
والد
کامیت
868459cabb

+ 57 - 1
deploy/utils.py

@@ -1,7 +1,8 @@
 # copy from alas https://github.com/LmeSzinc/AzurLaneAutoScript
 import os
 import re
-from typing import Callable, Generic, TypeVar
+from dataclasses import dataclass
+from typing import Callable, Generic, Iterable, TypeVar
 
 T = TypeVar("T")
 
@@ -112,3 +113,58 @@ def poor_yaml_write(data, file, template_file=DEPLOY_TEMPLATE):
 
     with open(file, 'w', encoding='utf-8', newline='') as f:
         f.write(text)
+
+@dataclass
+class DataProcessInfo:
+    proc: object  # psutil.Process or psutil._pswindows.Process
+    pid: int
+
+    @cached_property
+    def name(self):
+        try:
+            name = self.proc.name()
+        except:
+            name = ''
+        return name
+
+    @cached_property
+    def cmdline(self):
+        try:
+            cmdline = self.proc.cmdline()
+        except:
+            # psutil.AccessDenied
+            # # NoSuchProcess: process no longer exists (pid=xxx)
+            cmdline = []
+        cmdline = ' '.join(cmdline).replace(r'\\', '/').replace('\\', '/')
+        return cmdline
+
+    def __str__(self):
+        # Don't print `proc`, it will take some time to get process properties
+        return f'DataProcessInfo(name="{self.name}", pid={self.pid}, cmdline="{self.cmdline}")'
+
+    __repr__ = __str__
+
+
+def iter_process() -> Iterable[DataProcessInfo]:
+    try:
+        import psutil
+    except ModuleNotFoundError:
+        return
+
+    if psutil.WINDOWS:
+        # Since this is a one-time-usage, we access psutil._psplatform.Process directly
+        # to bypass the call of psutil.Process.is_running().
+        # This only costs about 0.017s.
+        for pid in psutil.pids():
+            proc = psutil._psplatform.Process(pid)
+            yield DataProcessInfo(
+                proc=proc,
+                pid=proc.pid,
+            )
+    else:
+        # This will cost about 0.45s, even `attr` is given.
+        for proc in psutil.process_iter():
+            yield DataProcessInfo(
+                proc=proc,
+                pid=proc.pid,
+            )

+ 0 - 0
module/base/__init__.py


+ 4 - 0
module/base/utils/__init__.py

@@ -0,0 +1,4 @@
+
+from .utils import *
+from .grids import *
+# from .points import *

+ 377 - 0
module/base/utils/grids.py

@@ -0,0 +1,377 @@
+import operator
+import typing as t
+
+
+class SelectedGrids:
+    def __init__(self, grids):
+        self.grids = grids
+        self.indexes: t.Dict[tuple, SelectedGrids] = {}
+
+    def __iter__(self):
+        return iter(self.grids)
+
+    def __getitem__(self, item):
+        if isinstance(item, int):
+            return self.grids[item]
+        else:
+            return SelectedGrids(self.grids[item])
+
+    def __contains__(self, item):
+        return item in self.grids
+
+    def __str__(self):
+        # return str([str(grid) for grid in self])
+        return '[' + ', '.join([str(grid) for grid in self]) + ']'
+
+    def __len__(self):
+        return len(self.grids)
+
+    def __bool__(self):
+        return self.count > 0
+
+    # def __getattr__(self, item):
+    #     return [grid.__getattribute__(item) for grid in self.grids]
+
+    @property
+    def location(self):
+        """
+        Returns:
+            list[tuple]:
+        """
+        return [grid.location for grid in self.grids]
+
+    @property
+    def cost(self):
+        """
+        Returns:
+            list[int]:
+        """
+        return [grid.cost for grid in self.grids]
+
+    @property
+    def weight(self):
+        """
+        Returns:
+            list[int]:
+        """
+        return [grid.weight for grid in self.grids]
+
+    @property
+    def count(self):
+        """
+        Returns:
+            int:
+        """
+        return len(self.grids)
+
+    def select(self, **kwargs):
+        """
+        Args:
+            **kwargs: Attributes of Grid.
+
+        Returns:
+            SelectedGrids:
+        """
+        def matched(obj):
+            flag = True
+            for k, v in kwargs.items():
+                obj_v = obj.__getattribute__(k)
+                if type(obj_v) != type(v) or obj_v != v:
+                    flag = False
+            return flag
+
+        return SelectedGrids([grid for grid in self.grids if matched(grid)])
+
+    def create_index(self, *attrs):
+        indexes = {}
+        # index_keys = [(grid.__getattribute__(attr) for attr in attrs) for grid in self.grids]
+        for grid in self.grids:
+            k = tuple(grid.__getattribute__(attr) for attr in attrs)
+            try:
+                indexes[k].append(grid)
+            except KeyError:
+                indexes[k] = [grid]
+
+        indexes = {k: SelectedGrids(v) for k, v in indexes.items()}
+        self.indexes = indexes
+        return indexes
+
+    def indexed_select(self, *values):
+        return self.indexes.get(values, SelectedGrids([]))
+
+    def left_join(self, right, on_attr, set_attr, default=None):
+        """
+        Args:
+            right (SelectedGrids): Right table to join
+            on_attr:
+            set_attr:
+            default:
+
+        Returns:
+            SelectedGrids:
+        """
+        right.create_index(*on_attr)
+        for grid in self:
+            attr_value = tuple([grid.__getattribute__(attr) for attr in on_attr])
+            right_grid = right.indexed_select(*attr_value).first_or_none()
+            if right_grid is not None:
+                for attr in set_attr:
+                    grid.__setattr__(attr, right_grid.__getattribute__(attr))
+            else:
+                for attr in set_attr:
+                    grid.__setattr__(attr, default)
+
+        return self
+
+    def filter(self, func):
+        """
+        Filter grids by a function.
+
+        Args:
+            func (callable): Function should receive an grid as argument, and return a bool.
+
+        Returns:
+            SelectedGrids:
+        """
+        return SelectedGrids([grid for grid in self if func(grid)])
+
+    def set(self, **kwargs):
+        """
+        Set attribute to each grid.
+
+        Args:
+            **kwargs:
+        """
+        for grid in self:
+            for key, value in kwargs.items():
+                grid.__setattr__(key, value)
+
+    def get(self, attr):
+        """
+        Get an attribute from each grid.
+
+        Args:
+            attr: Attribute name.
+
+        Returns:
+            list:
+        """
+        return [grid.__getattribute__(attr) for grid in self.grids]
+
+    def call(self, func, **kwargs):
+        """
+        Call a function in reach grid, and get results.
+
+        Args:
+            func (str): Function name to call.
+            **kwargs:
+
+        Returns:
+            list:
+        """
+        return [grid.__getattribute__(func)(**kwargs) for grid in self]
+
+    def first_or_none(self):
+        """
+        Returns:
+
+        """
+        try:
+            return self.grids[0]
+        except IndexError:
+            return None
+
+    def add(self, grids):
+        """
+        Args:
+            grids(SelectedGrids):
+
+        Returns:
+            SelectedGrids:
+        """
+        return SelectedGrids(list(set(self.grids + grids.grids)))
+
+    def add_by_eq(self, grids):
+        """
+        Another `add()` method, but de-duplicates with `__eq__` instead of `__hash__`.
+
+        Args:
+            grids(SelectedGrids):
+
+        Returns:
+            SelectedGrids:
+        """
+        new = []
+        for grid in self.grids + grids.grids:
+            if grid not in new:
+                new.append(grid)
+
+        return SelectedGrids(new)
+
+    def intersect(self, grids):
+        """
+        Args:
+            grids(SelectedGrids):
+
+        Returns:
+            SelectedGrids:
+        """
+        return SelectedGrids(list(set(self.grids).intersection(set(grids.grids))))
+
+    def intersect_by_eq(self, grids):
+        """
+        Another `intersect()` method, but de-duplicates with `__eq__` instead of `__hash__`.
+
+        Args:
+            grids(SelectedGrids):
+
+        Returns:
+            SelectedGrids:
+        """
+        new = []
+        for grid in self.grids:
+            if grid in grids.grids:
+                new.append(grid)
+
+        return SelectedGrids(new)
+
+    def delete(self, grids):
+        """
+        Args:
+            grids(SelectedGrids):
+
+        Returns:
+            SelectedGrids:
+        """
+        g = [grid for grid in self.grids if grid not in grids]
+        return SelectedGrids(g)
+
+    def sort(self, *args):
+        """
+        Args:
+            args (str): Attribute name to sort.
+
+        Returns:
+            SelectedGrids:
+        """
+        if not self:
+            return self
+        if len(args):
+            grids = sorted(self.grids, key=operator.attrgetter(*args))
+            return SelectedGrids(grids)
+        else:
+            return self
+
+    def sort_by_camera_distance(self, camera):
+        """
+        Args:
+            camera (tuple):
+
+        Returns:
+            SelectedGrids:
+        """
+        import numpy as np
+        if not self:
+            return self
+        location = np.array(self.location)
+        diff = np.sum(np.abs(location - camera), axis=1)
+        # grids = [x for _, x in sorted(zip(diff, self.grids))]
+        grids = tuple(np.array(self.grids)[np.argsort(diff)])
+        return SelectedGrids(grids)
+
+    def sort_by_clock_degree(self, center=(0, 0), start=(0, 1), clockwise=True):
+        """
+        Args:
+            center (tuple): Origin point.
+            start (tuple): Start coordinate, this point will be considered as theta=0.
+            clockwise (bool): True for clockwise, false for counterclockwise.
+
+        Returns:
+            SelectedGrids:
+        """
+        import numpy as np
+        if not self:
+            return self
+        vector = np.subtract(self.location, center)
+        theta = np.arctan2(vector[:, 1], vector[:, 0]) / np.pi * 180
+        vector = np.subtract(start, center)
+        theta = theta - np.arctan2(vector[1], vector[0]) / np.pi * 180
+        if not clockwise:
+            theta = -theta
+        theta[theta < 0] += 360
+        grids = tuple(np.array(self.grids)[np.argsort(theta)])
+        return SelectedGrids(grids)
+
+
+class RoadGrids:
+    def __init__(self, grids):
+        """
+        Args:
+            grids (list):
+        """
+        self.grids = []
+        for grid in grids:
+            if isinstance(grid, list):
+                self.grids.append(SelectedGrids(grids=grid))
+            else:
+                self.grids.append(SelectedGrids(grids=[grid]))
+
+    def __str__(self):
+        return str(' - '.join([str(grid) for grid in self.grids]))
+
+    def roadblocks(self):
+        """
+        Returns:
+            SelectedGrids:
+        """
+        grids = []
+        for block in self.grids:
+            if block.count == block.select(is_enemy=True).count:
+                grids += block.grids
+        return SelectedGrids(grids)
+
+    def potential_roadblocks(self):
+        """
+        Returns:
+            SelectedGrids:
+        """
+        grids = []
+        for block in self.grids:
+            if any([grid.is_fleet for grid in block]):
+                continue
+            if any([grid.is_cleared for grid in block]):
+                continue
+            if block.count - block.select(is_enemy=True).count == 1:
+                grids += block.select(is_enemy=True).grids
+        return SelectedGrids(grids)
+
+    def first_roadblocks(self):
+        """
+        Returns:
+            SelectedGrids:
+        """
+        grids = []
+        for block in self.grids:
+            if any([grid.is_fleet for grid in block]):
+                continue
+            if any([grid.is_cleared for grid in block]):
+                continue
+            if block.select(is_enemy=True).count >= 1:
+                grids += block.select(is_enemy=True).grids
+        return SelectedGrids(grids)
+
+    def combine(self, road):
+        """
+        Args:
+            road (RoadGrids):
+
+        Returns:
+            RoadGrids:
+        """
+        out = RoadGrids([])
+        for select_1 in self.grids:
+            for select_2 in road.grids:
+                select = select_1.add(select_2)
+                out.grids.append(select)
+
+        return out

+ 395 - 0
module/base/utils/points.py

@@ -0,0 +1,395 @@
+import numpy as np
+from scipy import optimize
+
+from .utils import area_pad
+
+
+class Points:
+    def __init__(self, points):
+        if points is None or len(points) == 0:
+            self._bool = False
+            self.points = None
+        else:
+            self._bool = True
+            self.points = np.array(points)
+            if len(self.points.shape) == 1:
+                self.points = np.array([self.points])
+            self.x, self.y = self.points.T
+
+    def __str__(self):
+        return str(self.points)
+
+    __repr__ = __str__
+
+    def __iter__(self):
+        return iter(self.points)
+
+    def __getitem__(self, item):
+        return self.points[item]
+
+    def __len__(self):
+        if self:
+            return len(self.points)
+        else:
+            return 0
+
+    def __bool__(self):
+        return self._bool
+
+    def link(self, point, is_horizontal=False):
+        if is_horizontal:
+            lines = [[y, np.pi / 2] for y in self.y]
+            return Lines(lines, is_horizontal=True)
+        else:
+            x, y = point
+            theta = -np.arctan((self.x - x) / (self.y - y))
+            rho = self.x * np.cos(theta) + self.y * np.sin(theta)
+            lines = np.array([rho, theta]).T
+            return Lines(lines, is_horizontal=False)
+
+    def mean(self):
+        if not self:
+            return None
+
+        return np.round(np.mean(self.points, axis=0)).astype(int)
+
+    def group(self, threshold=3):
+        if not self:
+            return np.array([])
+        groups = []
+        points = self.points
+        if len(points) == 1:
+            return np.array([points[0]])
+
+        while len(points):
+            p0, p1 = points[0], points[1:]
+            distance = np.sum(np.abs(p1 - p0), axis=1)
+            new = Points(np.append(p1[distance <= threshold], [p0], axis=0)).mean().tolist()
+            groups.append(new)
+            points = p1[distance > threshold]
+
+        return np.array(groups)
+
+
+class Lines:
+    MID_Y = 360
+
+    def __init__(self, lines, is_horizontal):
+        if lines is None or len(lines) == 0:
+            self._bool = False
+            self.lines = None
+        else:
+            self._bool = True
+            self.lines = np.array(lines)
+            if len(self.lines.shape) == 1:
+                self.lines = np.array([self.lines])
+            self.rho, self.theta = self.lines.T
+        self.is_horizontal = is_horizontal
+
+    def __str__(self):
+        return str(self.lines)
+
+    __repr__ = __str__
+
+    def __iter__(self):
+        return iter(self.lines)
+
+    def __getitem__(self, item):
+        return Lines(self.lines[item], is_horizontal=self.is_horizontal)
+
+    def __len__(self):
+        if self:
+            return len(self.lines)
+        else:
+            return 0
+
+    def __bool__(self):
+        return self._bool
+
+    @property
+    def sin(self):
+        return np.sin(self.theta)
+
+    @property
+    def cos(self):
+        return np.cos(self.theta)
+
+    @property
+    def mean(self):
+        if not self:
+            return None
+        if self.is_horizontal:
+            return np.mean(self.lines, axis=0)
+        else:
+            x = np.mean(self.mid)
+            theta = np.mean(self.theta)
+            rho = x * np.cos(theta) + self.MID_Y * np.sin(theta)
+            return np.array((rho, theta))
+
+    @property
+    def mid(self):
+        if not self:
+            return np.array([])
+        if self.is_horizontal:
+            return self.rho
+        else:
+            return (self.rho - self.MID_Y * self.sin) / self.cos
+
+    def get_x(self, y):
+        return (self.rho - y * self.sin) / self.cos
+
+    def get_y(self, x):
+        return (self.rho - x * self.cos) / self.sin
+
+    def add(self, other):
+        if not other:
+            return self
+        if not self:
+            return other
+        lines = np.append(self.lines, other.lines, axis=0)
+        return Lines(lines, is_horizontal=self.is_horizontal)
+
+    def move(self, x, y):
+        if not self:
+            return self
+        if self.is_horizontal:
+            self.lines[:, 0] += y
+        else:
+            self.lines[:, 0] += x * self.cos + y * self.sin
+        return Lines(self.lines, is_horizontal=self.is_horizontal)
+
+    def sort(self):
+        if not self:
+            return self
+        lines = self.lines[np.argsort(self.mid)]
+        return Lines(lines, is_horizontal=self.is_horizontal)
+
+    def group(self, threshold=3):
+        if not self:
+            return self
+        lines = self.sort()
+        prev = 0
+        regrouped = []
+        group = []
+        for mid, line in zip(lines.mid, lines.lines):
+            line = line.tolist()
+            if mid - prev > threshold:
+                if len(regrouped) == 0:
+                    if len(group) != 0:
+                        regrouped = [group]
+                else:
+                    regrouped += [group]
+                group = [line]
+            else:
+                group.append(line)
+            prev = mid
+        regrouped += [group]
+        regrouped = np.vstack([Lines(r, is_horizontal=self.is_horizontal).mean for r in regrouped])
+        return Lines(regrouped, is_horizontal=self.is_horizontal)
+
+    def distance_to_point(self, point):
+        x, y = point
+        return self.rho - x * self.cos - y * self.sin
+
+    @staticmethod
+    def cross_two_lines(lines1, lines2):
+        for rho1, sin1, cos1 in zip(lines1.rho, lines1.sin, lines1.cos):
+            for rho2, sin2, cos2 in zip(lines2.rho, lines2.sin, lines2.cos):
+                a = np.array([[cos1, sin1], [cos2, sin2]])
+                b = np.array([rho1, rho2])
+                yield np.linalg.solve(a, b)
+
+    def cross(self, other):
+        points = np.vstack(self.cross_two_lines(self, other))
+        points = Points(points)
+        return points
+
+    def delete(self, other, threshold=3):
+        if not self:
+            return self
+
+        other_mid = other.mid
+        lines = []
+        for mid, line in zip(self.mid, self.lines):
+            if np.any(np.abs(other_mid - mid) < threshold):
+                continue
+            lines.append(line)
+
+        return Lines(lines, is_horizontal=self.is_horizontal)
+
+
+def area2corner(area):
+    """
+    Args:
+        area: (x1, y1, x2, y2)
+
+    Returns:
+        np.ndarray: [upper-left, upper-right, bottom-left, bottom-right]
+    """
+    return np.array([[area[0], area[1]], [area[2], area[1]], [area[0], area[3]], [area[2], area[3]]])
+
+
+def corner2area(corner):
+    """
+    Args:
+        corner: [upper-left, upper-right, bottom-left, bottom-right]
+
+    Returns:
+        np.ndarray: (x1, y1, x2, y2)
+    """
+    x, y = np.array(corner).T
+    return np.rint([np.min(x), np.min(y), np.max(x), np.max(y)]).astype(int)
+
+
+def corner2inner(corner):
+    """
+    The largest rectangle inscribed in trapezoid.
+
+    Args:
+        corner: ((x0, y0), (x1, y1), (x2, y2), (x3, y3))
+
+    Returns:
+        tuple[int]: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
+    """
+    x0, y0, x1, y1, x2, y2, x3, y3 = np.array(corner).flatten()
+    area = tuple(np.rint((max(x0, x2), max(y0, y1), min(x1, x3), min(y2, y3))).astype(int))
+    return area
+
+
+def corner2outer(corner):
+    """
+    The smallest rectangle circumscribed by the trapezoid.
+
+    Args:
+        corner: ((x0, y0), (x1, y1), (x2, y2), (x3, y3))
+
+    Returns:
+        tuple[int]: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
+    """
+    x0, y0, x1, y1, x2, y2, x3, y3 = np.array(corner).flatten()
+    area = tuple(np.rint((min(x0, x2), min(y0, y1), max(x1, x3), max(y2, y3))).astype(int))
+    return area
+
+
+def trapezoid2area(corner, pad=0):
+    """
+    Convert corners of a trapezoid to area.
+
+    Args:
+        corner: ((x0, y0), (x1, y1), (x2, y2), (x3, y3))
+        pad (int):
+            Positive value for inscribed area.
+            Negative value and 0 for circumscribed area.
+
+    Returns:
+        tuple[int]: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
+    """
+    if pad > 0:
+        return area_pad(corner2inner(corner), pad=pad)
+    elif pad < 0:
+        return area_pad(corner2outer(corner), pad=pad)
+    else:
+        return area_pad(corner2area(corner), pad=pad)
+
+
+def points_to_area_generator(points, shape):
+    """
+    Args:
+        points (np.ndarray): N x 2 array.
+        shape (tuple): (x, y).
+
+    Yields:
+        tuple, np.ndarray: (x, y), [upper-left, upper-right, bottom-left, bottom-right]
+    """
+    points = points.reshape(*shape[::-1], 2)
+    for y in range(shape[1] - 1):
+        for x in range(shape[0] - 1):
+            area = np.array([points[y, x], points[y, x + 1], points[y + 1, x], points[y + 1, x + 1]])
+            yield ((x, y), area)
+
+
+def get_map_inner(points):
+    """
+    Args:
+        points (np.ndarray): N x 2 array.
+
+    Yields:
+        np.ndarray: (x, y).
+    """
+    points = np.array(points)
+    if len(points.shape) == 1:
+        points = np.array([points])
+
+    return np.mean(points, axis=0)
+
+
+def separate_edges(edges, inner):
+    """
+    Args:
+        edges: A iterate object which contains float ot integer.
+        inner (float, int): A inner point to separate edges.
+
+    Returns:
+        float, float: Lower edge and upper edge. if not found, return None
+    """
+    if len(edges) == 0:
+        return None, None
+    elif len(edges) == 1:
+        edge = edges[0]
+        return (None, edge) if edge > inner else (edge, None)
+    else:
+        lower = [edge for edge in edges if edge < inner]
+        upper = [edge for edge in edges if edge > inner]
+        lower = lower[0] if len(lower) else None
+        upper = upper[-1] if len(upper) else None
+        return lower, upper
+
+
+def perspective_transform(points, data):
+    """
+    Args:
+        points: A 2D array with shape (n, 2)
+        data: Perspective data, a 2D array with shape (3, 3),
+            see https://web.archive.org/web/20150222120106/xenia.media.mit.edu/~cwren/interpolator/
+
+    Returns:
+        np.ndarray: 2D array with shape (n, 2)
+    """
+    points = np.pad(np.array(points), ((0, 0), (0, 1)), mode='constant', constant_values=1)
+    matrix = data.dot(points.T)
+    x, y = matrix[0] / matrix[2], matrix[1] / matrix[2]
+    points = np.array([x, y]).T
+    return points
+
+
+def fit_points(points, mod, encourage=1):
+    """
+    Get a closet point in a group of points with common difference.
+    Will ignore points in the distance.
+
+    Args:
+        points: Points on image, a 2D array with shape (n, 2)
+        mod: Common difference of points, (x, y).
+        encourage (int, float): Describe how close to fit a group of points, in pixel.
+            Smaller means closer to local minimum, larger means closer to global minimum.
+
+    Returns:
+        np.ndarray: (x, y)
+    """
+    encourage = np.square(encourage)
+    mod = np.array(mod)
+    points = np.array(points) % mod
+    points = np.append(points - mod, points, axis=0)
+
+    def cal_distance(point):
+        distance = np.linalg.norm(points - point, axis=1)
+        return np.sum(1 / (1 + np.exp(encourage / distance) / distance))
+
+    # Fast local minimizer
+    # result = optimize.minimize(cal_distance, np.mean(points, axis=0), method='SLSQP')
+    # return result['x'] % mod
+
+    # Brute-force global minimizer
+    area = np.append(-mod - 10, mod + 10)
+    result = optimize.brute(cal_distance, ((area[0], area[2]), (area[1], area[3])))
+    return result % mod

+ 0 - 0
module/base/utils.py → module/base/utils/utils.py


+ 14 - 2
module/device/connection.py

@@ -1,7 +1,7 @@
 # This Python file uses the following encoding: utf-8
 import ipaddress
 import logging
-import platform
+import platform2
 import re
 import socket
 import subprocess
@@ -301,7 +301,7 @@ class Connection(ConnectionAttr):
                 logger.error(e)
                 logger.error(f'Unknown host name: {socket.gethostname()}')
                 host = '127.0.0.1'
-            if platform.system() == 'Linux' and host == '127.0.1.1':
+            if platform2.system() == 'Linux' and host == '127.0.1.1':
                 host = '127.0.0.1'
             logger.info(f'Connecting to local emulator, using host {host}')
             port = random_port(self.config.FORWARD_PORT_RANGE)
@@ -843,6 +843,18 @@ class Connection(ConnectionAttr):
         packages = [p for p in packages if any([k in p.lower() for k in keywords])]
         return packages
 
+    # def list_known_packages(self, show_log=True):
+    #     """
+    #     Args:
+    #         show_log:
+    #
+    #     Returns:
+    #         list[str]: List of package names
+    #     """
+    #     packages = self.list_package(show_log=show_log)
+    #     packages = [p for p in packages if p in server_.VALID_PACKAGE or p in server_.VALID_CLOUD_PACKAGE]
+    #     return packages
+
     def detect_package(self, keywords=('onmyoji', 'yys'), set_config=True):
         """
         Show all possible packages with the given keyword on this device.

+ 36 - 14
module/device/device.py

@@ -1,27 +1,29 @@
-import sys
-import cv2
+
 from collections import deque
 from datetime import datetime
 
+# Patch pkg_resources before importing adbutils and uiautomator2
+from module.device.pkg_resources import get_distribution
+# Just avoid being removed by import optimization
+_ = get_distribution
+
+from module.device.env import IS_WINDOWS
 from module.base.timer import Timer
 from module.config.utils import get_server_next_update
 from module.device.app_control import AppControl
 from module.device.control import Control
-from module.device.method.window import Window
+from module.device.platform2 import Platform
 from module.device.screenshot import Screenshot
-from module.exception import (GameNotRunningError, GameStuckError,
-                              GameTooManyClickError, RequestHumanTakeover)
-# from module.handler.assets import GET_MISSION
+from module.exception import (GameNotRunningError,
+                              GameStuckError,
+                              GameTooManyClickError,
+                              RequestHumanTakeover,
+                              EmulatorNotRunningError)
 from module.logger import logger
 
-if sys.platform == 'win32':
-    from module.device.emulator import EmulatorManager
-else:
-    class EmulatorManager:
-        pass
 
 
-class Device(Screenshot, Control, AppControl, EmulatorManager):
+class Device(Platform, Screenshot, Control, AppControl):
     _screen_size_checked = False
     detect_record = set()
     click_record = deque(maxlen=15)
@@ -30,9 +32,29 @@ class Device(Screenshot, Control, AppControl, EmulatorManager):
     stuck_long_wait_list = ['BATTLE_STATUS_S', 'PAUSE', 'LOGIN_CHECK']
 
     def __init__(self, *args, **kwargs):
-        super().__init__(*args, **kwargs)
+        for trial in range(4):
+            try:
+                super().__init__(*args, **kwargs)
+                break
+            except EmulatorNotRunningError:
+                if trial >= 3:
+                    logger.critical('Failed to start emulator after 3 trial')
+                    raise RequestHumanTakeover
+                # Try to start emulator
+                if self.emulator_instance is not None:
+                    self.emulator_start()
+                else:
+                    logger.critical(
+                        f'No emulator with serial "{self.config.Emulator_Serial}" found, '
+                        f'please set a correct serial'
+                    )
+                    raise RequestHumanTakeover
+
+        # Auto-fill emulator info
+        if IS_WINDOWS and self.config.script.device.emulatorinfo_type == 'auto':
+            _ = self.emulator_instance
+
         self.screenshot_interval_set()
-        # 我不能接受为什么继承了Window但是不会自动初始化
 
         # Auto-select the fastest screenshot method
         if self.config.script.device.screenshot_method == 'auto':

+ 1 - 1
module/device/env.py

@@ -4,4 +4,4 @@ import sys
 
 IS_WINDOWS = sys.platform == 'win32'
 IS_MACINTOSH = sys.platform == 'darwin'
-IS_LINUX = sys.platform == 'linux'
+IS_LINUX = sys.platform == 'linux'

+ 17 - 1
module/device/handle.py

@@ -17,7 +17,6 @@ from win32con import (SRCCOPY, DESKTOPHORZRES, DESKTOPVERTRES, WM_LBUTTONUP,
                       WM_LBUTTONDOWN, WM_ACTIVATE, WA_ACTIVE, MK_LBUTTON,
                       WM_NCHITTEST, WM_SETCURSOR, HTCLIENT, WM_MOUSEMOVE)
 from module.config.config import Config
-from module.exception import RequestHumanTakeover, EmulatorNotRunningError
 from module.logger import logger
 
 
@@ -80,6 +79,12 @@ class WindowNode(NodeMixin):
         self.num = num
         self.parent = parent
 
+    @classmethod
+    def get_tree_depth(cls, root_node: 'WindowNode'):
+        if not root_node.children:
+            return 1 if root_node else 0
+        return max(node.depth for node in root_node.descendants) + 1
+
 
 class EmulatorFamily(Enum):
     FAMILY_MUMU = 10  # mumu模拟器
@@ -399,6 +404,17 @@ class Handle:
         return round(wReal / wAfter, 2)
 
 
+    @classmethod
+    def handle_has_children(cls, hwnd: int, name: str = 'MuMuPlayer12') -> bool:
+        root_node = WindowNode(name=name, num=hwnd)
+        Handle.handle_tree(hwnd=hwnd, node=root_node)
+        handle_depth = WindowNode.get_tree_depth(root_node)
+        if handle_depth > 1:
+            logger.info(f'Window handle [{hwnd}] depth: {handle_depth}')
+            return True
+        return False
+
+
 if __name__ == '__main__':
     h = Handle(config='oas1')
     # logger.info(h.auto_handle_title(h.all_windows()))

+ 109 - 0
module/device/pkg_resources/__init__.py

@@ -0,0 +1,109 @@
+import os
+import re
+import sys
+
+from module.base.decorator import cached_property
+from module.logger import logger
+
+"""
+Importing pkg_resources is so slow, like 0.4 ~ 1.0s, just google it you will find it indeed really slow.
+Since it was some kind of standard library there is no way to modify it or speed it up.
+So here's a poor but fast implementation of pkg_resources returning the things in need.
+
+To patch:
+```
+# Patch pkg_resources before importing adbutils and uiautomator2
+from module.device.pkg_resources import get_distribution
+# Just avoid being removed by import optimization
+_ = get_distribution
+```
+"""
+# Inject sys.modules, pretend we have pkg_resources imported
+try:
+    sys.modules['pkg_resources'] = sys.modules['module.device.pkg_resources']
+except KeyError:
+    logger.error('Patch pkg_resources failed, patch module does not exists')
+
+
+def remove_suffix(s, suffix):
+    """
+    Remove suffix of a string or bytes like `string.removesuffix(suffix)`, which is on Python3.9+
+
+    Args:
+        s (str, bytes):
+        suffix (str, bytes):
+
+    Returns:
+        str, bytes:
+    """
+    return s[:-len(suffix)] if s.endswith(suffix) else s
+
+
+class FakeDistributionObject:
+    def __init__(self, dist, version):
+        self.dist = dist
+        self.version = version
+
+    def __str__(self):
+        return f'{self.__class__.__name__}({self.dist}={self.version})'
+
+    __repr__ = __str__
+
+
+class PackageCache:
+    @cached_property
+    def site_packages(self):
+        # Just whatever library to locate the `site-packages` directory
+        import requests
+        path = os.path.abspath(os.path.join(requests.__file__, '../../'))
+        return path
+
+    @cached_property
+    def dict_installed_packages(self):
+        """
+        Returns:
+            dict: Key: str, package name
+                Value: FakeDistributionObject
+        """
+        dic = {}
+        for file in os.listdir(self.site_packages):
+            # mxnet_cu101-1.6.0.dist-info
+            # adbutils-0.11.0-py3.7.egg-info
+            res = re.match(r'^([a-zA-Z0-9._]+)-([a-zA-Z0-9._]+)-', file)
+            if res:
+                version = remove_suffix(res.group(2), '.dist')
+                # version = res.group(2)
+                obj = FakeDistributionObject(
+                    dist=res.group(1),
+                    version=version,
+                )
+                dic[obj.dist] = obj
+
+        return dic
+
+
+PACKAGE_CACHE = PackageCache()
+
+
+def resource_filename(*args):
+    if args == ("adbutils", "binaries"):
+        path = os.path.abspath(os.path.join(PACKAGE_CACHE.site_packages, *args))
+        return path
+
+
+def get_distribution(dist):
+    """Return a current distribution object for a Requirement or string"""
+    if dist == 'adbutils':
+        return PACKAGE_CACHE.dict_installed_packages.get(
+            'adbutils',
+            FakeDistributionObject('adbutils', '0.11.0'),
+        )
+    if dist == 'uiautomator2':
+        return PACKAGE_CACHE.dict_installed_packages.get(
+            'uiautomator2',
+            FakeDistributionObject('uiautomator2', '2.16.17'),
+        )
+
+
+class DistributionNotFound(Exception):
+    pass

+ 6 - 0
module/device/platform2/__init__.py

@@ -0,0 +1,6 @@
+from module.device.env import IS_WINDOWS
+
+if IS_WINDOWS:
+    from module.device.platform2.platform_windows import PlatformWindows as Platform
+else:
+    from module.device.platform2.platform_base import PlatformBase as Platform

+ 287 - 0
module/device/platform2/emulator_base.py

@@ -0,0 +1,287 @@
+import os
+import re
+import typing as t
+from dataclasses import dataclass
+
+from module.device.platform2.utils import cached_property, iter_folder
+
+
+def abspath(path):
+    return os.path.abspath(path).replace('\\', '/')
+
+
+def get_serial_pair(serial):
+    """
+    Args:
+        serial (str):
+
+    Returns:
+        str, str: `127.0.0.1:5555+{X}` and `emulator-5554+{X}`, 0 <= X <= 32
+    """
+    if serial.startswith('127.0.0.1:'):
+        try:
+            port = int(serial[10:])
+            if 5555 <= port <= 5555 + 32:
+                return f'127.0.0.1:{port}', f'emulator-{port - 1}'
+        except (ValueError, IndexError):
+            pass
+    if serial.startswith('emulator-'):
+        try:
+            port = int(serial[9:])
+            if 5554 <= port <= 5554 + 32:
+                return f'127.0.0.1:{port + 1}', f'emulator-{port}'
+        except (ValueError, IndexError):
+            pass
+
+    return None, None
+
+
+def remove_duplicated_path(paths):
+    """
+    Args:
+        paths (list[str]):
+
+    Returns:
+        list[str]:
+    """
+    paths = sorted(set(paths))
+    dic = {}
+    for path in paths:
+        dic.setdefault(path.lower(), path)
+    return list(dic.values())
+
+
+@dataclass
+class EmulatorInstanceBase:
+    # Serial for adb connection
+    serial: str
+    # Emulator instance name, used for start/stop emulator
+    name: str
+    # Path to emulator .exe
+    path: str
+
+    def __str__(self):
+        return f'{self.type}(serial="{self.serial}", name="{self.name}", path="{self.path}")'
+
+    @cached_property
+    def type(self) -> str:
+        """
+        Returns:
+            str: Emulator type, such as Emulator.NoxPlayer
+        """
+        return self.emulator.type
+
+    @cached_property
+    def emulator(self):
+        """
+        Returns:
+            Emulator:
+        """
+        return EmulatorBase(self.path)
+
+    def __eq__(self, other):
+        if isinstance(other, str) and self.type == other:
+            return True
+        if isinstance(other, list) and self.type in other:
+            return True
+        if isinstance(other, EmulatorInstanceBase):
+            return super().__eq__(other) and self.type == other.type
+        return super().__eq__(other)
+
+    def __hash__(self):
+        return hash(str(self))
+
+    def __bool__(self):
+        return True
+
+    @cached_property
+    def MuMuPlayer12_id(self):
+        """
+        Convert MuMu 12 instance name to instance id.
+        Example names:
+            MuMuPlayer-12.0-3
+            YXArkNights-12.0-1
+
+        Returns:
+            int: Instance ID, or None if this is not a MuMu 12 instance
+        """
+        res = re.search(r'MuMuPlayer(?:Global)?-12.0-(\d+)', self.name)
+        if res:
+            return int(res.group(1))
+        res = re.search(r'YXArkNights-12.0-(\d+)', self.name)
+        if res:
+            return int(res.group(1))
+
+        return None
+
+    @cached_property
+    def LDPlayer_id(self):
+        """
+        Convert LDPlayer instance name to instance id.
+        Example names:
+            leidian0
+            leidian1
+
+        Returns:
+            int: Instance ID, or None if this is not a LDPlayer instance
+        """
+        res = re.search(r'leidian(\d+)', self.name)
+        if res:
+            return int(res.group(1))
+
+        return None
+
+
+class EmulatorBase:
+    # Values here must match those in argument.yaml EmulatorInfo.Emulator.option
+    NoxPlayer = 'NoxPlayer'
+    NoxPlayer64 = 'NoxPlayer64'
+    NoxPlayerFamily = [NoxPlayer, NoxPlayer64]
+    BlueStacks4 = 'BlueStacks4'
+    BlueStacks5 = 'BlueStacks5'
+    BlueStacks4HyperV = 'BlueStacks4HyperV'
+    BlueStacks5HyperV = 'BlueStacks5HyperV'
+    BlueStacksFamily = [BlueStacks4, BlueStacks5]
+    LDPlayer3 = 'LDPlayer3'
+    LDPlayer4 = 'LDPlayer4'
+    LDPlayer9 = 'LDPlayer9'
+    LDPlayerFamily = [LDPlayer3, LDPlayer4, LDPlayer9]
+    MuMuPlayer = 'MuMuPlayer'
+    MuMuPlayerX = 'MuMuPlayerX'
+    MuMuPlayer12 = 'MuMuPlayer12'
+    MuMuPlayerFamily = [MuMuPlayer, MuMuPlayerX, MuMuPlayer12]
+    MEmuPlayer = 'MEmuPlayer'
+
+    @classmethod
+    def path_to_type(cls, path: str) -> str:
+        """
+        Args:
+            path: Path to .exe file
+
+        Returns:
+            str: Emulator type, such as Emulator.NoxPlayer,
+                or '' if this is not a emulator.
+        """
+        return ''
+
+    def iter_instances(self) -> t.Iterable[EmulatorInstanceBase]:
+        """
+        Yields:
+            EmulatorInstance: Emulator instances found in this emulator
+        """
+        pass
+
+    def iter_adb_binaries(self) -> t.Iterable[str]:
+        """
+        Yields:
+            str: Filepath to adb binaries found in this emulator
+        """
+        pass
+
+    def __init__(self, path):
+        # Path to .exe file
+        self.path = path.replace('\\', '/')
+        # Path to emulator folder
+        self.dir = os.path.dirname(path)
+        # str: Emulator type, or '' if this is not a emulator.
+        self.type = self.__class__.path_to_type(path)
+
+    def __eq__(self, other):
+        if isinstance(other, str) and self.type == other:
+            return True
+        if isinstance(other, list) and self.type in other:
+            return True
+        return super().__eq__(other)
+
+    def __str__(self):
+        return f'{self.type}(path="{self.path}")'
+
+    __repr__ = __str__
+
+    def __hash__(self):
+        return hash(self.path)
+
+    def __bool__(self):
+        return True
+
+    def abspath(self, path, folder=None):
+        if folder is None:
+            folder = self.dir
+        return abspath(os.path.join(folder, path))
+
+    @classmethod
+    def is_emulator(cls, path: str) -> bool:
+        """
+        Args:
+            path: Path to .exe file.
+
+        Returns:
+            bool: If this is a emulator.
+        """
+        return bool(cls.path_to_type(path))
+
+    def list_folder(self, folder, is_dir=False, ext=None):
+        """
+        Safely list files in a folder
+
+        Args:
+            folder:
+            is_dir:
+            ext:
+
+        Returns:
+            list[str]:
+        """
+        folder = self.abspath(folder)
+        return list(iter_folder(folder, is_dir=is_dir, ext=ext))
+
+
+class EmulatorManagerBase:
+    @staticmethod
+    def iter_running_emulator():
+        """
+        Yields:
+            str: Path to emulator executables, may contains duplicate values
+        """
+        return
+
+    @cached_property
+    def all_emulators(self) -> t.List[EmulatorBase]:
+        """
+        Get all emulators installed on current computer.
+        """
+        return []
+
+    @cached_property
+    def all_emulator_instances(self) -> t.List[EmulatorInstanceBase]:
+        """
+        Get all emulator instances installed on current computer.
+        """
+        return []
+
+    @cached_property
+    def all_emulator_serials(self) -> t.List[str]:
+        """
+        Returns:
+            list[str]: All possible serials on current computer.
+        """
+        out = []
+        for emulator in self.all_emulator_instances:
+            out.append(emulator.serial)
+            # Also add serial like `emulator-5554`
+            port_serial, emu_serial = get_serial_pair(emulator.serial)
+            if emu_serial:
+                out.append(emu_serial)
+        return out
+
+    @cached_property
+    def all_adb_binaries(self) -> t.List[str]:
+        """
+        Returns:
+            list[str]: All adb binaries of emulators on current computer.
+        """
+        out = []
+        for emulator in self.all_emulators:
+            for exe in emulator.iter_adb_binaries():
+                out.append(exe)
+        return out

+ 588 - 0
module/device/platform2/emulator_windows.py

@@ -0,0 +1,588 @@
+import codecs
+import os
+import re
+import typing as t
+import winreg
+from dataclasses import dataclass
+
+# module/device/platform/emulator_base.py
+# module/device/platform/emulator_windows.py
+# Will be used in Alas Easy Install, they shouldn't import any Alas modules.
+from module.device.platform2.emulator_base import (
+    EmulatorBase,
+    EmulatorInstanceBase,
+    EmulatorManagerBase,
+    remove_duplicated_path)
+from module.device.platform2.utils import cached_property, iter_folder
+
+
+@dataclass
+class RegValue:
+    name: str
+    value: str
+    typ: int
+
+
+def list_reg(reg) -> t.List[RegValue]:
+    """
+    List all values in a reg key
+    """
+    rows = []
+    index = 0
+    try:
+        while 1:
+            value = RegValue(*winreg.EnumValue(reg, index))
+            index += 1
+            rows.append(value)
+    except OSError:
+        pass
+    return rows
+
+
+def list_key(reg) -> t.List[RegValue]:
+    """
+    List all values in a reg key
+    """
+    rows = []
+    index = 0
+    try:
+        while 1:
+            value = winreg.EnumKey(reg, index)
+            index += 1
+            rows.append(value)
+    except OSError:
+        pass
+    return rows
+
+
+def abspath(path):
+    return os.path.abspath(path).replace('\\', '/')
+
+
+class EmulatorInstance(EmulatorInstanceBase):
+    @cached_property
+    def emulator(self):
+        """
+        Returns:
+            Emulator:
+        """
+        return Emulator(self.path)
+
+
+class Emulator(EmulatorBase):
+    @classmethod
+    def path_to_type(cls, path: str) -> str:
+        """
+        Args:
+            path: Path to .exe file, case insensitive
+
+        Returns:
+            str: Emulator type, such as Emulator.NoxPlayer
+        """
+        folder, exe = os.path.split(path)
+        folder, dir1 = os.path.split(folder)
+        folder, dir2 = os.path.split(folder)
+        exe = exe.lower()
+        dir1 = dir1.lower()
+        dir2 = dir2.lower()
+        if exe == 'nox.exe':
+            if dir2 == 'nox':
+                return cls.NoxPlayer
+            elif dir2 == 'nox64':
+                return cls.NoxPlayer64
+            else:
+                return cls.NoxPlayer
+        if exe == 'bluestacks.exe':
+            if dir1 in ['bluestacks', 'bluestacks_cn']:
+                return cls.BlueStacks4
+            elif dir1 in ['bluestacks_nxt', 'bluestacks_nxt_cn']:
+                return cls.BlueStacks5
+            else:
+                return cls.BlueStacks4
+        if exe == 'hd-player.exe':
+            if dir1 in ['bluestacks', 'bluestacks_cn']:
+                return cls.BlueStacks4
+            elif dir1 in ['bluestacks_nxt', 'bluestacks_nxt_cn']:
+                return cls.BlueStacks5
+            else:
+                return cls.BlueStacks5
+        if exe == 'dnplayer.exe':
+            if dir1 == 'ldplayer':
+                return cls.LDPlayer3
+            elif dir1 == 'ldplayer4':
+                return cls.LDPlayer4
+            elif dir1 == 'ldplayer9':
+                return cls.LDPlayer9
+            else:
+                return cls.LDPlayer3
+        if exe == 'nemuplayer.exe':
+            if dir2 == 'nemu':
+                return cls.MuMuPlayer
+            elif dir2 == 'nemu9':
+                return cls.MuMuPlayerX
+            else:
+                return cls.MuMuPlayer
+        if exe == 'mumuplayer.exe':
+            return cls.MuMuPlayer12
+        if exe == 'memu.exe':
+            return cls.MEmuPlayer
+
+        return ''
+
+    @staticmethod
+    def multi_to_single(exe):
+        """
+        Convert a string that might be a multi-instance manager to its single instance executable.
+
+        Args:
+            exe (str): Path to emulator executable
+
+        Yields:
+            str: Path to emulator executable
+        """
+        if 'HD-MultiInstanceManager.exe' in exe:
+            yield exe.replace('HD-MultiInstanceManager.exe', 'HD-Player.exe')
+            yield exe.replace('HD-MultiInstanceManager.exe', 'Bluestacks.exe')
+        elif 'MultiPlayerManager.exe' in exe:
+            yield exe.replace('MultiPlayerManager.exe', 'Nox.exe')
+        elif 'dnmultiplayer.exe' in exe:
+            yield exe.replace('dnmultiplayer.exe', 'dnplayer.exe')
+        elif 'NemuMultiPlayer.exe' in exe:
+            yield exe.replace('NemuMultiPlayer.exe', 'NemuPlayer.exe')
+        elif 'MuMuMultiPlayer.exe' in exe:
+            yield exe.replace('MuMuMultiPlayer.exe', 'MuMuPlayer.exe')
+        elif 'MuMuManager.exe' in exe:
+            yield exe.replace('MuMuManager.exe', 'MuMuPlayer.exe')
+        elif 'MEmuConsole.exe' in exe:
+            yield exe.replace('MEmuConsole.exe', 'MEmu.exe')
+        else:
+            yield exe
+
+    @staticmethod
+    def single_to_console(exe: str):
+        """
+        Convert a string that might be a single instance executable to its console.
+
+        Args:
+            exe (str): Path to emulator executable
+
+        Returns:
+            str: Path to emulator console
+        """
+        if 'MuMuPlayer.exe' in exe:
+            return exe.replace('MuMuPlayer.exe', 'MuMuManager.exe')
+        elif 'LDPlayer.exe' in exe:
+            return exe.replace('LDPlayer.exe', 'ldconsole.exe')
+        elif 'dnplayer.exe' in exe:
+            return exe.replace('dnplayer.exe', 'ldconsole.exe')
+        elif 'Bluestacks.exe' in exe:
+            return exe.replace('Bluestacks.exe', 'bsconsole.exe')
+        elif 'MEmu.exe' in exe:
+            return exe.replace('MEmu.exe', 'memuc.exe')
+        else:
+            return exe
+
+    @staticmethod
+    def vbox_file_to_serial(file: str) -> str:
+        """
+        Args:
+            file: Path to vbox file
+
+        Returns:
+            str: serial such as `127.0.0.1:5555`
+        """
+        regex = re.compile('<*?hostport="(.*?)".*?guestport="5555"/>')
+        try:
+            with open(file, 'r', encoding='utf-8', errors='ignore') as f:
+                for line in f.readlines():
+                    # <Forwarding name="port2" proto="1" hostip="127.0.0.1" hostport="62026" guestport="5555"/>
+                    res = regex.search(line)
+                    if res:
+                        return f'127.0.0.1:{res.group(1)}'
+            return ''
+        except FileNotFoundError:
+            return ''
+
+    def iter_instances(self):
+        """
+        Yields:
+            EmulatorInstance: Emulator instances found in this emulator
+        """
+        if self == Emulator.NoxPlayerFamily:
+            # ./BignoxVMS/{name}/{name}.vbox
+            for folder in self.list_folder('./BignoxVMS', is_dir=True):
+                for file in iter_folder(folder, ext='.vbox'):
+                    serial = Emulator.vbox_file_to_serial(file)
+                    if serial:
+                        yield EmulatorInstance(
+                            serial=serial,
+                            name=os.path.basename(folder),
+                            path=self.path,
+                        )
+        elif self == Emulator.BlueStacks5:
+            # Get UserDefinedDir, where BlueStacks stores data
+            folder = None
+            try:
+                with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\BlueStacks_nxt") as reg:
+                    folder = winreg.QueryValueEx(reg, 'UserDefinedDir')[0]
+            except FileNotFoundError:
+                pass
+            try:
+                with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\BlueStacks_nxt_cn") as reg:
+                    folder = winreg.QueryValueEx(reg, 'UserDefinedDir')[0]
+            except FileNotFoundError:
+                pass
+            if not folder:
+                return
+            # Read {UserDefinedDir}/bluestacks.conf
+            try:
+                with open(self.abspath('./bluestacks.conf', folder), encoding='utf-8') as f:
+                    content = f.read()
+            except FileNotFoundError:
+                return
+            # bst.instance.Nougat64.adb_port="5555"
+            emulators = re.findall(r'bst.instance.(\w+).status.adb_port="(\d+)"', content)
+            for emulator in emulators:
+                yield EmulatorInstance(
+                    serial=f'127.0.0.1:{emulator[1]}',
+                    name=emulator[0],
+                    path=self.path,
+                )
+        elif self == Emulator.BlueStacks4:
+            # ../Engine/Android
+            regex = re.compile(r'^Android')
+            for folder in self.list_folder('../Engine', is_dir=True):
+                folder = os.path.basename(folder)
+                res = regex.match(folder)
+                if not res:
+                    continue
+                # Serial from BlueStacks4 are not static, they get increased on every emulator launch
+                # Assume all use 127.0.0.1:5555
+                yield EmulatorInstance(
+                    serial=f'127.0.0.1:5555',
+                    name=folder,
+                    path=self.path
+                )
+        elif self == Emulator.LDPlayerFamily:
+            # ./vms/leidian0
+            regex = re.compile(r'^leidian(\d+)$')
+            for folder in self.list_folder('./vms', is_dir=True):
+                folder = os.path.basename(folder)
+                res = regex.match(folder)
+                if not res:
+                    continue
+                # LDPlayer has no forward port config in .vbox file
+                # Ports are auto increase, 5555, 5557, 5559, etc
+                port = int(res.group(1)) * 2 + 5555
+                yield EmulatorInstance(
+                    serial=f'127.0.0.1:{port}',
+                    name=folder,
+                    path=self.path
+                )
+        elif self == Emulator.MuMuPlayer:
+            # MuMu has no multi instances, on 7555 only
+            yield EmulatorInstance(
+                serial='127.0.0.1:7555',
+                name='',
+                path=self.path,
+            )
+        elif self == Emulator.MuMuPlayerX:
+            # vms/nemu-12.0-x64-default
+            for folder in self.list_folder('../vms', is_dir=True):
+                for file in iter_folder(folder, ext='.nemu'):
+                    serial = Emulator.vbox_file_to_serial(file)
+                    if serial:
+                        yield EmulatorInstance(
+                            serial=serial,
+                            name=os.path.basename(folder),
+                            path=self.path,
+                        )
+        elif self == Emulator.MuMuPlayer12:
+            # vms/MuMuPlayer-12.0-0
+            for folder in self.list_folder('../vms', is_dir=True):
+                for file in iter_folder(folder, ext='.nemu'):
+                    serial = Emulator.vbox_file_to_serial(file)
+                    name = os.path.basename(folder)
+                    if serial:
+                        yield EmulatorInstance(
+                            serial=serial,
+                            name=name,
+                            path=self.path,
+                        )
+                    # Fix for MuMu12 v4.0.4, default instance of which has no forward record in vbox config
+                    else:
+                        instance = EmulatorInstance(
+                            serial=serial,
+                            name=name,
+                            path=self.path,
+                        )
+                        if instance.MuMuPlayer12_id:
+                            instance.serial = f'127.0.0.1:{16384 + 32 * instance.MuMuPlayer12_id}'
+                            yield instance
+        elif self == Emulator.MEmuPlayer:
+            # ./MemuHyperv VMs/{name}/{name}.memu
+            for folder in self.list_folder('./MemuHyperv VMs', is_dir=True):
+                for file in iter_folder(folder, ext='.memu'):
+                    serial = Emulator.vbox_file_to_serial(file)
+                    if serial:
+                        yield EmulatorInstance(
+                            serial=serial,
+                            name=os.path.basename(folder),
+                            path=self.path,
+                        )
+
+    def iter_adb_binaries(self) -> t.Iterable[str]:
+        """
+        Yields:
+            str: Filepath to adb binaries found in this emulator
+        """
+        if self == Emulator.NoxPlayerFamily:
+            exe = self.abspath('./nox_adb.exe')
+            if os.path.exists(exe):
+                yield exe
+        if self == Emulator.MuMuPlayerFamily:
+            # From MuMu9\emulator\nemu9\EmulatorShell
+            # to MuMu9\emulator\nemu9\vmonitor\bin\adb_server.exe
+            exe = self.abspath('../vmonitor/bin/adb_server.exe')
+            if os.path.exists(exe):
+                yield exe
+
+        # All emulators have adb.exe
+        exe = self.abspath('./adb.exe')
+        if os.path.exists(exe):
+            yield exe
+
+
+class EmulatorManager(EmulatorManagerBase):
+    @staticmethod
+    def iter_user_assist():
+        """
+        Get recently executed programs in UserAssist
+        https://github.com/forensicmatt/MonitorUserAssist
+
+        Yields:
+            str: Path to emulator executables, may contains duplicate values
+        """
+        path = r'Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist'
+        # {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\xxx.exe
+        regex_hash = re.compile(r'{.*}')
+        try:
+            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path) as reg:
+                folders = list_key(reg)
+        except FileNotFoundError:
+            return
+
+        for folder in folders:
+            try:
+                with winreg.OpenKey(winreg.HKEY_CURRENT_USER, f'{path}\\{folder}\\Count') as reg:
+                    for key in list_reg(reg):
+                        key = codecs.decode(key.name, 'rot-13')
+                        # Skip those with hash
+                        if regex_hash.search(key):
+                            continue
+                        for file in Emulator.multi_to_single(key):
+                            yield file
+            except FileNotFoundError:
+                # FileNotFoundError: [WinError 2] 系统找不到指定的文件。
+                # Might be a random directory without "Count" subdirectory
+                continue
+
+    @staticmethod
+    def iter_mui_cache():
+        """
+        Iter emulator executables that has ever run.
+        http://what-when-how.com/windows-forensic-analysis/registry-analysis-windows-forensic-analysis-part-8/
+        https://3gstudent.github.io/%E6%B8%97%E9%80%8F%E6%8A%80%E5%B7%A7-Windows%E7%B3%BB%E7%BB%9F%E6%96%87%E4%BB%B6%E6%89%A7%E8%A1%8C%E8%AE%B0%E5%BD%95%E7%9A%84%E8%8E%B7%E5%8F%96%E4%B8%8E%E6%B8%85%E9%99%A4
+
+        Yields:
+            str: Path to emulator executable, may contains duplicate values
+        """
+        path = r'Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\MuiCache'
+        try:
+            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path) as reg:
+                rows = list_reg(reg)
+        except FileNotFoundError:
+            return
+
+        regex = re.compile(r'(^.*\.exe)\.')
+        for row in rows:
+            res = regex.search(row.name)
+            if not res:
+                continue
+            for file in Emulator.multi_to_single(res.group(1)):
+                yield file
+
+    @staticmethod
+    def get_install_dir_from_reg(path, key):
+        """
+        Args:
+            path (str): f'SOFTWARE\\leidian\\ldplayer'
+            key (str): 'InstallDir'
+
+        Returns:
+            str: Installation dir or None
+        """
+        try:
+            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path) as reg:
+                root = winreg.QueryValueEx(reg, key)[0]
+                return root
+        except FileNotFoundError:
+            pass
+        try:
+            with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) as reg:
+                root = winreg.QueryValueEx(reg, key)[0]
+                return root
+        except FileNotFoundError:
+            pass
+
+        return None
+
+    @staticmethod
+    def iter_uninstall_registry():
+        """
+        Iter emulator uninstaller from registry.
+
+        Yields:
+            str: Path to uninstall exe file
+        """
+        known_uninstall_registry_path = [
+            r'SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall',
+            r'Software\Microsoft\Windows\CurrentVersion\Uninstall'
+        ]
+        known_emulator_registry_name = [
+            'Nox',
+            'Nox64',
+            'BlueStacks',
+            'BlueStacks_nxt',
+            'BlueStacks_cn',
+            'BlueStacks_nxt_cn',
+            'LDPlayer',
+            'LDPlayer4',
+            'LDPlayer9',
+            'leidian',
+            'leidian4',
+            'leidian9',
+            'Nemu',
+            'Nemu9',
+            'MuMuPlayer-12.0'
+            'MEmu',
+        ]
+        for path in known_uninstall_registry_path:
+            try:
+                with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) as reg:
+                    software_list = list_key(reg)
+            except FileNotFoundError:
+                continue
+            for software in software_list:
+                if software not in known_emulator_registry_name:
+                    continue
+                try:
+                    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, f'{path}\\{software}') as software_reg:
+                        uninstall = winreg.QueryValueEx(software_reg, 'UninstallString')[0]
+                except FileNotFoundError:
+                    continue
+                if not uninstall:
+                    continue
+                # UninstallString is like:
+                # C:\Program Files\BlueStacks_nxt\BlueStacksUninstaller.exe -tmp
+                # "E:\ProgramFiles\Microvirt\MEmu\uninstall\uninstall.exe" -u
+                # Extract path in ""
+                res = re.search('"(.*?)"', uninstall)
+                uninstall = res.group(1) if res else uninstall
+                yield uninstall
+
+    @staticmethod
+    def iter_running_emulator():
+        """
+        Yields:
+            str: Path to emulator executables, may contains duplicate values
+        """
+        try:
+            import psutil
+        except ModuleNotFoundError:
+            return
+        # Since this is a one-time-usage, we access psutil._psplatform.Process directly
+        # to bypass the call of psutil.Process.is_running().
+        # This only costs about 0.017s.
+        for pid in psutil.pids():
+            proc = psutil._psplatform.Process(pid)
+            try:
+                exe = proc.cmdline()
+                exe = exe[0].replace(r'\\', '/').replace('\\', '/')
+            except (psutil.AccessDenied, psutil.NoSuchProcess, IndexError, OSError):
+                # psutil.AccessDenied
+                # NoSuchProcess: process no longer exists (pid=xxx)
+                # OSError: [WinError 87] 参数错误。: '(originated from ReadProcessMemory)'
+                continue
+
+            if Emulator.is_emulator(exe):
+                yield exe
+
+    @cached_property
+    def all_emulators(self) -> t.List[Emulator]:
+        """
+        Get all emulators installed on current computer.
+        """
+        exe = set([])
+
+        # MuiCache
+        for file in EmulatorManager.iter_mui_cache():
+            if Emulator.is_emulator(file) and os.path.exists(file):
+                exe.add(file)
+
+        # UserAssist
+        for file in EmulatorManager.iter_user_assist():
+            if Emulator.is_emulator(file) and os.path.exists(file):
+                exe.add(file)
+
+        # LDPlayer install path
+        for path in [r'SOFTWARE\leidian\ldplayer',
+                     r'SOFTWARE\leidian\ldplayer9']:
+            ld = self.get_install_dir_from_reg(path, 'InstallDir')
+            if ld:
+                ld = abspath(os.path.join(ld, './dnplayer.exe'))
+                if Emulator.is_emulator(ld) and os.path.exists(ld):
+                    exe.add(ld)
+
+        # Uninstall registry
+        for uninstall in EmulatorManager.iter_uninstall_registry():
+            # Find emulator executable from uninstaller
+            for file in iter_folder(abspath(os.path.dirname(uninstall)), ext='.exe'):
+                if Emulator.is_emulator(file) and os.path.exists(file):
+                    exe.add(file)
+            # Find from parent directory
+            for file in iter_folder(abspath(os.path.join(os.path.dirname(uninstall), '../')), ext='.exe'):
+                if Emulator.is_emulator(file) and os.path.exists(file):
+                    exe.add(file)
+            # MuMu specific directory
+            for file in iter_folder(abspath(os.path.join(os.path.dirname(uninstall), 'EmulatorShell')), ext='.exe'):
+                if Emulator.is_emulator(file) and os.path.exists(file):
+                    exe.add(file)
+
+        # Running
+        for file in EmulatorManager.iter_running_emulator():
+            if os.path.exists(file):
+                exe.add(file)
+
+        # De-redundancy
+        exe = [Emulator(path).path for path in exe if Emulator.is_emulator(path)]
+        exe = [Emulator(path) for path in remove_duplicated_path(exe)]
+        return exe
+
+    @cached_property
+    def all_emulator_instances(self) -> t.List[EmulatorInstance]:
+        """
+        Get all emulator instances installed on current computer.
+        """
+        instances = []
+        for emulator in self.all_emulators:
+            instances += list(emulator.iter_instances())
+
+        instances: t.List[EmulatorInstance] = sorted(instances, key=lambda x: str(x))
+        return instances
+
+
+if __name__ == '__main__':
+    self = EmulatorManager()
+    for emu in self.all_emulator_instances:
+        print(emu)

+ 226 - 0
module/device/platform2/platform_base.py

@@ -0,0 +1,226 @@
+import sys
+import typing as t
+
+from pydantic import BaseModel
+
+from module.base.decorator import cached_property, del_cached_property
+from module.base.utils import SelectedGrids
+# from module.device.connection import Connection
+from module.device.method.utils import get_serial_pair
+from module.device.platform2.emulator_base import EmulatorInstanceBase, EmulatorManagerBase, remove_duplicated_path
+from module.logger import logger
+
+
+class EmulatorInfo(BaseModel):
+    emulator: str = ''
+    name: str = ''
+    path: str = ''
+
+    # For APIs of chinac.com, a phone cloud platform.
+    # access_key: SecretStr = ''
+    # secret: SecretStr = ''
+
+
+class PlatformBase(EmulatorManagerBase):
+    """
+    Base interface of a platform, platform can be various operating system or phone clouds.
+    For each `Platform` class, the following APIs must be implemented.
+    - all_emulators()
+    - all_emulator_instances()
+    - emulator_start()
+    - emulator_stop()
+    """
+
+    def emulator_start(self):
+        """
+        Start a emulator, until startup completed.
+        - Retry is required.
+        - Using bored sleep to wait startup is forbidden.
+        """
+        logger.info(f'Current platform {sys.platform} does not support emulator_start, skip')
+
+    def emulator_stop(self):
+        """
+        Stop a emulator.
+        """
+        logger.info(f'Current platform {sys.platform} does not support emulator_stop, skip')
+
+    @cached_property
+    def config_interface(self) -> dict:
+        result = {'emulator': 'auto',
+                  'name': '',
+                  'path': '',
+                  'serial': '127.0.0.1:16384'}
+        if hasattr(self, 'config'):
+            result = {
+                'emulator': self.config.script.device.emulatorinfo_type,
+                'name': self.config.script.device.emulatorinfo_name,
+                'path': self.config.script.device.emulatorinfo_path,
+                'serial': self.config.script.device.serial
+            }
+        return result
+
+    def _config_save_new(self, emulator: str, name: str, path: str):
+        if hasattr(self, 'config'):
+            self.config.script.device.emulatorinfo_type = emulator
+            self.config.script.device.emulatorinfo_name = name
+            self.config.script.device.emulatorinfo_path = path
+            self.config.save()
+
+    @cached_property
+    def emulator_info(self) -> EmulatorInfo:
+        emulator = self.config_interface['emulator']
+        if emulator == 'auto':
+            emulator = ''
+
+        def parse_info(value):
+            if isinstance(value, str):
+                value = value.strip().replace('\n', '')
+                if value in ['None', 'False', 'True']:
+                    value = ''
+                return value
+            else:
+                return ''
+
+        name = parse_info(self.config_interface['name'])
+        path = parse_info(self.config_interface['path'])
+
+        return EmulatorInfo(
+            emulator=emulator,
+            name=name,
+            path=path,
+        )
+
+    @cached_property
+    def emulator_instance(self) -> t.Optional[EmulatorInstanceBase]:
+        """
+        Returns:
+            EmulatorInstanceBase: Emulator instance or None
+        """
+        data = self.emulator_info
+        old_info = dict(
+            emulator=data.emulator,
+            path=data.path,
+            name=data.name,
+        )
+        # Redirect emulator-5554 to 127.0.0.1:5555
+        serial = self.config_interface['serial']
+        port_serial, _ = get_serial_pair(serial)
+        if port_serial is not None:
+            serial = port_serial
+
+        instance = self.find_emulator_instance(
+            serial=serial,
+            name=data.name,
+            path=data.path,
+            emulator=data.emulator,
+        )
+
+        # Write complete emulator data
+        if instance is not None:
+            new_info = dict(
+                emulator=instance.type,
+                path=instance.path,
+                name=instance.name,
+            )
+            if new_info != old_info:
+                self._config_save_new(emulator=instance.type, name=instance.name, path=instance.path)
+                del_cached_property(self, 'emulator_info')
+
+        return instance
+
+    def find_emulator_instance(
+            self,
+            serial: str,
+            name: str = None,
+            path: str = None,
+            emulator: str = None
+    ) -> t.Optional[EmulatorInstanceBase]:
+        """
+        Args:
+            serial: Serial like "127.0.0.1:5555"
+            name: Instance name like "Nougat64"
+            path: Emulator install path like "C:/Program Files/BlueStacks_nxt/HD-Player.exe"
+            emulator: Emulator type defined in Emulator class, like "BlueStacks5"
+
+        Returns:
+            EmulatorInstance: Emulator instance or None if no instances not found.
+        """
+        logger.hr('Find emulator instance', level=2)
+        instances = SelectedGrids(self.all_emulator_instances)
+        for instance in instances:
+            logger.info(instance)
+        search_args = dict(serial=serial)
+
+        # Search by serial
+        select = instances.select(**search_args)
+        if select.count == 0:
+            logger.warning(f'No emulator instance with {search_args}, serial invalid')
+            return None
+        if select.count == 1:
+            instance = select[0]
+            logger.hr('Emulator instance', level=2)
+            logger.info(f'Found emulator instance: {instance}')
+            return instance
+
+        # Multiple instances in given serial, search by name
+        if name:
+            search_args['name'] = name
+            select = instances.select(**search_args)
+            if select.count == 0:
+                logger.warning(f'No emulator instances with {search_args}, name invalid')
+                search_args.pop('name')
+            elif select.count == 1:
+                instance = select[0]
+                logger.hr('Emulator instance', level=2)
+                logger.info(f'Found emulator instance: {instance}')
+                return instance
+
+        # Multiple instances in given serial and name, search by path
+        if path:
+            search_args['path'] = path
+            select = instances.select(**search_args)
+            if select.count == 0:
+                logger.warning(f'No emulator instances with {search_args}, path invalid')
+                search_args.pop('path')
+            elif select.count == 1:
+                instance = select[0]
+                logger.hr('Emulator instance', level=2)
+                logger.info(f'Found emulator instance: {instance}')
+                return instance
+
+        # Multiple instances in given serial, name and path, search by emulator
+        if emulator:
+            search_args['type'] = emulator
+            select = instances.select(**search_args)
+            if select.count == 0:
+                logger.warning(f'No emulator instances with {search_args}, type invalid')
+                search_args.pop('type')
+            elif select.count == 1:
+                instance = select[0]
+                logger.hr('Emulator instance', level=2)
+                logger.info(f'Found emulator instance: {instance}')
+                return instance
+
+        # Still too many instances, search from running emulators
+        running = remove_duplicated_path(list(self.iter_running_emulator()))
+        logger.info('Running emulators')
+        for exe in running:
+            logger.info(exe)
+        if len(running) == 1:
+            logger.info('Only one running emulator')
+            # Same as searching path
+            search_args['path'] = running[0]
+            select = instances.select(**search_args)
+            if select.count == 0:
+                logger.warning(f'No emulator instances with {search_args}, path invalid')
+                search_args.pop('path')
+            elif select.count == 1:
+                instance = select[0]
+                logger.hr('Emulator instance', level=2)
+                logger.info(f'Found emulator instance: {instance}')
+                return instance
+
+        # Still too many instances
+        logger.warning(f'Found multiple emulator instances with {search_args}')
+        return None

+ 372 - 0
module/device/platform2/platform_windows.py

@@ -0,0 +1,372 @@
+import ctypes
+import re
+import subprocess
+import psutil
+from adbutils import AdbDevice, AdbClient
+
+from deploy.utils import DataProcessInfo
+from module.base.decorator import run_once
+from module.base.timer import Timer
+from module.device.handle import Handle
+from module.device.platform2.platform_base import PlatformBase
+from module.device.platform2.emulator_windows import Emulator, EmulatorInstance, EmulatorManager
+from module.logger import logger
+
+
+class EmulatorUnknown(Exception):
+    pass
+
+
+def get_focused_window():
+    return ctypes.windll.user32.GetForegroundWindow()
+
+
+def set_focus_window(hwnd):
+    ctypes.windll.user32.SetForegroundWindow(hwnd)
+
+
+def minimize_window(hwnd):
+    ctypes.windll.user32.ShowWindow(hwnd, 6)
+
+
+def get_window_title(hwnd):
+    """Returns the window title as a string."""
+    text_len_in_characters = ctypes.windll.user32.GetWindowTextLengthW(hwnd)
+    string_buffer = ctypes.create_unicode_buffer(
+        text_len_in_characters + 1)  # +1 for the \0 at the end of the null-terminated string.
+    ctypes.windll.user32.GetWindowTextW(hwnd, string_buffer, text_len_in_characters + 1)
+    return string_buffer.value
+
+
+def flash_window(hwnd, flash=True):
+    ctypes.windll.user32.FlashWindow(hwnd, flash)
+
+
+class AdbDeviceWithStatus(AdbDevice):
+    def __init__(self, client: AdbClient, serial: str, status: str):
+        self.status = status
+        super().__init__(client, serial)
+
+    def __str__(self):
+        return f'AdbDevice({self.serial}, {self.status})'
+
+    __repr__ = __str__
+
+    def __bool__(self):
+        return True
+
+class PlatformWindows(PlatformBase, EmulatorManager):
+    @classmethod
+    def execute(cls, command):
+        """
+        Args:
+            command (str):
+
+        Returns:
+            subprocess.Popen:
+        """
+        command = command.replace(r"\\", "/").replace("\\", "/").replace('"', '"')
+        logger.info(f'Execute: {command}')
+        return subprocess.Popen(command, close_fds=True)  # only work on Windows
+
+    @classmethod
+    def kill_process_by_regex(cls, regex: str) -> int:
+        """
+        Kill processes with cmdline match the given regex.
+
+        Args:
+            regex:
+
+        Returns:
+            int: Number of processes killed
+        """
+        count = 0
+
+        for proc in psutil.process_iter():
+            cmdline = DataProcessInfo(proc=proc, pid=proc.pid).cmdline
+            if re.search(regex, cmdline):
+                logger.info(f'Kill emulator: {cmdline}')
+                proc.kill()
+                count += 1
+
+        return count
+
+    def _emulator_start(self, instance: EmulatorInstance):
+        """
+        Start a emulator without error handling
+        """
+        exe: str = instance.emulator.path
+        if instance == Emulator.MuMuPlayer:
+            # NemuPlayer.exe
+            self.execute(exe)
+        elif instance == Emulator.MuMuPlayerX:
+            # NemuPlayer.exe -m nemu-12.0-x64-default
+            self.execute(f'"{exe}" -m {instance.name}')
+        elif instance == Emulator.MuMuPlayer12:
+            # MuMuPlayer.exe -v 0
+            if instance.MuMuPlayer12_id is None:
+                logger.warning(f'Cannot get MuMu instance index from name {instance.name}')
+            self.execute(f'"{exe}" -v {instance.MuMuPlayer12_id}')
+        elif instance == Emulator.LDPlayerFamily:
+            # ldconsole.exe launch --index 0
+            self.execute(f'"{Emulator.single_to_console(exe)}" launch --index {instance.LDPlayer_id}')
+        elif instance == Emulator.NoxPlayerFamily:
+            # Nox.exe -clone:Nox_1
+            self.execute(f'"{exe}" -clone:{instance.name}')
+        elif instance == Emulator.BlueStacks5:
+            # HD-Player.exe --instance Pie64
+            self.execute(f'"{exe}" --instance {instance.name}')
+        elif instance == Emulator.BlueStacks4:
+            # Bluestacks.exe -vmname Android_1
+            self.execute(f'"{exe}" -vmname {instance.name}')
+        elif instance == Emulator.MEmuPlayer:
+            # MEmu.exe MEmu_0
+            self.execute(f'"{exe}" {instance.name}')
+        else:
+            raise EmulatorUnknown(f'Cannot start an unknown emulator instance: {instance}')
+
+    def _emulator_stop(self, instance: EmulatorInstance):
+        """
+        Stop a emulator without error handling
+        """
+        exe: str = instance.emulator.path
+        if instance == Emulator.MuMuPlayer:
+            # MuMu6 does not have multi instance, kill one means kill all
+            # Has 4 processes
+            # "C:\Program Files\NemuVbox\Hypervisor\NemuHeadless.exe" --comment nemu-6.0-x64-default --startvm
+            # "E:\ProgramFiles\MuMu\emulator\nemu\EmulatorShell\NemuPlayer.exe"
+            # E:\ProgramFiles\MuMu\emulator\nemu\EmulatorShell\NemuService.exe
+            # "C:\Program Files\NemuVbox\Hypervisor\NemuSVC.exe" -Embedding
+            self.kill_process_by_regex(
+                rf'('
+                rf'NemuHeadless.exe'
+                rf'|NemuPlayer.exe\"'
+                rf'|NemuPlayer.exe$'
+                rf'|NemuService.exe'
+                rf'|NemuSVC.exe'
+                rf')'
+            )
+        elif instance == Emulator.MuMuPlayerX:
+            # MuMu X has 3 processes
+            # "E:\ProgramFiles\MuMu9\emulator\nemu9\EmulatorShell\NemuPlayer.exe" -m nemu-12.0-x64-default -s 0 -l
+            # "C:\Program Files\Muvm6Vbox\Hypervisor\Muvm6Headless.exe" --comment nemu-12.0-x64-default --startvm xxx
+            # "C:\Program Files\Muvm6Vbox\Hypervisor\Muvm6SVC.exe" --Embedding
+            self.kill_process_by_regex(
+                rf'('
+                rf'NemuPlayer.exe.*-m {instance.name}'
+                rf'|Muvm6Headless.exe'
+                rf'|Muvm6SVC.exe'
+                rf')'
+            )
+        elif instance == Emulator.MuMuPlayer12:
+            # MuMuManager.exe api -v 1 shutdown_player
+            if instance.MuMuPlayer12_id is None:
+                logger.warning(f'Cannot get MuMu instance index from name {instance.name}')
+            self.execute(f'"{Emulator.single_to_console(exe)}" api -v {instance.MuMuPlayer12_id} shutdown_player')
+        elif instance == Emulator.LDPlayerFamily:
+            # ldconsole.exe quit --index 0
+            self.execute(f'"{Emulator.single_to_console(exe)}" quit --index {instance.LDPlayer_id}')
+        elif instance == Emulator.NoxPlayerFamily:
+            # Nox.exe -clone:Nox_1 -quit
+            self.execute(f'"{exe}" -clone:{instance.name} -quit')
+        elif instance == Emulator.BlueStacks5:
+            # BlueStack has 2 processes
+            # C:\Program Files\BlueStacks_nxt_cn\HD-Player.exe --instance Pie64
+            # C:\Program Files\BlueStacks_nxt_cn\BstkSVC.exe -Embedding
+            self.kill_process_by_regex(
+                rf'('
+                rf'HD-Player.exe.*"--instance" "{instance.name}"'
+                rf')'
+            )
+        elif instance == Emulator.BlueStacks4:
+            # E:\Program Files (x86)\BluestacksCN\bsconsole.exe quit --name Android
+            self.execute(f'"{Emulator.single_to_console(exe)}" quit --name {instance.name}')
+        elif instance == Emulator.MEmuPlayer:
+            # F:\Program Files\Microvirt\MEmu\memuc.exe stop -n MEmu_0
+            self.execute(f'"{Emulator.single_to_console(exe)}" stop -n {instance.name}')
+        else:
+            raise EmulatorUnknown(f'Cannot stop an unknown emulator instance: {instance}')
+
+    def _emulator_function_wrapper(self, func: callable):
+        """
+        Args:
+            func (callable): _emulator_start or _emulator_stop
+
+        Returns:
+            bool: If success
+        """
+        try:
+            func(self.emulator_instance)
+            return True
+        except OSError as e:
+            msg = str(e)
+            # OSError: [WinError 740] 请求的操作需要提升。
+            if 'WinError 740' in msg:
+                logger.error('To start/stop MumuAppPlayer, ALAS needs to be run as administrator')
+        except EmulatorUnknown as e:
+            logger.error(e)
+        except Exception as e:
+            logger.exception(e)
+
+        logger.error(f'Emulator function {func.__name__}() failed')
+        return False
+
+    def emulator_start_watch(self):
+        """
+        Returns:
+            bool: True if startup completed
+                False if timeout
+        """
+        logger.hr('Emulator start', level=2)
+        current_window = get_focused_window()
+        serial = self.emulator_instance.serial
+        logger.info(f'Current window: {current_window}')
+
+        def adb_connect():
+            m = self.adb_client.connect(self.serial)
+            if 'connected' in m:
+                # Connected to 127.0.0.1:59865
+                # Already connected to 127.0.0.1:59865
+                return False
+            elif '(10061)' in m:
+                # cannot connect to 127.0.0.1:55555:
+                # No connection could be made because the target machine actively refused it. (10061)
+                return False
+            else:
+                return True
+
+        @run_once
+        def show_online(m):
+            logger.info(f'Emulator online: {m}')
+
+        @run_once
+        def show_ping(m):
+            logger.info(f'Command ping: {m}')
+
+        @run_once
+        def show_package(m):
+            logger.info(f'Found azurlane packages: {m}')
+
+        interval = Timer(1).start()
+        timeout = Timer(180).start()
+        struct_window = Timer(10)
+        new_window = 0
+        while 1:
+            interval.wait()
+            interval.reset()
+            if timeout.reached():
+                logger.warning(f'Emulator start timeout')
+                return False
+
+            # Check emulator window showing up
+            # logger.info([get_focused_window(), get_window_title(get_focused_window())])
+            if current_window != 0 and new_window == 0:
+                new_window = get_focused_window()
+                if current_window != new_window:
+                    logger.info(f'New window showing up: {new_window}, focus back')
+                    set_focus_window(current_window)
+                else:
+                    new_window = 0
+
+            # Check device connection
+            devices = self.list_device().select(serial=serial)
+            # logger.info(devices)
+            if devices:
+                device: AdbDeviceWithStatus = devices.first_or_none()
+                if device.status == 'device':
+                    # Emulator online
+                    pass
+                if device.status == 'offline':
+                    self.adb_client.disconnect(serial)
+                    adb_connect()
+                    continue
+            else:
+                # Try to connect
+                adb_connect()
+                continue
+            show_online(devices.first_or_none())
+
+            # Check command availability
+            try:
+                pong = self.adb_shell(['echo', 'pong'])
+            except Exception as e:
+                logger.info(e)
+                continue
+            show_ping(pong)
+
+            # Check game package
+            packages = self.list_app_packages(show_log=False)
+            if len(packages):
+                pass
+            else:
+                continue
+            show_package(packages)
+
+            # Check Window structure
+            if not struct_window.started():
+                struct_window.start()
+            elif struct_window.reached():
+                break
+            if new_window == 0:
+                continue
+            if not Handle.handle_has_children(hwnd=new_window):
+                continue
+
+            # All check passed
+            break
+
+        if new_window != 0 and new_window != current_window:
+            logger.info(f'Minimize new window: {new_window}')
+            minimize_window(new_window)
+        if current_window:
+            logger.info(f'De-flash current window: {current_window}')
+            flash_window(current_window, flash=False)
+        if new_window:
+            logger.info(f'Flash new window: {new_window}')
+            flash_window(new_window, flash=True)
+        logger.info('Emulator start completed')
+        return True
+
+    def emulator_start(self):
+        logger.hr('Emulator start', level=1)
+        for _ in range(3):
+            # Stop
+            if not self._emulator_function_wrapper(self._emulator_stop):
+                return False
+            # Start
+            if self._emulator_function_wrapper(self._emulator_start):
+                # Success
+                self.emulator_start_watch()
+                return True
+            else:
+                # Failed to start, stop and start again
+                if self._emulator_function_wrapper(self._emulator_stop):
+                    continue
+                else:
+                    return False
+
+        logger.error('Failed to start emulator 3 times, stopped')
+        return False
+
+    def emulator_stop(self):
+        logger.hr('Emulator stop', level=1)
+        for _ in range(3):
+            # Stop
+            if self._emulator_function_wrapper(self._emulator_stop):
+                # Success
+                return True
+            else:
+                # Failed to stop, start and stop again
+                if self._emulator_function_wrapper(self._emulator_start):
+                    continue
+                else:
+                    return False
+
+        logger.error('Failed to stop emulator 3 times, stopped')
+        return False
+
+
+if __name__ == '__main__':
+    self = PlatformWindows()
+    d = self.emulator_instance
+    print(d)

+ 54 - 0
module/device/platform2/utils.py

@@ -0,0 +1,54 @@
+import os
+from typing import Callable, Generic, TypeVar
+
+T = TypeVar("T")
+
+
+class cached_property(Generic[T]):
+    """
+    cached-property from https://github.com/pydanny/cached-property
+    Add typing support
+
+    A property that is only computed once per instance and then replaces itself
+    with an ordinary attribute. Deleting the attribute resets the property.
+    Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76
+    """
+
+    def __init__(self, func: Callable[..., T]):
+        self.func = func
+
+    def __get__(self, obj, cls) -> T:
+        if obj is None:
+            return self
+
+        value = obj.__dict__[self.func.__name__] = self.func(obj)
+        return value
+
+
+def iter_folder(folder, is_dir=False, ext=None):
+    """
+    Args:
+        folder (str):
+        is_dir (bool): True to iter directories only
+        ext (str): File extension, such as `.yaml`
+
+    Yields:
+        str: Absolute path of files
+    """
+    try:
+        files = os.listdir(folder)
+    except FileNotFoundError:
+        return
+
+    for file in files:
+        sub = os.path.join(folder, file)
+        if is_dir:
+            if os.path.isdir(sub):
+                yield sub.replace('\\\\', '/').replace('\\', '/')
+        elif ext is not None:
+            if not os.path.isdir(sub):
+                _, extension = os.path.splitext(file)
+                if extension == ext:
+                    yield os.path.join(folder, file).replace('\\\\', '/').replace('\\', '/')
+        else:
+            yield os.path.join(folder, file).replace('\\\\', '/').replace('\\', '/')

+ 25 - 3
tasks/Script/config_device.py

@@ -2,6 +2,7 @@
 # @author runhey
 # github https://github.com/runhey
 from enum import Enum
+from typing import Union
 from pydantic import BaseModel, ValidationError, validator, Field
 
 from module.logger import logger
@@ -31,14 +32,28 @@ class ControlMethod(str, Enum):
     MINITOUCH = 'minitouch'
     WINDOW_MESSAGE = 'window_message'
 
+class EmulatorInfoType(str, Enum):
+    # module.device.platform2.emulator_base.EmulatorBase
+    AUTO = 'auto'
+    NoxPlayer = 'NoxPlayer'
+    NoxPlayer64 = 'NoxPlayer64'
+    BlueStacks4 = 'BlueStacks4'
+    BlueStacks5 = 'BlueStacks5'
+    BlueStacks4HyperV = 'BlueStacks4HyperV'
+    BlueStacks5HyperV = 'BlueStacks5HyperV'
+    LDPlayer3 = 'LDPlayer3'
+    LDPlayer4 = 'LDPlayer4'
+    LDPlayer9 = 'LDPlayer9'
+    MuMuPlayer = 'MuMuPlayer'
+    MuMuPlayerX = 'MuMuPlayerX'
+    MuMuPlayer12 = 'MuMuPlayer12'
+    MEmuPlayer = 'MEmuPlayer'
+
 class Device(BaseModel):
     serial: str = Field(default="auto",
                         description='serial_help')
     handle: str = Field(default='',
                         description='handle_help')
-    emulatorinfo_path: str = Field(default='',
-                        description='emulatorinfo_path_help')
-    # 举例, E:\ProgramFiles\MuMuPlayer-12.0\shell\MuMuPlayer.exe
     package_name: PackageName = Field(title='Package Name',
                                       default=PackageName.AUTO,
                                       description='package_name_help')
@@ -48,6 +63,13 @@ class Device(BaseModel):
                                           description='control_method_help')
     adb_restart: bool = Field(default=False,
                               description='adb_restart_help')
+    emulatorinfo_type: Union[EmulatorInfoType, str] = Field(default=EmulatorInfoType.AUTO,
+                                                description='emulatorinfo_type_help')
+    emulatorinfo_name: str = Field(default='',
+                                   description='emulatorinfo_name_help')
+    emulatorinfo_path: str = Field(default='',
+                                   description='emulatorinfo_path_help')
+    # 举例, E:\ProgramFiles\MuMuPlayer-12.0\shell\MuMuPlayer.exe