Skip to main content

maa_framework/
lib.rs

1//! # MaaFramework Rust Bindings
2//!
3//! High-performance, safe Rust bindings for [MaaFramework](https://github.com/MaaXYZ/MaaFramework),
4//! a game automation framework based on image recognition.
5//!
6//! ## Quick Start
7//!
8//! ```no_run
9//! use maa_framework::toolkit::Toolkit;
10//! use maa_framework::controller::Controller;
11//! use maa_framework::resource::Resource;
12//! use maa_framework::tasker::Tasker;
13//!
14//! fn main() -> Result<(), Box<dyn std::error::Error>> {
15//!     // 0. Load library (Dynamic only)
16//!     #[cfg(feature = "dynamic")]
17//!     maa_framework::load_library(std::path::Path::new("MaaFramework.dll"))?;
18//!
19//!     // 1. Find devices
20//!     let devices = Toolkit::find_adb_devices()?;
21//!     let device = devices.first().expect("No device found");
22//!
23//!     // 2. Create controller (agent_path: "" to use MAA_AGENT_PATH or current dir)
24//!     let adb_path = device.adb_path.to_str().ok_or_else(|| {
25//!         std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid ADB path")
26//!     })?;
27//!     let controller = Controller::new_adb(adb_path, &device.address, "{}", "")?;
28//!
29//!     // 3. Create resource and tasker
30//!     let resource = Resource::new()?;
31//!     let tasker = Tasker::new()?;
32//!
33//!     // 4. Bind and run
34//!     tasker.bind(&resource, &controller)?;
35//!     let job = tasker.post_task("StartTask", "{}")?;
36//!     job.wait();
37//!
38//!     Ok(())
39//! }
40//! ```
41//!
42//! ## Core Modules
43//!
44//! | Module | Description |
45//! |--------|-------------|
46//! | [`tasker`] | Task execution and pipeline management |
47//! | [`resource`] | Resource loading (images, models, pipelines) |
48//! | [`controller`] | Device control (ADB, Win32, macOS, PlayCover, WlRoots) |
49//! | [`context`] | Task execution context for custom components |
50//! | [`toolkit`] | Device discovery utilities |
51//! | [`pipeline`] | Pipeline configuration types |
52//! | [`job`] | Asynchronous job management |
53//! | [`event_sink`] | Event sink system for typed callbacks |
54//! | [`buffer`] | Safe data buffers for FFI |
55//! | [`custom`] | Custom recognizer and action traits |
56//! | [`custom_controller`] | Custom controller implementation |
57//! | [`notification`] | Structured event notification parsing |
58//! | [`common`] | Common types and data structures |
59//! | [`error`] | Error types and handling |
60//! | [`util`] | Miscellaneous utility functions |
61//! | [`agent_client`] | Remote custom component client |
62//! | [`agent_server`] | Remote custom component server |
63//!
64//! ## Feature Flags
65//!
66//! - `adb` - ADB controller support (default)
67//! - `win32` - Win32 controller support (Windows only)
68//! - `custom` - Custom recognizer/action/controller support
69//! - `toolkit` - Device discovery utilities
70//! - `image` - Integration with the `image` crate
71
72#![allow(non_upper_case_globals)]
73#![allow(non_camel_case_types)]
74#![allow(non_snake_case)]
75
76pub mod agent_client;
77pub mod agent_server;
78pub mod buffer;
79pub mod callback;
80pub mod common;
81pub mod context;
82pub mod controller;
83pub mod custom;
84pub mod custom_controller;
85pub mod error;
86pub mod event_sink;
87pub mod job;
88pub mod notification;
89pub mod pipeline;
90pub mod resource;
91pub mod tasker;
92pub mod toolkit;
93pub mod util;
94
95pub use common::ControllerFeature;
96pub use common::MaaStatus;
97pub use error::{MaaError, MaaResult};
98
99pub use maa_framework_sys as sys;
100
101use std::ffi::CString;
102use std::sync::atomic::{AtomicU8, Ordering};
103
104const RUNTIME_CONTEXT_UNKNOWN: u8 = 0;
105#[cfg(feature = "dynamic")]
106const RUNTIME_CONTEXT_FRAMEWORK: u8 = 1;
107const RUNTIME_CONTEXT_AGENT_SERVER: u8 = 2;
108
109static RUNTIME_CONTEXT: AtomicU8 = AtomicU8::new(RUNTIME_CONTEXT_UNKNOWN);
110
111/// Get the MaaFramework version string.
112///
113/// # Example
114/// ```no_run
115/// println!("MaaFramework version: {}", maa_framework::maa_version());
116/// ```
117pub fn maa_version() -> &'static str {
118    unsafe {
119        std::ffi::CStr::from_ptr(sys::MaaVersion())
120            .to_str()
121            .unwrap_or("unknown")
122    }
123}
124
125/// Set a global framework option.
126///
127/// Low-level function for setting global options. Consider using the
128/// convenience wrappers like [`configure_logging`], [`set_debug_mode`], etc.
129pub fn set_global_option(
130    key: sys::MaaGlobalOption,
131    value: *mut std::ffi::c_void,
132    size: u64,
133) -> MaaResult<()> {
134    let ret = unsafe { sys::MaaGlobalSetOption(key, value, size) };
135    common::check_bool(ret)
136}
137
138/// Configure the log output directory.
139///
140/// # Arguments
141/// * `log_dir` - Path to the directory where logs should be stored
142pub fn configure_logging(log_dir: &str) -> MaaResult<()> {
143    let c_dir = CString::new(log_dir)?;
144    set_global_option(
145        sys::MaaGlobalOptionEnum_MaaGlobalOption_LogDir as i32,
146        c_dir.as_ptr() as *mut _,
147        c_dir.as_bytes().len() as u64,
148    )
149}
150
151/// Enable or disable debug mode.
152///
153/// In debug mode:
154/// - Recognition details include raw images and draws
155/// - All tasks are treated as focus tasks and produce callbacks
156///
157/// # Arguments
158/// * `enable` - `true` to enable debug mode
159pub fn set_debug_mode(enable: bool) -> MaaResult<()> {
160    let mut val_bool = if enable { 1u8 } else { 0u8 };
161    set_global_option(
162        sys::MaaGlobalOptionEnum_MaaGlobalOption_DebugMode as i32,
163        &mut val_bool as *mut _ as *mut _,
164        std::mem::size_of::<u8>() as u64,
165    )
166}
167
168/// Set the log level for stdout output.
169///
170/// # Arguments
171/// * `level` - Logging level (use `sys::MaaLoggingLevel*` constants)
172pub fn set_stdout_level(level: sys::MaaLoggingLevel) -> MaaResult<()> {
173    let mut val = level;
174    set_global_option(
175        sys::MaaGlobalOptionEnum_MaaGlobalOption_StdoutLevel as i32,
176        &mut val as *mut _ as *mut _,
177        std::mem::size_of::<sys::MaaLoggingLevel>() as u64,
178    )
179}
180
181/// Enable/disable saving recognition visualizations to log directory.
182pub fn set_save_draw(enable: bool) -> MaaResult<()> {
183    let mut val: u8 = if enable { 1 } else { 0 };
184    set_global_option(
185        sys::MaaGlobalOptionEnum_MaaGlobalOption_SaveDraw as i32,
186        &mut val as *mut _ as *mut _,
187        std::mem::size_of::<u8>() as u64,
188    )
189}
190
191/// Enable/disable saving screenshots on error.
192pub fn set_save_on_error(enable: bool) -> MaaResult<()> {
193    let mut val: u8 = if enable { 1 } else { 0 };
194    set_global_option(
195        sys::MaaGlobalOptionEnum_MaaGlobalOption_SaveOnError as i32,
196        &mut val as *mut _ as *mut _,
197        std::mem::size_of::<u8>() as u64,
198    )
199}
200
201/// Set JPEG quality for saved draw images (0-100, default 85).
202pub fn set_draw_quality(quality: i32) -> MaaResult<()> {
203    let mut val = quality;
204    set_global_option(
205        sys::MaaGlobalOptionEnum_MaaGlobalOption_DrawQuality as i32,
206        &mut val as *mut _ as *mut _,
207        std::mem::size_of::<i32>() as u64,
208    )
209}
210
211/// Set the recognition image cache limit (default 4096).
212pub fn set_reco_image_cache_limit(limit: u64) -> MaaResult<()> {
213    let mut val = limit;
214    set_global_option(
215        sys::MaaGlobalOptionEnum_MaaGlobalOption_RecoImageCacheLimit as i32,
216        &mut val as *mut _ as *mut _,
217        std::mem::size_of::<u64>() as u64,
218    )
219}
220
221/// Load a plugin from the specified path.
222pub fn load_plugin(path: &str) -> MaaResult<()> {
223    let c_path = CString::new(path)?;
224    let ret = unsafe { sys::MaaGlobalLoadPlugin(c_path.as_ptr()) };
225    common::check_bool(ret)
226}
227
228/// Loads the MaaFramework dynamic library.
229///
230/// You **must** call this function successfully before using any other APIs when the `dynamic`
231/// feature is enabled.
232///
233/// # Arguments
234///
235/// * `path` - Path to the dynamic library file (e.g., `MaaFramework.dll`, `libMaaFramework.so`).
236///
237/// # Errors
238///
239/// Returns an error if:
240/// * The library file cannot be found or loaded.
241/// * The library has already been loaded (multiple initialization is not supported).
242/// * Required symbols are missing from the library.
243///
244/// # Panics
245///
246/// Subsequent calls to any MaaFramework API will panic if the library has not been initialized.
247///
248/// # Safety
249///
250/// This function is `unsafe` because:
251/// * It executes arbitrary initialization code (e.g., `DllMain`) inside the loaded library.
252/// * The caller must ensure `path` points to a valid MaaFramework binary compatible with these bindings.
253#[cfg(feature = "dynamic")]
254pub fn load_library(path: &std::path::Path) -> Result<(), String> {
255    let context = runtime_context_from_library_path(path);
256    unsafe { sys::load_library(path) }?;
257    RUNTIME_CONTEXT.store(context, Ordering::Relaxed);
258    Ok(())
259}
260
261/// Finds and loads the MaaFramework dynamic library when using the `dynamic` feature.
262///
263/// Tries, in order: `MAA_SDK_PATH` (bin/lib), project `MAA-*` dirs (from `CARGO_MANIFEST_DIR`
264/// or current dir), `target/debug` or `target/release`, then current dir. Use this in examples
265/// or apps so that `cargo run --example main` works without setting env vars.
266///
267/// # Errors
268///
269/// Returns an error if no library file is found or loading fails.
270#[cfg(feature = "dynamic")]
271pub fn ensure_library_loaded() -> Result<(), String> {
272    let lib_name = if cfg!(target_os = "windows") {
273        "MaaFramework.dll"
274    } else if cfg!(target_os = "macos") {
275        "libMaaFramework.dylib"
276    } else {
277        "libMaaFramework.so"
278    };
279
280    let mut candidates: Vec<std::path::PathBuf> = Vec::new();
281
282    if let Ok(sdk) = std::env::var("MAA_SDK_PATH") {
283        let sdk = std::path::PathBuf::from(sdk);
284        candidates.push(sdk.join("bin").join(lib_name));
285        candidates.push(sdk.join("lib").join(lib_name));
286    }
287
288    let search_roots: Vec<std::path::PathBuf> = std::env::var("CARGO_MANIFEST_DIR")
289        .map(std::path::PathBuf::from)
290        .into_iter()
291        .chain(std::env::current_dir().ok())
292        .collect();
293
294    for root in &search_roots {
295        if let Ok(entries) = std::fs::read_dir(root) {
296            for e in entries.flatten() {
297                let p = e.path();
298                if p.is_dir() {
299                    if let Some(name) = p.file_name() {
300                        if name.to_string_lossy().starts_with("MAA-") {
301                            candidates.push(p.join("bin").join(lib_name));
302                        }
303                    }
304                }
305            }
306        }
307    }
308
309    if let Ok(cwd) = std::env::current_dir() {
310        candidates.push(cwd.join("target/debug").join(lib_name));
311        candidates.push(cwd.join("target/release").join(lib_name));
312        candidates.push(cwd.join(lib_name));
313    }
314
315    let chosen = candidates.into_iter().find(|p| p.exists());
316    match chosen {
317        Some(path) => load_library(&path),
318        None => Err(
319            "MaaFramework library not found. Set MAA_SDK_PATH or place SDK (e.g. MAA-*/bin/)."
320                .to_string(),
321        ),
322    }
323}
324
325pub(crate) fn mark_agent_server_context() {
326    RUNTIME_CONTEXT.store(RUNTIME_CONTEXT_AGENT_SERVER, Ordering::Relaxed);
327}
328
329pub(crate) fn is_agent_server_context() -> bool {
330    RUNTIME_CONTEXT.load(Ordering::Relaxed) == RUNTIME_CONTEXT_AGENT_SERVER
331}
332
333#[cfg(feature = "dynamic")]
334fn runtime_context_from_library_path(path: &std::path::Path) -> u8 {
335    let Some(file_name) = path.file_name() else {
336        return RUNTIME_CONTEXT_UNKNOWN;
337    };
338    let file_name = file_name.to_string_lossy();
339    if file_name.is_empty() {
340        return RUNTIME_CONTEXT_UNKNOWN;
341    }
342    if file_name.contains("MaaAgentServer") {
343        RUNTIME_CONTEXT_AGENT_SERVER
344    } else {
345        RUNTIME_CONTEXT_FRAMEWORK
346    }
347}