runhey 3 лет назад
Родитель
Сommit
35f5b41cc4

+ 79 - 0
deploy/adb.py

@@ -0,0 +1,79 @@
+# This Python file uses the following encoding: utf-8
+# copy from alas https://github.com/LmeSzinc/AzurLaneAutoScript
+import logging
+
+from deploy.config import DeployConfig
+from deploy.emulator import EmulatorConnect
+from deploy.logger import logger
+from deploy.utils import *
+
+def show_fix_tip(module):
+    logger.info(f"""
+    To fix this:
+    1. Open console.bat
+    2. Execute the following commands:
+        pip uninstall -y {module}
+        pip install --no-cache-dir {module}
+    3. Re-open Alas.exe
+    """)
+
+
+class AdbManager(DeployConfig):
+    @cached_property
+    def adb(self):
+        return self.filepath('AdbExecutable')
+
+    def adb_install(self):
+        logger.hr('Start ADB service', 0)
+
+        emulator = EmulatorConnect(adb=self.adb)
+        if self.ReplaceAdb:
+            logger.hr('Replace ADB', 1)
+            emulator.adb_replace()
+        elif self.AutoConnect:
+            logger.hr('ADB Connect', 1)
+            emulator.brute_force_connect()
+
+        if self.InstallUiautomator2:
+            logger.hr('Uiautomator2 Init', 1)
+            try:
+                import adbutils
+                from uiautomator2 import init
+            except ModuleNotFoundError as e:
+                message = str(e)
+                for module in ['apkutils2', 'progress']:
+                    # ModuleNotFoundError: No module named 'apkutils2'
+                    # ModuleNotFoundError: No module named 'progress.bar'
+                    if module in message:
+                        show_fix_tip(module)
+                        exit(1)
+                raise
+
+            # Remove global proxies, or uiautomator2 will go through it
+            for k in list(os.environ.keys()):
+                if k.lower().endswith('_proxy'):
+                    del os.environ[k]
+
+            for device in adbutils.adb.iter_device():
+                initer = init.Initer(device, loglevel=logging.DEBUG)
+                # MuMu X has no ro.product.cpu.abi, pick abi from ro.product.cpu.abilist
+                if initer.abi not in ['x86_64', 'x86', 'arm64-v8a', 'armeabi-v7a', 'armeabi']:
+                    initer.abi = initer.abis[0]
+                initer.set_atx_agent_addr('127.0.0.1:7912')
+
+                for _ in range(2):
+                    try:
+                        initer.install()
+                        break
+                    except AssertionError:
+                        logger.info(f'AssertionError when installing uiautomator2 on device {device.serial}')
+                        logger.info('If you are using BlueStacks or LD player or WSA, '
+                                    'please enable ADB in the settings of your emulator')
+                        exit(1)
+                    except ConnectionError:
+                        if _ == 1:
+                            raise
+                        init.GITHUB_BASEURL = 'http://tool.appetizer.io/openatx'
+
+                initer._device.shell(["rm", "/data/local/tmp/minicap"])
+                initer._device.shell(["rm", "/data/local/tmp/minicap.so"])

+ 164 - 0
deploy/config.py

