Skip to main content

MaaImageBuffer

Struct MaaImageBuffer 

Source
pub struct MaaImageBuffer { /* private fields */ }
Expand description

Image buffer for storing and manipulating image data.

Supports raw BGR data and encoded formats (PNG/JPEG). Compatible with OpenCV image types.

Implementations§

Source§

impl MaaImageBuffer

Source

pub fn new() -> MaaResult<Self>

Create a new buffer.

Examples found in repository?
examples/main.rs (line 56)
37    fn analyze(
38        &self,
39        context: &Context,
40        _task_id: sys::MaaTaskId,
41        node_name: &str,
42        custom_recognition_name: &str,
43        custom_recognition_param: &str,
44        _image: &maa_framework::buffer::MaaImageBuffer,
45        _roi: &maa_framework::common::Rect,
46    ) -> Option<(maa_framework::common::Rect, String)> {
47        println!(
48            "[MyRecognition] analyze called: node={}, name={}, param={}",
49            node_name, custom_recognition_name, custom_recognition_param
50        );
51
52        // --- Context API Demo ---
53
54        // 1. Run sub-pipeline recognition with override
55        let pp_override = r#"{"MyCustomOCR": {"recognition": "OCR", "roi": [100, 100, 200, 300]}}"#;
56        if let Ok(img_buf) = buffer::MaaImageBuffer::new() {
57            let reco_id = context.run_recognition("MyCustomOCR", pp_override, &img_buf);
58            println!("  run_recognition result: {:?}", reco_id);
59        }
60
61        // 2. Take a new screenshot via tasker's controller
62        let tasker_ptr = context.tasker_handle();
63        if !tasker_ptr.is_null() {
64            // Note: In real usage, you would use the Tasker's controller reference
65            println!("  tasker handle available for controller access");
66        }
67
68        // 3. Async click - post now, will wait later
69        // (In real code, you'd get controller from context.tasker)
70        println!("  [Demo] Would post async click at (10, 20)");
71
72        // 4. Override pipeline for all subsequent operations in this context
73        let _ = context.override_pipeline(r#"{"MyCustomOCR": {"roi": [1, 1, 114, 514]}}"#);
74
75        // 5. Check if tasker is stopping - IMPORTANT for responsive cancellation
76        // Note: Context provides tasker_handle() which returns a raw pointer.
77        // In production code, you should wrap this or use the Tasker instance directly.
78        // Here we demonstrate the raw API call for completeness.
79        let tasker_ptr = context.tasker_handle();
80        if !tasker_ptr.is_null() {
81            // Using sys:: directly requires unsafe - this matches C API usage
82            let is_stopping = unsafe { sys::MaaTaskerStopping(tasker_ptr) != 0 };
83            if is_stopping {
84                println!("  Task is stopping, returning early!");
85                return Some((
86                    common::Rect {
87                        x: 0,
88                        y: 0,
89                        width: 0,
90                        height: 0,
91                    },
92                    r#"{"status": "Task Stopped"}"#.to_string(),
93                ));
94            }
95        }
96
97        // 6. Wait for the async click to complete
98        println!("  [Demo] Async click would complete here");
99
100        // 7. Clone context for independent operations (modifications won't affect original)
101        if let Ok(new_ctx) = context.clone_context() {
102            let _ = new_ctx.override_pipeline(r#"{"MyCustomOCR": {"roi": [100, 200, 300, 400]}}"#);
103
104            // Run recognition and use the result
105            if let Ok(img_buf) = buffer::MaaImageBuffer::new() {
106                let reco_id = new_ctx.run_recognition("MyCustomOCR", "{}", &img_buf);
107
108                // If recognition succeeded, get the tasker to retrieve details
109                if reco_id.is_ok() {
110                    // In a real scenario, you would:
111                    // 1. Get recognition detail from tasker
112                    // 2. Check if it hit
113                    // 3. Use the box coordinates to click
114                    println!("  [Demo] Would get reco detail and click on result box");
115
116                    // Example of clicking on recognition result box:
117                    // if let Ok(Some(detail)) = tasker.get_recognition_detail(reco_id) {
118                    //     if detail.hit {
119                    //         let box_rect = detail.box_rect;
120                    //         controller.post_click(box_rect.x, box_rect.y).wait();
121                    //     }
122                    // }
123                }
124            }
125            // new_ctx changes don't affect original context
126        }
127
128        // 8. Get current task ID
129        let task_id = context.task_id();
130        println!("  current task_id: {}", task_id);
131
132        // 9. Get task job for result retrieval
133        let task_job = context.get_task_job();
134        if let Ok(Some(detail)) = task_job.get(false) {
135            println!("  task entry: {}", detail.entry);
136        }
137
138        // Return recognition result: bounding box + detail JSON
139        Some((
140            common::Rect {
141                x: 0,
142                y: 0,
143                width: 100,
144                height: 100,
145            },
146            r#"{"message": "Hello World!"}"#.to_string(),
147        ))
148    }
Source

pub unsafe fn from_raw(handle: *mut MaaImageBuffer) -> Self

Create from an existing handle.

§Safety

This function assumes the handle is valid. The returned buffer will NOT take ownership of the handle (it won’t be destroyed on drop). Use this when you are borrowing a handle from the C API.

Source

pub fn from_handle(handle: *mut MaaImageBuffer) -> Option<Self>

Create from an existing handle safely (checks for null). Returns None if handle is null.

Source

pub fn as_ptr(&self) -> *mut MaaImageBuffer

Get the underlying raw handle.

Source

pub fn raw(&self) -> *mut MaaImageBuffer

Get the underlying raw handle (alias for as_ptr).

Source§

impl MaaImageBuffer

Source

pub fn is_empty(&self) -> bool

Check if the buffer is empty (contains no image data).

Source

pub fn clear(&mut self) -> MaaResult<()>

Clear the buffer, releasing any image data.

Source

pub fn width(&self) -> i32

Get the image width in pixels.

Source

pub fn height(&self) -> i32

Get the image height in pixels.

Source

pub fn channels(&self) -> i32

Get the number of color channels (e.g., 3 for RGB, 4 for RGBA).

Source

pub fn image_type(&self) -> i32

Get the OpenCV image type constant.

Source

pub fn to_vec(&self) -> Option<Vec<u8>>

Get the encoded image data as a byte vector (PNG format).

Source

pub fn raw_data(&self) -> Option<&[u8]>

Get the raw image data (BGR format, row-major).

Source

pub fn set_raw_data( &mut self, data: &[u8], width: i32, height: i32, img_type: i32, ) -> MaaResult<()>

Set the image from raw BGR data.

Source

pub fn set(&mut self, data: &[u8], width: i32, height: i32) -> MaaResult<()>

Set the image from raw BGR data (assuming 3 channels, CV_8UC3).

Source

pub fn set_encoded(&mut self, data: &[u8]) -> MaaResult<()>

Set the image from encoded data (PNG/JPEG).

Source

pub fn resize(&mut self, width: i32, height: i32) -> MaaResult<()>

Resize the image.

  • width: Target width, 0 for auto aspect ratio.
  • height: Target height, 0 for auto aspect ratio.

Trait Implementations§

Source§

impl Debug for MaaImageBuffer

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for MaaImageBuffer

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Drop for MaaImageBuffer

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl Send for MaaImageBuffer

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.