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, PlayCover) |
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;
102
103/// Get the MaaFramework version string.
104///
105/// # Example
106/// ```no_run
107/// println!("MaaFramework version: {}", maa_framework::maa_version());
108/// ```
109pub fn maa_version() -> &'static str {
110 unsafe {
111 std::ffi::CStr::from_ptr(sys::MaaVersion())
112 .to_str()
113 .unwrap_or("unknown")
114 }
115}
116
117/// Set a global framework option.
118///
119/// Low-level function for setting global options. Consider using the
120/// convenience wrappers like [`configure_logging`], [`set_debug_mode`], etc.
121pub fn set_global_option(
122 key: sys::MaaGlobalOption,
123 value: *mut std::ffi::c_void,
124 size: u64,
125) -> MaaResult<()> {
126 let ret = unsafe { sys::MaaGlobalSetOption(key, value, size) };
127 common::check_bool(ret)
128}
129
130/// Configure the log output directory.
131///
132/// # Arguments
133/// * `log_dir` - Path to the directory where logs should be stored
134pub fn configure_logging(log_dir: &str) -> MaaResult<()> {
135 let c_dir = CString::new(log_dir)?;
136 set_global_option(
137 sys::MaaGlobalOptionEnum_MaaGlobalOption_LogDir as i32,
138 c_dir.as_ptr() as *mut _,
139 c_dir.as_bytes().len() as u64,
140 )
141}
142
143/// Enable or disable debug mode.
144///
145/// In debug mode:
146/// - Recognition details include raw images and draws
147/// - All tasks are treated as focus tasks and produce callbacks
148///
149/// # Arguments
150/// * `enable` - `true` to enable debug mode
151pub fn set_debug_mode(enable: bool) -> MaaResult<()> {
152 let mut val_bool = if enable { 1u8 } else { 0u8 };
153 set_global_option(
154 sys::MaaGlobalOptionEnum_MaaGlobalOption_DebugMode as i32,
155 &mut val_bool as *mut _ as *mut _,
156 std::mem::size_of::<u8>() as u64,
157 )
158}
159
160/// Set the log level for stdout output.
161///
162/// # Arguments
163/// * `level` - Logging level (use `sys::MaaLoggingLevel*` constants)
164pub fn set_stdout_level(level: sys::MaaLoggingLevel) -> MaaResult<()> {
165 let mut val = level;
166 set_global_option(
167 sys::MaaGlobalOptionEnum_MaaGlobalOption_StdoutLevel as i32,
168 &mut val as *mut _ as *mut _,
169 std::mem::size_of::<sys::MaaLoggingLevel>() as u64,
170 )
171}
172
173/// Enable/disable saving recognition visualizations to log directory.
174pub fn set_save_draw(enable: bool) -> MaaResult<()> {
175 let mut val: u8 = if enable { 1 } else { 0 };
176 set_global_option(
177 sys::MaaGlobalOptionEnum_MaaGlobalOption_SaveDraw as i32,
178 &mut val as *mut _ as *mut _,
179 std::mem::size_of::<u8>() as u64,
180 )
181}
182
183/// Enable/disable saving screenshots on error.
184pub fn set_save_on_error(enable: bool) -> MaaResult<()> {
185 let mut val: u8 = if enable { 1 } else { 0 };
186 set_global_option(
187 sys::MaaGlobalOptionEnum_MaaGlobalOption_SaveOnError as i32,
188 &mut val as *mut _ as *mut _,
189 std::mem::size_of::<u8>() as u64,
190 )
191}
192
193/// Set JPEG quality for saved draw images (0-100, default 85).
194pub fn set_draw_quality(quality: i32) -> MaaResult<()> {
195 let mut val = quality;
196 set_global_option(
197 sys::MaaGlobalOptionEnum_MaaGlobalOption_DrawQuality as i32,
198 &mut val as *mut _ as *mut _,
199 std::mem::size_of::<i32>() as u64,
200 )
201}
202
203/// Set the recognition image cache limit (default 4096).
204pub fn set_reco_image_cache_limit(limit: u64) -> MaaResult<()> {
205 let mut val = limit;
206 set_global_option(
207 sys::MaaGlobalOptionEnum_MaaGlobalOption_RecoImageCacheLimit as i32,
208 &mut val as *mut _ as *mut _,
209 std::mem::size_of::<u64>() as u64,
210 )
211}
212
213/// Load a plugin from the specified path.
214pub fn load_plugin(path: &str) -> MaaResult<()> {
215 let c_path = CString::new(path)?;
216 let ret = unsafe { sys::MaaGlobalLoadPlugin(c_path.as_ptr()) };
217 common::check_bool(ret)
218}
219
220/// Loads the MaaFramework dynamic library.
221///
222/// You **must** call this function successfully before using any other APIs when the `dynamic`
223/// feature is enabled.
224///
225/// # Arguments
226///
227/// * `path` - Path to the dynamic library file (e.g., `MaaFramework.dll`, `libMaaFramework.so`).
228///
229/// # Errors
230///
231/// Returns an error if:
232/// * The library file cannot be found or loaded.
233/// * The library has already been loaded (multiple initialization is not supported).
234/// * Required symbols are missing from the library.
235///
236/// # Panics
237///
238/// Subsequent calls to any MaaFramework API will panic if the library has not been initialized.
239///
240/// # Safety
241///
242/// This function is `unsafe` because:
243/// * It executes arbitrary initialization code (e.g., `DllMain`) inside the loaded library.
244/// * The caller must ensure `path` points to a valid MaaFramework binary compatible with these bindings.
245#[cfg(feature = "dynamic")]
246pub fn load_library(path: &std::path::Path) -> Result<(), String> {
247 unsafe { sys::load_library(path) }
248}
249
250/// Finds and loads the MaaFramework dynamic library when using the `dynamic` feature.
251///
252/// Tries, in order: `MAA_SDK_PATH` (bin/lib), project `MAA-*` dirs (from `CARGO_MANIFEST_DIR`
253/// or current dir), `target/debug` or `target/release`, then current dir. Use this in examples
254/// or apps so that `cargo run --example main` works without setting env vars.
255///
256/// # Errors
257///
258/// Returns an error if no library file is found or loading fails.
259#[cfg(feature = "dynamic")]
260pub fn ensure_library_loaded() -> Result<(), String> {
261 let lib_name = if cfg!(target_os = "windows") {
262 "MaaFramework.dll"
263 } else if cfg!(target_os = "macos") {
264 "libMaaFramework.dylib"
265 } else {
266 "libMaaFramework.so"
267 };
268
269 let mut candidates: Vec<std::path::PathBuf> = Vec::new();
270
271 if let Ok(sdk) = std::env::var("MAA_SDK_PATH") {
272 let sdk = std::path::PathBuf::from(sdk);
273 candidates.push(sdk.join("bin").join(lib_name));
274 candidates.push(sdk.join("lib").join(lib_name));
275 }
276
277 let search_roots: Vec<std::path::PathBuf> = std::env::var("CARGO_MANIFEST_DIR")
278 .map(std::path::PathBuf::from)
279 .into_iter()
280 .chain(std::env::current_dir().ok())
281 .collect();
282
283 for root in &search_roots {
284 if let Ok(entries) = std::fs::read_dir(root) {
285 for e in entries.flatten() {
286 let p = e.path();
287 if p.is_dir() {
288 if let Some(name) = p.file_name() {
289 if name.to_string_lossy().starts_with("MAA-") {
290 candidates.push(p.join("bin").join(lib_name));
291 }
292 }
293 }
294 }
295 }
296 }
297
298 if let Ok(cwd) = std::env::current_dir() {
299 candidates.push(cwd.join("target/debug").join(lib_name));
300 candidates.push(cwd.join("target/release").join(lib_name));
301 candidates.push(cwd.join(lib_name));
302 }
303
304 let chosen = candidates.into_iter().find(|p| p.exists());
305 match chosen {
306 Some(path) => load_library(&path),
307 None => Err(
308 "MaaFramework library not found. Set MAA_SDK_PATH or place SDK (e.g. MAA-*/bin/)."
309 .to_string(),
310 ),
311 }
312}