Skip to content

Commit

Permalink
perf: 调整 Python Binding 初始化行为 (#445)
Browse files Browse the repository at this point in the history
改动详情见 #443
讨论历史见 #444

---------

Co-authored-by: MistEO <mistereo@hotmail.com>
  • Loading branch information
weinibuliu and MistEO authored Dec 4, 2024
1 parent e0c13ee commit 5d309df
Show file tree
Hide file tree
Showing 8 changed files with 29 additions and 90 deletions.
12 changes: 7 additions & 5 deletions source/binding/Python/maa/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import os
from pathlib import Path

from .library import Library

__PATH = os.path.join(os.path.dirname(__file__), "bin")
env_path = Path(os.environ.get("MAAFW_BINARY_PATH"))
if env_path:
__PATH = env_path
else:
__PATH = Path(Path(__file__).parent, "bin")

if os.path.exists(__PATH):
ver = Library.open(__PATH)
if ver:
print(f"MaaFw version: {ver}")
Library.open(__PATH)
22 changes: 0 additions & 22 deletions source/binding/Python/maa/buffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@ class StringBuffer:
_own: bool

def __init__(self, handle: Optional[MaaStringBufferHandle] = None):
if not Library.initialized:
raise RuntimeError(
"Library not initialized, please call `library.open()` first."
)
self._set_api_properties()

if handle:
Expand Down Expand Up @@ -97,10 +93,6 @@ class StringListBuffer:
_own: bool

def __init__(self, handle: Optional[MaaStringListBufferHandle] = None):
if not Library.initialized:
raise RuntimeError(
"Library not initialized, please call `library.open()` first."
)
self._set_api_properties()

if handle:
Expand Down Expand Up @@ -203,11 +195,6 @@ class ImageBuffer:
_own: bool

def __init__(self, c_handle: Optional[MaaImageBufferHandle] = None):
if not Library.initialized:
raise RuntimeError(
"Library not initialized, please call `library.open()` first."
)

self._set_api_properties()

if c_handle:
Expand Down Expand Up @@ -309,10 +296,6 @@ class ImageListBuffer:
_own: bool

def __init__(self, c_handle: Optional[MaaImageListBufferHandle] = None):
if not Library.initialized:
raise RuntimeError(
"Library not initialized, please call `library.open()` first."
)
self._set_api_properties()

if c_handle:
Expand Down Expand Up @@ -413,11 +396,6 @@ class RectBuffer:
_own: bool

def __init__(self, c_handle: Optional[MaaRectHandle] = None):
if not Library.initialized:
raise RuntimeError(
"Library not initialized, please call `library.open()` first."
)

self._set_api_properties()

if c_handle:
Expand Down
7 changes: 1 addition & 6 deletions source/binding/Python/maa/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,6 @@ def __init__(
self,
handle: Optional[MaaControllerHandle] = None,
):
if not Library.initialized:
raise RuntimeError(
"Library not initialized, please call `library.open()` first."
)

self._set_api_properties()

if handle:
Expand Down Expand Up @@ -152,7 +147,7 @@ def set_screenshot_target_short_side(self, short_side: int) -> bool:
ctypes.sizeof(ctypes.c_int32),
)
)