@@ -0,0 +1,164 @@
+# This Python file uses the following encoding: utf-8
+# copy from alas https://github.com/LmeSzinc/AzurLaneAutoScript
+import copy
+from typing import Optional, Union
+
+from deploy.logger import logger
+from deploy.utils import *
+
+
+class ExecutionError(Exception):
+    pass
+
+
+class ConfigModel:
+    # Git
+    Repository: str = "https://e.coding.net/onmyojiautoscript/oas/OnmyojiAutoScript.git"
+    Branch: str = "master"
+    GitExecutable: str = "./toolkit/Git/mingw64/bin/git.exe"
+    GitProxy: Optional[str] = None
+    SSLVerify: bool = False
+    AutoUpdate: bool = True
+    KeepLocalChanges: bool = False
+
+    # Python
+    PythonExecutable: str = "./toolkit/python.exe"
+    PypiMirror: Optional[str] = None
+    InstallDependencies: bool = True
+    RequirementsFile: str = "requirements.txt"
+
+    # Adb
+    AdbExecutable: str = "./toolkit/Lib/site-packages/adbutils/binaries/adb.exe"
+    ReplaceAdb: bool = True
+    AutoConnect: bool = True
+    InstallUiautomator2: bool = True
+
+    # Ocr
+    UseOcrServer: bool = False
+    StartOcrServer: bool = False
+    OcrServerPort: int = 22268
+    OcrClientAddress: str = "127.0.0.1:22268"
+
+    # Update
+    EnableReload: bool = True
+    CheckUpdateInterval: int = 5
+    AutoRestartTime: str = "03:50"
+
+    # Misc
+    DiscordRichPresence: bool = False
+
+    # Remote Access
+    EnableRemoteAccess: bool = False
+    SSHUser: Optional[str] = None
+    SSHServer: Optional[str] = None
+    SSHExecutable: Optional[str] = None
+
+    # Webui
+    WebuiHost: str = "0.0.0.0"
+    WebuiPort: int = 22267
+    Language: str = "en-US"
+    Theme: str = "default"
+    DpiScaling: bool = True
+    Password: Optional[str] = None
+    CDN: Union[str, bool] = False
+    Run: Optional[str] = None
+
+
+class DeployConfig(ConfigModel):
+    def __init__(self, file=DEPLOY_CONFIG):
+        """
+        Args:
+            file (str): User deploy config.
+        """
+        self.file = file
+        self.config = {}
+        self.read()
+        self.write()
+        self.show_config()
+
+    def show_config(self):
+        logger.hr("Show deploy config", 1)
+        for k, v in self.config.items():
+            if k in ("Password", "SSHUser"):
+                continue
+            if self.config_template[k] == v:
+                continue
+            logger.info(f"{k}: {v}")
+
+        logger.info(f"Rest of the configs are the same as default")
+
+    def read(self):
+        self.config = poor_yaml_read(DEPLOY_TEMPLATE)
+        self.config_template = copy.deepcopy(self.config)
+        self.config.update(poor_yaml_read(self.file))
+
+        for key, value in self.config.items():
+            if hasattr(self, key):
+                super().__setattr__(key, value)
+
+    def write(self):
+        poor_yaml_write(self.config, self.file)
+
+    def filepath(self, key):
+        """
+        Args:
+            key (str):
+
+        Returns:
+            str: Absolute filepath.
+        """
+        return (
+            os.path.abspath(os.path.join(self.root_filepath, self.config[key]))
+            .replace(r"\\", "/")
+            .replace("\\", "/")
+            .replace('"', '"')
+        )
+
+    @cached_property
+    def root_filepath(self):
+        return (
+            os.path.abspath(os.path.join(os.path.dirname(__file__), "../"))
+            .replace(r"\\", "/")
+            .replace("\\", "/")
+            .replace('"', '"')
+        )
+
+    def execute(self, command, allow_failure=False, output=True):
+        """
+        Args:
+            command (str):
+            allow_failure (bool):
+            output(bool):
+
+        Returns:
+            bool: If success.
+                Terminate installation if failed to execute and not allow_failure.
+        """
+        command = command.replace(r"\\", "/").replace("\\", "/").replace('"', '"')
+        if not output:
+            command = command + ' >nul 2>nul'
+        logger.info(command)
+        error_code = os.system(command)
+        if error_code:
+            if allow_failure:
+                logger.info(f"[ allowed failure ], error_code: {error_code}")
+                return False
+            else:
+                logger.info(f"[ failure ], error_code: {error_code}")
+                self.show_error(command)
+                raise ExecutionError
+        else:
+            logger.info(f"[ success ]")
+            return True
+
+    def show_error(self, command=None):
+        logger.hr("Update failed", 0)
+        self.show_config()
+        logger.info("")
+        logger.info(f"Last command: {command}")
+        logger.info(
+            "Please check your deploy settings in config/deploy.yaml "
+            "and re-open Alas.exe"
+        )
+        logger.info("Take the screenshot of entire window if you need help")
+

+ 379 - 0
deploy/emulator.py

