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
24//! let controller = Controller::new_adb(
25//! device.adb_path.to_str().unwrap(),
26//! &device.address,
27//! "{}",
28//! None,
29//! )?;
30//!
31//! // 3. Create resource and tasker
32//! let resource = Resource::new()?;
33//! let tasker = Tasker::new()?;
34//!
35//! // 4. Bind and run
36//! tasker.bind(&resource, &controller)?;
37//! let job = tasker.post_task("StartTask", "{}")?;
38//! job.wait();
39//!
40//! Ok(())
41//! }
42//! ```
43//!
44//! ## Core Modules
45//!
46//! | Module | Description |
47//! |--------|-------------|
48//! | [`tasker`] | Task execution and pipeline management |
49//! | [`resource`] | Resource loading (images, models, pipelines) |
50//! | [`controller`] | Device control (ADB, Win32, PlayCover) |
51//! | [`context`] | Task execution context for custom components |
52//! | [`toolkit`] | Device discovery utilities |
53//! | [`pipeline`] | Pipeline configuration types |
54//! | [`job`] | Asynchronous job management |
55//! | [`event_sink`] | Event sink system for typed callbacks |
56//! | [`buffer`] | Safe data buffers for FFI |
57//! | [`custom`] | Custom recognizer and action traits |
58//! | [`custom_controller`] | Custom controller implementation |
59//! | [`notification`] | Structured event notification parsing |
60//! | [`common`] | Common types and data structures |
61//! | [`error`] | Error types and handling |
62//! | [`util`] | Miscellaneous utility functions |
63//! | [`agent_client`] | Remote custom component client |
64//! | [`agent_server`] | Remote custom component server |
65//!
66//! ## Feature Flags
67//!
68//! - `adb` - ADB controller support (default)
69//! - `win32` - Win32 controller support (Windows only)
70//! - `custom` - Custom recognizer/action/controller support
71//! - `toolkit` - Device discovery utilities
72//! - `image` - Integration with the `image` crate
73
74#![allow(non_upper_case_globals)]
75#![allow(non_camel_case_types)]
76#![allow(non_snake_case)]
77
78pub mod agent_client;
79pub mod agent_server;
80pub mod buffer;
81pub mod callback;
82pub mod common;
83pub mod context;
84pub mod controller;
85pub mod custom;
86pub mod custom_controller;
87pub mod error;
88pub mod event_sink;
89pub mod job;
90pub mod notification;
91pub mod pipeline;
92pub mod resource;
93pub mod sys;
94pub mod tasker;
95pub mod toolkit;
96pub mod util;
97
98pub use common::ControllerFeature;
99pub use common::MaaStatus;
100pub use error::{MaaError, MaaResult};
101
102use std::ffi::CString;
103
104/// Get the MaaFramework version string.
105///
106/// # Example
107/// ```no_run
108/// println!("MaaFramework version: {}", maa_framework::maa_version());
109/// ```
110pub fn maa_version() -> &'static str {
111 unsafe {
112 std::ffi::CStr::from_ptr(sys::MaaVersion())
113 .to_str()
114 .unwrap_or("unknown")
115 }
116}
117
118/// Set a global framework option.
119///
120/// Low-level function for setting global options. Consider using the
121/// convenience wrappers like [`configure_logging`], [`set_debug_mode`], etc.
122pub fn set_global_option(
123 key: sys::MaaGlobalOption,
124 value: *mut std::ffi::c_void,
125 size: u64,
126) -> MaaResult<()> {
127 let ret = unsafe { sys::MaaGlobalSetOption(key, value, size) };
128 common::check_bool(ret)
129}
130
131/// Configure the log output directory.
132///
133/// # Arguments
134/// * `log_dir` - Path to the directory where logs should be stored
135pub fn configure_logging(log_dir: &str) -> MaaResult<()> {
136 let c_dir = CString::new(log_dir)?;
137 set_global_option(
138 sys::MaaGlobalOptionEnum_MaaGlobalOption_LogDir as i32,
139 c_dir.as_ptr() as *mut _,
140 c_dir.as_bytes().len() as u64,
141 )
142}
143
144/// Enable or disable debug mode.
145///
146/// In debug mode:
147/// - Recognition details include raw images and draws
148/// - All tasks are treated as focus tasks and produce callbacks
149///
150/// # Arguments
151/// * `enable` - `true` to enable debug mode
152pub fn set_debug_mode(enable: bool) -> MaaResult<()> {
153 let mut val_bool = if enable { 1u8 } else { 0u8 };
154 set_global_option(
155 sys::MaaGlobalOptionEnum_MaaGlobalOption_DebugMode as i32,
156 &mut val_bool as *mut _ as *mut _,
157 std::mem::size_of::<u8>() as u64,
158 )
159}
160
161/// Set the log level for stdout output.
162///
163/// # Arguments
164/// * `level` - Logging level (use `sys::MaaLoggingLevel*` constants)
165pub fn set_stdout_level(level: sys::MaaLoggingLevel) -> MaaResult<()> {
166 let mut val = level;
167 set_global_option(
168 sys::MaaGlobalOptionEnum_MaaGlobalOption_StdoutLevel as i32,
169 &mut val as *mut _ as *mut _,
170 std::mem::size_of::<sys::MaaLoggingLevel>() as u64,
171 )
172}
173
174/// Enable/disable saving recognition visualizations to log directory.
175pub fn set_save_draw(enable: bool) -> MaaResult<()> {
176 let mut val: u8 = if enable { 1 } else { 0 };
177 set_global_option(
178 sys::MaaGlobalOptionEnum_MaaGlobalOption_SaveDraw as i32,
179 &mut val as *mut _ as *mut _,
180 std::mem::size_of::<u8>() as u64,
181 )
182}
183
184/// Enable/disable saving screenshots on error.
185pub fn set_save_on_error(enable: bool) -> MaaResult<()> {
186 let mut val: u8 = if enable { 1 } else { 0 };
187 set_global_option(
188 sys::MaaGlobalOptionEnum_MaaGlobalOption_SaveOnError as i32,
189 &mut val as *mut _ as *mut _,
190 std::mem::size_of::<u8>() as u64,
191 )
192}
193
194/// Set JPEG quality for saved draw images (0-100, default 85).
195pub fn set_draw_quality(quality: i32) -> MaaResult<()> {
196 let mut val = quality;
197 set_global_option(
198 sys::MaaGlobalOptionEnum_MaaGlobalOption_DrawQuality as i32,
199 &mut val as *mut _ as *mut _,
200 std::mem::size_of::<i32>() as u64,
201 )
202}
203
204/// Set the recognition image cache limit (default 4096).
205pub fn set_reco_image_cache_limit(limit: u64) -> MaaResult<()> {
206 let mut val = limit;
207 set_global_option(
208 sys::MaaGlobalOptionEnum_MaaGlobalOption_RecoImageCacheLimit as i32,
209 &mut val as *mut _ as *mut _,
210 std::mem::size_of::<u64>() as u64,
211 )
212}
213
214/// Load a plugin from the specified path.
215pub fn load_plugin(path: &str) -> MaaResult<()> {
216 let c_path = CString::new(path)?;
217 let ret = unsafe { sys::MaaGlobalLoadPlugin(c_path.as_ptr()) };
218 common::check_bool(ret)
219}
220
221/// Loads the MaaFramework dynamic library.
222///
223/// You **must** call this function successfully before using any other APIs when the `dynamic`
224/// feature is enabled.
225///
226/// # Arguments
227///
228/// * `path` - Path to the dynamic library file (e.g., `MaaFramework.dll`, `libMaaFramework.so`).
229///
230/// # Errors
231///
232/// Returns an error if:
233/// * The library file cannot be found or loaded.
234/// * The library has already been loaded (multiple initialization is not supported).
235/// * Required symbols are missing from the library.
236///
237/// # Panics
238///
239/// Subsequent calls to any MaaFramework API will panic if the library has not been initialized.
240///
241/// # Safety
242///
243/// This function is `unsafe` because:
244/// * It executes arbitrary initialization code (e.g., `DllMain`) inside the loaded library.
245/// * The caller must ensure `path` points to a valid MaaFramework binary compatible with these bindings.
246#[cfg(feature = "dynamic")]
247pub fn load_library(path: &std::path::Path) -> Result<(), String> {
248 unsafe { sys::load_library(path) }
249}