def set_screenshot_use_raw_size(self, enable: bool) -> bool:
cbool = MaaBool(enable)
return bool(
Expand Down
40 changes: 8 additions & 32 deletions source/binding/Python/maa/library.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@
import ctypes.util
import pathlib
import platform
from typing import Optional, Union

from .define import *


class Library:

initialized = False

@staticmethod
def open(path: Union[pathlib.Path, str]) -> Optional[str]:
def open(path: pathlib.Path):
if not path.exists():
raise FileNotFoundError(f"`{path}` does not exist.")

platform_values = {
"windows": ("MaaFramework.dll", "MaaToolkit.dll"),
"darwin": ("libMaaFramework.dylib", "libMaaToolkit.dylib"),
Expand All @@ -26,40 +26,16 @@ def open(path: Union[pathlib.Path, str]) -> Optional[str]:
else:
lib_import = ctypes.CDLL

try:
Library.framework_libpath = (
pathlib.Path(path) / platform_values[platform_type][0]
)
Library.framework = lib_import(str(Library.framework_libpath))
except OSError:
Library.framework_libpath = ctypes.util.find_library("MaaFramework")
Library.framework = lib_import(str(Library.framework_libpath))

try:
Library.toolkit_libpath = (
pathlib.Path(path) / platform_values[platform_type][1]
)
Library.toolkit = lib_import(str(Library.toolkit_libpath))
except OSError:
Library.toolkit_libpath = ctypes.util.find_library("MaaToolkit")
Library.toolkit = lib_import(str(Library.toolkit_libpath))
Library.framework_libpath = path / platform_values[platform_type][0]
Library.framework = lib_import(str(Library.framework_libpath))

if not Library.framework or not Library.toolkit:
Library.initialized = False
return None
Library.toolkit_libpath = path / platform_values[platform_type][1]
Library.toolkit = lib_import(str(Library.toolkit_libpath))

Library._set_api_properties()
Library.initialized = True

return Library.version()

@staticmethod
def version() -> str:
if not Library.initialized:
raise RuntimeError(
"Library not initialized, please call `library.open()` first."
)

return Library.framework.MaaVersion().decode()

@staticmethod
Expand Down
6 changes: 0 additions & 6 deletions source/binding/Python/maa/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,6 @@ def __init__(
notification_handler: Optional[NotificationHandler] = None,
handle: Optional[MaaResourceHandle] = None,
):

if not Library.initialized:
raise RuntimeError(
"Library not initialized, please call `library.open()` first."
)

self._set_api_properties()

if handle:
Expand Down
6 changes: 0 additions & 6 deletions source/binding/Python/maa/tasker.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import ctypes
import json
import time
from pathlib import Path
from typing import Any, Dict, Optional, Union

Expand All @@ -25,11 +24,6 @@ def __init__(
notification_handler: Optional[NotificationHandler] = None,
handle: Optional[MaaTaskerHandle] = None,
):
if not Library.initialized:
raise RuntimeError(
"Library not initialized, please call `library.open()` first."
)

self._set_api_properties()

if handle:
Expand Down
5 changes: 0 additions & 5 deletions source/binding/Python/maa/toolkit.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,11 +189,6 @@ def _set_api_properties():
return
Toolkit._api_properties_initialized = True

if not Library.initialized:
raise RuntimeError(
"Library not initialized, please call `library.open()` first."
)

Library.toolkit.MaaToolkitConfigInitOption.restype = MaaBool
Library.toolkit.MaaToolkitConfigInitOption.argtypes = [
ctypes.c_char_p,
Expand Down
21 changes: 13 additions & 8 deletions test/python/binding_test.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
import os
from pathlib import Path
import numpy
import sys

import numpy

if len(sys.argv) < 2:
print("Usage: python binding_test.py <install_dir>")
sys.exit(1)

install_dir = Path(sys.argv[1]).resolve()
print(f"install_dir: {install_dir}")
binding_dir = Path(install_dir, "binding", "Python")

binding_dir = str(install_dir / "binding" / "Python")
if binding_dir not in sys.path:
sys.path.insert(0, binding_dir)
os.environ["MAAFW_BINARY_PATH"] = str(f"{install_dir}/bin")
print(f"install_dir: {install_dir}")
print(f"binding_dir: {binding_dir}")

if str(binding_dir) not in sys.path:
sys.path.insert(0, str(binding_dir))

from maa.library import Library
from maa.resource import Resource
Expand Down Expand Up @@ -262,7 +266,9 @@ def click(self, x: int, y: int) -> bool:
return True

def swipe(self, x1: int, y1: int, x2: int, y2: int, duration: int) -> bool:
print(f"on MyController.swipe, x1: {x1}, y1: {y1}, x2: {x2}, y2: {y2}, duration: {duration}")
print(
f"on MyController.swipe, x1: {x1}, y1: {y1}, x2: {x2}, y2: {y2}, duration: {duration}"
)
self.count += 1
return True

Expand Down Expand Up @@ -309,8 +315,7 @@ def input_text(self, text: str) -> bool:


if __name__ == "__main__":
version = Library.open(install_dir / "bin")
print(f"MaaFw Version: {version}")
print(f"MaaFw Version: {Library.version()}")

Toolkit.init_option(install_dir / "bin")

Expand Down

0 comments on commit 5d309df

Please sign in to comment.