@@ -0,0 +1,379 @@
+import asyncio
+import filecmp
+import os
+import re
+import shutil
+import subprocess
+import winreg
+
+from deploy.logger import logger
+from deploy.utils import cached_property
+
+asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
+
+
+class VirtualBoxEmulator:
+    UNINSTALL_REG = "SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
+    UNINSTALL_REG_2 = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
+
+    def __init__(self, name, root_path, adb_path, vbox_path, vbox_name):
+        """
+        Args:
+            name (str): Emulator name in windows uninstall list.
+            root_path (str): Relative path from uninstall.exe to emulator installation folder.
+            adb_path (str, list[str]): Relative path to adb.exe. List of str if there are multiple adb in emulator.
+            vbox_path (str): Relative path to virtual box folder.
+            vbox_name (str): Regular Expression to match the name of .vbox file.
+        """
+        self.name = name
+        self.root_path = root_path
+        self.adb_path = adb_path if isinstance(adb_path, list) else [adb_path]
+        self.vbox_path = vbox_path
+        self.vbox_name = vbox_name
+
+    @cached_property
+    def root(self):
+        """
+        Returns:
+            str: Root installation folder of emulator.
+
+        Raises:
+            FileNotFoundError: If emulator not installed.
+        """
+        if self.name == 'LDPlayer4':
+            root = self.get_install_dir_from_reg('SOFTWARE\\leidian\\ldplayer', 'InstallDir')
+            if root is not None:
+                return root
+        if self.name == 'LDPlayer9':
+            root = self.get_install_dir_from_reg('SOFTWARE\\leidian\\ldplayer9', 'InstallDir')
+            if root is not None:
+                return root
+
+        try:
+            reg = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, f'{self.UNINSTALL_REG}\\{self.name}', 0)
+        except FileNotFoundError:
+            reg = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, f'{self.UNINSTALL_REG_2}\\{self.name}', 0)
+        res = winreg.QueryValueEx(reg, 'UninstallString')[0]
+
+        file = re.search('"(.*?)"', res)
+        file = file.group(1) if file else res
+        root = os.path.abspath(os.path.join(os.path.dirname(file), self.root_path))
+        return root
+
+    def get_install_dir_from_reg(self, path, key):
+        """
+        Args:
+            path (str): f'SOFTWARE\\leidian\\ldplayer'
+            key (str): 'InstallDir'
+
+        Returns:
+            str: Installation dir or None
+        """
+        try:
+            reg = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path, 0)
+            root = winreg.QueryValueEx(reg, key)[0]
+            if os.path.exists(root):
+                return root
+        except FileNotFoundError:
+            pass
+        try:
+            reg = winreg.OpenKey(winreg.HKEY_CURRENT_USER, path, 0)
+            root = winreg.QueryValueEx(reg, key)[0]
+            if os.path.exists(root):
+                return root
+        except FileNotFoundError:
+            pass
+
+        return None
+
+    @cached_property
+    def adb_binary(self):
+        return [os.path.abspath(os.path.join(self.root, a)) for a in self.adb_path]
+
+    @cached_property
+    def adb_backup(self):
+        files = []
+        for adb in self.adb_binary:
+            for n in range(10):
+                backup = f'{adb}.bak{n}' if n else f'{adb}.bak'
+                if os.path.exists(backup):
+                    continue
+                else:
+                    files.append(backup)
+                    break
+        return files
+
+    @cached_property
+    def serial(self):
+        """
+        Returns:
+            list[str]: Such as ['127.0.0.1:62001', '127.0.0.1:62025']
+        """
+        vbox = []
+        for path, folders, files in os.walk(os.path.join(self.root, self.vbox_path)):
+            for file in files:
+                if re.match(self.vbox_name, file):
+                    file = os.path.join(path, file)
+                    vbox.append(file)
+
+        serial = []
+        for file in vbox:
+            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 = re.search('<*?hostport="(.*?)".*?guestport="5555"/>', line)
+                    if res:
+                        serial.append(f'127.0.0.1:{res.group(1)}')
+
+        return serial
+
+    def adb_replace(self, adb):
+        """
+        Backup the adb in emulator folder to xxx.bak, replace it with your adb.
+        Need to call `adb kill-server` before replacing.
+
+        Args:
+            adb (str): Absolute path to adb.exe
+        """
+        for ori, bak in zip(self.adb_binary, self.adb_backup):
+            logger.info(f'Replacing {ori}')
+            if os.path.exists(ori):
+                if filecmp.cmp(adb, ori, shallow=True):
+                    logger.info(f'{adb} is same as {ori}, skip')
+                else:
+                    logger.info(f'{ori} -----> {bak}')
+                    shutil.move(ori, bak)
+                    logger.info(f'{adb} -----> {ori}')
+                    shutil.copy(adb, ori)
+            else:
+                logger.info(f'{ori} not exists, skip')
+
+    def adb_recover(self):
+        """ Revert adb replacement """
+        for ori in self.adb_binary:
+            logger.info(f'Recovering {ori}')
+            bak = f'{ori}.bak'
+            if os.path.exists(bak):
+                logger.info(f'Delete {ori}')
+                if os.path.exists(ori):
+                    os.remove(ori)
+                logger.info(f'{bak} -----> {ori}')
+                shutil.move(bak, ori)
+            else:
+                logger.info(f'Not exists {bak}, skip')
+
+
+# NoxPlayer 夜神模拟器
+nox_player = VirtualBoxEmulator(
+    name="Nox",
+    root_path=".",
+    adb_path=["./adb.exe", "./nox_adb.exe"],
+    vbox_path="./BignoxVMS",
+    vbox_name='.*.vbox$'
+)
+nox_player_64 = VirtualBoxEmulator(
+    name="Nox64",
+    root_path=".",
+    adb_path=["./adb.exe", "./nox_adb.exe"],
+    vbox_path="./BignoxVMS",
+    vbox_name='.*.vbox$'
+)
+# LDPlayer 雷电模拟器
+ld_player = VirtualBoxEmulator(
+    name="LDPlayer",
+    root_path=".",
+    adb_path="./adb.exe",
+    vbox_path="./vms",
+    vbox_name='.*.vbox$'
+)
+ld_player_4 = VirtualBoxEmulator(
+    name="LDPlayer4",
+    root_path=".",
+    adb_path="./adb.exe",
+    vbox_path="./vms",
+    vbox_name='.*.vbox$'
+)
+ld_player_9 = VirtualBoxEmulator(
+    name="LDPlayer9",
+    root_path=".",
+    adb_path="./adb.exe",
+    vbox_path="./vms",
+    vbox_name='.*.vbox$'
+)
+# MemuPlayer 逍遥模拟器
+memu_player = VirtualBoxEmulator(
+    name="MEmu",
+    root_path="../",
+    adb_path="./adb.exe",
+    vbox_path="./MemuHyperv VMs",
+    vbox_name='.*.memu$'
+)
+# MumuPlayer MuMu模拟器
+mumu_player = VirtualBoxEmulator(
+    name="Nemu",
+    root_path=".",
+    adb_path="./vmonitor/bin/adb_server.exe",
+    vbox_path="./vms",
+    vbox_name='.*.nemu$'
+)
+mumu12_player = VirtualBoxEmulator(
+    name="Nemu12",
+    root_path=".",
+    adb_path="./shell/adb.exe",
+    vbox_path="./vms",
+    vbox_name='.*.nemu$'
+)
+
+class EmulatorConnect:
+    SUPPORTED_EMULATORS = [
+        nox_player,
+        nox_player_64,
+        ld_player,
+        ld_player_4,
+        ld_player_9,
+        memu_player,
+        mumu_player,
+        mumu12_player
+    ]
+
+    def __init__(self, adb='adb.exe'):
+        self.adb_binary = adb
+
+    def _execute(self, cmd, timeout=10, output=True):
+        """
+        Returns:
+            Object: Stdout(str) of cmd if output,
+                    return code(int) of cmd if not output.
+        """
+        if not output:
+            cmd.extend(['>nul', '2>nul'])
+        logger.info(' '.join(cmd))
+        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
+        try:
+            stdout, stderr = process.communicate(timeout=timeout)
+            ret_code = process.returncode
+        except subprocess.TimeoutExpired:
+            process.kill()
+            stdout, stderr = process.communicate()
+            ret_code = 1
+            logger.info(f'TimeoutExpired, stdout={stdout}, stderr={stderr}')
+        if output:
+            return stdout
+        else:
+            return ret_code
+
+    @cached_property
+    def emulators(self):
+        """
+        Returns:
+            list: List of installed emulators on current computer.
+        """
+        emulators = []
+        for emulator in self.SUPPORTED_EMULATORS:
+            try:
+                serial = emulator.serial
+                emulators.append(emulator)
+            except FileNotFoundError:
+                continue
+            if len(serial):
+                logger.info(f'Emulator {emulator.name} found, instances: {serial}')
+
+        return emulators
+
+    def devices(self):
+        """
+        Returns:
+            list[str]: Connected devices in adb
+        """
+        result = self._execute([self.adb_binary, 'devices']).decode()
+        devices = []
+        for line in result.replace('\r\r\n', '\n').replace('\r\n', '\n').split('\n'):
+            if line.startswith('List') or '\t' not in line:
+                continue
+            serial, status = line.split('\t')
+            if status == 'device':
+                devices.append(serial)
+
+        logger.info(f'Devices: {devices}')
+        return devices
+
+    def adb_kill(self):
+        # self._execute([self.adb_binary, 'devices'])
+        # self._execute([self.adb_binary, 'kill-server'])
+
+        # Just kill it, because some adb don't obey.
+        logger.info('Kill all known ADB')
+        for exe in [
+            # Most emulator use this
+            'adb.exe',
+            # NoxPlayer 夜神模拟器
+            'nox_adb.exe',
+            # MumuPlayer MuMu模拟器
+            'adb_server.exe',
+            # Bluestacks 蓝叠模拟器
+            'HD-Adb.exe'
+        ]:
+            ret_code = self._execute(['taskkill', '/f', '/im', exe], output=False)
+            if ret_code == 0:
+                logger.info(f'Task {exe} killed')
+            elif ret_code == 128:
+                logger.info(f'Task {exe} not found')
+            else:
+                logger.info(f'Error occurred when killing task {exe}, return code {ret_code}')
+
+    @cached_property
+    def serial(self):
+        """
+        Returns:
+            list[str]: All available emulator serial on current computer.
+        """
+        serial = ['127.0.0.1:7555']
+        for emulator in self.emulators:
+            serial += emulator.serial
+            for s in emulator.serial:
+                ip, port = s.split(':')
+                port = int(port) - 1
+                if 5554 <= int(port) < 5600:
+                    serial.append(f'emulator-{port}')
+
+        return serial
+
+    def brute_force_connect(self):
+        """ Brute-force connect all available emulator instances """
+        self.devices()
+
+        async def connect():
+            await asyncio.gather(
+                *[asyncio.create_subprocess_exec(self.adb_binary, 'connect', serial) for serial in self.serial]
+            )
+
+        asyncio.run(connect())
+
+        return self.devices()
+
+    def adb_replace(self, adb=None):
+        """
+        Different version of ADB will kill each other when starting.
+        Chinese emulators (NoxPlayer, LDPlayer, MemuPlayer, MuMuPlayer) use their own adb,
+        instead of the one in system PATH, so when they start they kill the adb.exe Alas is using.
+        Replacing the ADB in emulator is the simplest way to solve this.
+
+        Args:
+            adb (str): Absolute path to adb.exe
+        """
+        self.adb_kill()
+        for emulator in self.emulators:
+            emulator.adb_replace(adb if adb is not None else self.adb_binary)
+        self.brute_force_connect()
+
+    def adb_recover(self):
+        """ Revert adb replacement """
+        self.adb_kill()
+        for emulator in self.emulators:
+            emulator.adb_recover()
+        self.brute_force_connect()
+
+
+if __name__ == '__main__':
+    emu = EmulatorConnect()
+    logger.info(emu.brute_force_connect())

+ 11 - 0
deploy/fluentui.py

@@ -0,0 +1,11 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+
+from deploy.config import DeployConfig
+from deploy.logger import logger
+from deploy.utils import *
+
+
+class FluentuiManager(DeployConfig):
+        pass

+ 95 - 0
deploy/git.py

@@ -0,0 +1,95 @@
+# This Python file uses the following encoding: utf-8
+# copy from alas https://github.com/LmeSzinc/AzurLaneAutoScript
+from deploy.config import DeployConfig
+from deploy.logger import logger
+from deploy.utils import *
+
+
+class GitManager(DeployConfig):
+    @cached_property
+    def git(self):
+        return self.filepath('GitExecutable')
+
+    @staticmethod
+    def remove(file):
+        try:
+            os.remove(file)
+            logger.info(f'Removed file: {file}')
+        except FileNotFoundError:
+            logger.info(f'File not found: {file}')
+
+    def git_repository_init(
+            self, repo, source='origin', branch='master',
+            proxy='', ssl_verify=True, keep_changes=False
+    ):
+        logger.hr('Git Init', 1)
+        if not self.execute(f'"{self.git}" init', allow_failure=True):
+            self.remove('./.git/config')
+            self.remove('./.git/index')
+            self.remove('./.git/HEAD')
+            self.execute(f'"{self.git}" init')
+
+        logger.hr('Set Git Proxy', 1)
+        if proxy:
+            self.execute(f'"{self.git}" config --local http.proxy {proxy}')
+            self.execute(f'"{self.git}" config --local https.proxy {proxy}')
+        else:
+            self.execute(f'"{self.git}" config --local --unset http.proxy', allow_failure=True)
+            self.execute(f'"{self.git}" config --local --unset https.proxy', allow_failure=True)
+
+        if ssl_verify:
+            self.execute(f'"{self.git}" config --local http.sslVerify true', allow_failure=True)
+        else:
+            self.execute(f'"{self.git}" config --local http.sslVerify false', allow_failure=True)
+
+        logger.hr('Set Git Repository', 1)
+        if not self.execute(f'"{self.git}" remote set-url {source} {repo}', allow_failure=True):
+            self.execute(f'"{self.git}" remote add {source} {repo}')
+
+        logger.hr('Fetch Repository Branch', 1)
+        self.execute(f'"{self.git}" fetch {source} {branch}')
+
+        logger.hr('Pull Repository Branch', 1)
+        # Remove git lock
+        for lock_file in [
+            './.git/index.lock',
+            './.git/HEAD.lock',
+            './.git/refs/heads/master.lock',
+        ]:
+            if os.path.exists(lock_file):
+                logger.info(f'Lock file {lock_file} exists, removing')
+                os.remove(lock_file)
+        if keep_changes:
+            if self.execute(f'"{self.git}" stash', allow_failure=True):
+                self.execute(f'"{self.git}" pull --ff-only {source} {branch}')
+                if self.execute(f'"{self.git}" stash pop', allow_failure=True):
+                    pass
+                else:
+                    # No local changes to existing files, untracked files not included
+                    logger.info('Stash pop failed, there seems to be no local changes, skip instead')
+            else:
+                logger.info('Stash failed, this may be the first installation, drop changes instead')
+                self.execute(f'"{self.git}" reset --hard {source}/{branch}')
+                self.execute(f'"{self.git}" pull --ff-only {source} {branch}')
+        else:
+            self.execute(f'"{self.git}" reset --hard {source}/{branch}')
+            self.execute(f'"{self.git}" pull --ff-only {source} {branch}')
+
+        logger.hr('Show Version', 1)
+        self.execute(f'"{self.git}" --no-pager log --no-merges -1')
+
+    def git_install(self):
+        logger.hr('Update Alas', 0)
+
+        if not self.AutoUpdate:
+            logger.info('AutoUpdate is disabled, skip')
+            return
+
+        self.git_repository_init(
+            repo=self.Repository,
+            source='origin',
+            branch=self.Branch,
+            proxy=self.GitProxy,
+            ssl_verify=self.SSLVerify,
+            keep_changes=self.KeepLocalChanges,
+        )

+ 4 - 5
deploy/installer.py

@@ -3,20 +3,19 @@ from deploy.patch import pre_checks
 pre_checks()
 
 from deploy.adb import AdbManager
-from deploy.alas import AlasManager
-from deploy.app import AppManager
+from deploy.process import ProcessManager
+from deploy.fluentui import FluentuiManager
 from deploy.config import ExecutionError
 from deploy.git import GitManager
 from deploy.pip import PipManager
 
 
-class Installer(GitManager, PipManager, AdbManager, AppManager, AlasManager):
+class Installer(GitManager, PipManager, AdbManager, FluentuiManager, ProcessManager):
     def install(self):
         try:
             self.git_install()
-            self.alas_kill()
+            self.process_kill()
             self.pip_install()
-            self.app_update()
             self.adb_install()
         except ExecutionError:
             exit(1)

+ 1 - 1
deploy/launcher/oas-gui.bat

@@ -13,7 +13,7 @@ set "_GitBin=%_root%\toolkit\Git\mingw64\bin"
 set "_adbBin=%_root%\toolkit\Lib\site-packages\adbutils\binaries"
 set "PATH=%_root%\toolkit\alias;%_root%\toolkit\command;%_pyBin%;%_pyBin%\Scripts;%_GitBin%;%_adbBin%;%PATH%"
 
-title Oas Updater
+title oas Updater
 python -m deploy.installer
 if %errorlevel% neq 0 (
     pause > nul

+ 54 - 0
deploy/pip.py

@@ -0,0 +1,54 @@
+# This Python file uses the following encoding: utf-8
+# copy from alas https://github.com/LmeSzinc/AzurLaneAutoScript
+from urllib.parse import urlparse
+
+from deploy.config import DeployConfig
+from deploy.logger import logger
+from deploy.utils import *
+
+
+class PipManager(DeployConfig):
+    @cached_property
+    def python(self):
+        return self.filepath("PythonExecutable")
+
+    @cached_property
+    def requirements_file(self):
+        if self.RequirementsFile == 'requirements.txt':
+            return 'requirements.txt'
+        else:
+            return self.filepath("RequirementsFile")
+
+    @cached_property
+    def pip(self):
+        return f'"{self.python}" -m pip'
+
+    def pip_install(self):
+        logger.hr('Update Dependencies', 0)
+
+        if not self.InstallDependencies:
+            logger.info('InstallDependencies is disabled, skip')
+            return
+
+        logger.hr('Check Python', 1)
+        self.execute(f'"{self.python}" --version')
+
+        arg = []
+        if self.PypiMirror:
+            mirror = self.PypiMirror
+            arg += ['-i', mirror]
+            # Trust http mirror or skip ssl verify
+            if 'http:' in mirror or not self.SSLVerify:
+                arg += ['--trusted-host', urlparse(mirror).hostname]
+        elif not self.SSLVerify:
+            arg += ['--trusted-host', 'pypi.org']
+            arg += ['--trusted-host', 'files.pythonhosted.org']
+
+        # Don't update pip, just leave it.
+        # logger.hr('Update pip', 1)
+        # self.execute(f'"{self.pip}" install --upgrade pip{arg}')
+        arg += ['--disable-pip-version-check']
+
+        logger.hr('Update Dependencies', 1)
+        arg = ' ' + ' '.join(arg) if arg else ''
+        self.execute(f'{self.pip} install -r {self.requirements_file}{arg}')

+ 68 - 0
deploy/process.py

@@ -0,0 +1,68 @@
+# This Python file uses the following encoding: utf-8
+# copy from alas https://github.com/LmeSzinc/AzurLaneAutoScript
+from deploy.config import DeployConfig
+from deploy.logger import logger
+from deploy.utils import *
+
+
+class ProcessManager(DeployConfig):
+    @cached_property
+    def process_folder(self):
+        return [
+            self.filepath("PythonExecutable"),
+            self.root_filepath
+        ]
+
+    @cached_property
+    def self_pid(self):
+        return os.getpid()
+
+    def iter_process_by_name(self, name):
+        """
+        Args:
+            name (str): process name, such as 'alas.exe'
+
+        Yields:
+            str, str, str: executable_path, process_name, process_id
+        """
+        try:
+            from win32com.client import GetObject
+        except ModuleNotFoundError:
+            logger.info('pywin32 not installed, skip')
+            return False
+
+        try:
+            wmi = GetObject('winmgmts:')
+            processes = wmi.InstancesOf('Win32_Process')
+            for p in processes:
+                executable_path = p.Properties_["ExecutablePath"].Value
+                process_name = p.Properties_("Name").Value
+                process_id = p.Properties_["ProcessID"].Value
+
+                if executable_path is not None and process_name == name and process_id != self.self_pid:
+                    executable_path = executable_path.replace(r'\\', '/').replace('\\', '/')
+                    for folder in self.process_folder:
+                        if folder in executable_path:
+                            yield executable_path, process_name, process_id
+        except Exception as e:
+            # Possible exception
+            # pywintypes.com_error: (-2147217392, 'OLE error 0x80041010', None, None)
+            logger.info(str(e))
+            return False
+
+    def kill_by_name(self, name):
+        """
+        Args:
+            name (str): Process name
+        """
+        logger.hr(f'Kill {name}', 1)
+        for row in self.iter_process_by_name(name):
+            logger.info(' '.join(map(str, row)))
+            self.execute(f'taskkill /f /pid {row[2]}', allow_failure=True, output=False)
+
+    def process_kill(self):
+        logger.hr(f'Kill existing Alas', 0)
+        self.kill_by_name('alas.exe')
+        self.kill_by_name('python.exe')
+
+

+ 155 - 0
deploy/template

@@ -0,0 +1,155 @@
+Deploy:
+  Git:
+    # URL of AzurLaneAutoScript repository
+    # [CN user] Use 'https://gitee.com/lmeszinc/azur-lane-auto-script-mirror' for faster and more stable download
+    # [Other] Use 'https://github.com/LmeSzinc/AzurLaneAutoScript'
+    Repository: https://e.coding.net/onmyojiautoscript/oas/OnmyojiAutoScript.git
+    # Branch of Alas
+    # [Developer] Use 'dev', 'app', etc, to try new features
+    # [Other] Use 'master', the stable branch
+    Branch: master
+    # Filepath of git executable `git.exe`
+    # [Easy installer] Use './toolkit/Git/mingw64/bin/git.exe'
+    # [Other] Use you own git
+    GitExecutable: ./toolkit/Git/mingw64/bin/git.exe
+    # Set git proxy
+    # [CN user] Use your local http proxy (http://127.0.0.1:{port}) or socks5 proxy (socks5://127.0.0.1:{port})
+    # [Other] Use null
+    GitProxy: null
+    # Update Alas at startup
+    # [In most cases] Use true
+    AutoUpdate: true
+    # Whether to keep local changes during update
+    # User settings, logs and screenshots will be kept, no mather this is true or false
+    # [Developer] Use true, if you modified the code
+    # [Other] Use false
+    KeepLocalChanges: false
+
+  Python:
+    # Filepath of python executable `python.exe`
+    # [Easy installer] Use './toolkit/python.exe'
+    # [Other] Use you own python, and its version should be 3.7.6 64bit
+    PythonExecutable: ./toolkit/python.exe
+    # URL of pypi mirror
+    # [CN user] Use 'https://pypi.tuna.tsinghua.edu.cn/simple' for faster and more stable download
+    # [Other] Use null
+    PypiMirror: https://pypi.tuna.tsinghua.edu.cn/simple
+    # Install dependencies at startup
+    # [In most cases] Use true
+    InstallDependencies: true
+    # Path to requirements.txt
+    # [In most cases] Use 'requirements.txt'
+    # [In AidLux] Use './deploy/AidLux/{version}/requirements.txt', version is default to 0.92
+    RequirementsFile: requirements.txt
+
+  Adb:
+    # Filepath of ADB executable `adb.exe`
+    # [Easy installer] Use './toolkit/Lib/site-packages/adbutils/binaries/adb.exe'
+    # [Other] Use you own latest ADB, but not the ADB in your emulator
+    AdbExecutable: ./toolkit/Lib/site-packages/adbutils/binaries/adb.exe
+    # Whether to replace ADB
+    # Chinese emulators (NoxPlayer, LDPlayer, MemuPlayer, MuMuPlayer) use their own ADB, instead of the latest.
+    # Different ADB servers will terminate each other at startup, resulting in disconnection.
+    # For compatibility, we have to replace them all.
+    # This will do:
+    #   1. Terminate current ADB server
+    #   2. Rename ADB from all emulators to *.bak and replace them by the AdbExecutable set above
+    #   3. Brute-force connect to all available emulator instances
+    # [In most cases] Use true
+    # [In few cases] Use false, if you have other programs using ADB.
+    ReplaceAdb: true
+    # Brute-force connect to all available emulator instances
+    # [In most cases] Use true
+    AutoConnect: true
+    # Re-install uiautomator2
+    # [In most cases] Use true
+    InstallUiautomator2: true
+
+  Ocr:
+    # Run Ocr as a service, can reduce memory usage by not import mxnet everytime you start an alas instance
+
+    # Whether to use ocr server
+    # [Default] false
+    UseOcrServer: false
+    # Whether to start ocr server when start GUI
+    # [Default] false
+    StartOcrServer: false
+    # Port of ocr server runs by GUI
+    # [Default] 22268
+    OcrServerPort: 22268
+    # Address of ocr server for alas instance to connect
+    # [Default] 127.0.0.1:22268
+    OcrClientAddress: 127.0.0.1:22268
+
+  Update:
+    # Use auto update and builtin updater feature
+    # This may cause problem https://github.com/LmeSzinc/AzurLaneAutoScript/issues/876
+    EnableReload: true
+    # Check update every X minute
+    # [Disable] 0
+    # [Default] 5
+    CheckUpdateInterval: 5
+    # Scheduled restart time
+    # If there are updates, Alas will automatically restart and update at this time every day
+    # and run all alas instances that running before restarted
+    # [Disable] null
+    # [Default] 03:50
+    AutoRestartTime: 03:50
+
+  Misc:
+    # Enable discord rich presence
+    DiscordRichPresence: false
+
+  RemoteAccess:
+    # Enable remote access (using ssh reverse tunnel serve by https://github.com/wang0618/localshare)
+    # ! You need to set Password below to enable remote access since everyone can access to your alas if they have your url.
+    # See here (http://app.azurlane.cloud/en.html) for more infomation.
+    EnableRemoteAccess: false
+    # Username when login into ssh server
+    # [Default] null (will generate a random one when startup)
+    SSHUser: null
+    # Server to connect
+    # [Default] null
+    # [Format] host:port
+    SSHServer: null
+    # Filepath of SSH executable `ssh.exe`
+    # [Default] ssh (find ssh in system PATH)
+    # If you don't have one, install OpenSSH or download it here (https://github.com/PowerShell/Win32-OpenSSH/releases)
+    SSHExecutable: ssh
+
+  Webui:
+    # --host. Host to listen
+    # [Use IPv6] '::'
+    # [In most cases] Default to '0.0.0.0'
+    WebuiHost: 0.0.0.0
+    # --port. Port to listen
+    # You will be able to access webui via `http://{host}:{port}`
+    # [In most cases] Default to 22267
+    WebuiPort: 22267
+    # Language to use on web ui
+    # 'zh-CN' for Chinese simplified
+    # 'en-US' for English
+    # 'ja-JP' for Japanese
+    # 'zh-TW' for Chinese traditional
+    Language: zh-CN
+    # Theme of web ui
+    # 'default' for light theme
+    # 'dark' for dark theme
+    Theme: default
+    # Follow system DPI scaling
+    # [In most cases] true
+    # [In few cases] false to make Alas smaller, if you have a low resolution but high DPI scaling.
+    DpiScaling: true
+    # --key. Password of web ui
+    # Useful when expose Alas to the public network
+    Password: null
+    # --cdn. Use jsdelivr cdn for pywebio static files (css, js).
+    # 'true' for jsdelivr cdn
+    # 'false' for self host cdn (automatically)
+    # 'https://path.to.your/cdn' to use custom cdn
+    CDN: false
+    # --run. Auto-run specified config when startup
+    # 'null' default no specified config
+    # '["alas"]' specified "alas" config
+    # '["alas","alas2"]' specified "alas" "alas2" configs
+    Run: null

+ 114 - 0
deploy/utils.py

@@ -0,0 +1,114 @@
+# copy from alas https://github.com/LmeSzinc/AzurLaneAutoScript
+import os
+import re
+from typing import Callable, Generic, TypeVar
+
+T = TypeVar("T")
+
+DEPLOY_CONFIG = './config/deploy.yaml'
+DEPLOY_TEMPLATE = './deploy/template'
+
+
+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
+    """
+    for file in os.listdir(folder):
+        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('\\', '/')
+
+
+def poor_yaml_read(file):
+    """
+    Poor implementation to load yaml without pyyaml dependency, but with re
+
+    Args:
+        file (str):
+
+    Returns:
+        dict:
+    """
+    if not os.path.exists(file):
+        return {}
+
+    data = {}
+    regex = re.compile(r'^(.*?):(.*?)$')
+    with open(file, 'r', encoding='utf-8') as f:
+        for line in f.readlines():
+            line = line.strip('\n\r\t ').replace('\\', '/')
+            if line.startswith('#'):
+                continue
+            result = re.match(regex, line)
+            if result:
+                k, v = result.group(1), result.group(2).strip('\n\r\t\' ')
+                if v:
+                    if v.lower() == 'null':
+                        v = None
+                    elif v.lower() == 'false':
+                        v = False
+                    elif v.lower() == 'true':
+                        v = True
+                    elif v.isdigit():
+                        v = int(v)
+                    data[k] = v
+
+    return data
+
+
+def poor_yaml_write(data, file, template_file=DEPLOY_TEMPLATE):
+    """
+    Args:
+        data (dict):
+        file (str):
+        template_file (str):
+    """
+    with open(template_file, 'r', encoding='utf-8') as f:
+        text = f.read().replace('\\', '/')
+
+    for key, value in data.items():
+        if value is None:
+            value = 'null'
+        elif value is True:
+            value = "true"
+        elif value is False:
+            value = "false"
+        text = re.sub(f'{key}:.*?\n', f'{key}: {value}\n', text)
+
+    with open(file, 'w', encoding='utf-8', newline='') as f:
+        f.write(text)

+ 28 - 0
module/gui/qml/Component/SplitPanel.qml

@@ -4,4 +4,32 @@ import FluentUI
 
 Item {
 
+    // 左边菜单
+    FluArea{
+        id: menuArea
+        anchors.left: parent.left
+        height: parent.height
+        width: 200
+        FluTreeView{
+            id: menu_tree
+            anchors.fill: parent
+            Component.onCompleted: {
+                var datas = []
+                datas.push(createItem("Node1",false))
+                datas.push(createItem("Node2",false))
+                datas.push(createItem("Node2",true,[createItem("Node2-1",false),createItem("Node2-2",false)]))
+                updateData(datas)
+            }
+        }
+    }
+    // 右边内容
+    FluArea{
+        anchors.right: parent.right
+        anchors.rightMargin: 12
+        anchors.left: menuArea.right
+        anchors.leftMargin: 12
+        anchors.top: parent.top
+        anchors.bottom: parent.bottom
+        anchors.bottomMargin: 12
+    }
 }

+ 6 - 22
module/gui/qml/Page/O_Home.qml

@@ -4,26 +4,10 @@ import QtQuick.Window
 import QtQuick.Controls
 import FluentUI
 
-Item{
-//    leftPadding:10
-//    rightPadding:10
-//    bottomPadding:20
-    FluTreeView{
-        id: menu_tree
-        anchors.left: parent.left
-        width:200
-        height:parent.height
-        Component.onCompleted: {
-            var datas = []
-            datas.push(createItem("Node1",false))
-            datas.push(createItem("Node2",false))
-            datas.push(createItem("Node2",true,[createItem("Node2-1",false),createItem("Node2-2",false)]))
-            updateData(datas)
-        }
-    }
-    FluArea{
-        anchors.right: parent.right
-        anchors.left: menu_tree.right
-        height: parent.height
-    }
+import "../Component"
+
+
+SplitPanel{
+
 }
+

+ 1 - 0
requirements-in.txt

@@ -0,0 +1 @@
+pyside6==6.4.3

+ 15 - 0
requirements.txt

@@ -0,0 +1,15 @@
+#
+# This file is autogenerated by pip-compile with Python 3.10
+# by the following command:
+#
+#    pip-compile --annotation-style=line --output-file=requirements.txt requirements-in.txt
+#
+--index-url https://pypi.tuna.tsinghua.edu.cn/simple
+--trusted-host pypi.tuna.tsinghua.edu.cn
+
+click==8.1.3              # via -r requirements-in.txt
+colorama==0.4.6           # via click
+pyside6==6.4.3            # via -r requirements-in.txt
+pyside6-addons==6.4.3     # via pyside6
+pyside6-essentials==6.4.3  # via pyside6
+shiboken6==6.4.3          # via pyside6