maa-framework 1.23.0

Rust bindings for MaaFramework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! Device discovery and configuration utilities.

use serde::{Deserialize, Serialize};

use crate::{MaaError, MaaResult, common, sys};
use std::ffi::{CStr, CString};
use std::path::{Path, PathBuf};
use std::sync::Once;

/// Information about a connected ADB device.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdbDevice {
    /// Device display name.
    pub name: String,
    /// Path to the ADB executable.
    pub adb_path: PathBuf,
    /// Device address (e.g., "127.0.0.1:5555").
    pub address: String,
    /// Supported screencap methods (bitflags).
    pub screencap_methods: u64,
    /// Supported input methods (bitflags).
    pub input_methods: u64,
    /// Device configuration as JSON.
    pub config: serde_json::Value,
}

/// Information about a desktop window (Win32).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DesktopWindow {
    /// Window handle (HWND).
    pub hwnd: usize,
    /// Window class name.
    pub class_name: String,
    /// Window title.
    pub window_name: String,
}

/// A gamescope instance discovered from the session.
///
/// Combines the display number, PipeWire capture node and libei (EIS) socket of
/// a single gamescope instance into one model.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GamescopeInstance {
    /// Display number (`n` in `gamescope-<n>`).
    pub display_no: u32,
    /// PipeWire node ID. Usable as `pw_node_id` in
    /// [`crate::common::LinuxControllerConfig`]. `0` means no capture node.
    pub pipewire_node_id: u32,
    /// EIS socket path. Usable as `eis_socket_path` in
    /// [`crate::common::LinuxControllerConfig`]. Empty when no EIS socket exists.
    pub eis_socket_path: String,
}

/// macOS system permission types used by toolkit helpers.
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MacOSPermission {
    /// Screen recording / screen capture permission.
    ScreenCapture = sys::MaaMacOSPermissionEnum_MaaMacOSPermissionScreenCapture as i32,
    /// Accessibility permission for input simulation.
    Accessibility = sys::MaaMacOSPermissionEnum_MaaMacOSPermissionAccessibility as i32,
}

/// Toolkit utilities for device discovery and configuration.
pub struct Toolkit;

static AGENT_SERVER_INIT_OPTION_WARNING: Once = Once::new();

impl Toolkit {
    #[inline]
    fn unsupported(api: &str) -> MaaError {
        MaaError::UnsupportedInAgentServer(api.to_string())
    }

    fn maybe_warn_init_option_in_agent_server() {
        if std::env::var_os("MAA_RUST_WARN_AGENTSERVER_TOOLKIT_INIT").is_none() {
            return;
        }

        AGENT_SERVER_INIT_OPTION_WARNING.call_once(|| {
            eprintln!(
                "Warning: Toolkit::init_option is deprecated in AgentServer; only log_dir is applied."
            );
        });
    }

    /// Initialize MAA framework options.
    ///
    /// # Arguments
    /// * `user_path` - Path to user data directory
    /// * `default_config` - Default configuration JSON string
    pub fn init_option(user_path: &str, default_config: &str) -> MaaResult<()> {
        if crate::is_agent_server_context() {
            let _ = default_config;
            Self::maybe_warn_init_option_in_agent_server();
            let log_dir = Path::new(user_path).join("debug");
            return crate::configure_logging(log_dir.to_string_lossy().as_ref());
        }

        let c_path = CString::new(user_path)?;
        let c_config = CString::new(default_config)?;
        let ret = unsafe { sys::MaaToolkitConfigInitOption(c_path.as_ptr(), c_config.as_ptr()) };
        common::check_bool(ret)
    }

    /// Find connected ADB devices.
    ///
    /// Scans for all known Android emulators and connected ADB devices.
    ///
    /// # Returns
    /// List of discovered ADB devices with their configurations.
    pub fn find_adb_devices() -> MaaResult<Vec<AdbDevice>> {
        if crate::is_agent_server_context() {
            return Err(Self::unsupported("Toolkit::find_adb_devices"));
        }
        Self::find_adb_devices_impl(None)
    }

    /// Find connected ADB devices using a specific ADB binary.
    ///
    /// # Arguments
    /// * `adb_path` - Path to the ADB binary to use for discovery
    ///
    /// # Returns
    /// List of discovered ADB devices with their configurations.
    pub fn find_adb_devices_with_adb(adb_path: &str) -> MaaResult<Vec<AdbDevice>> {
        if crate::is_agent_server_context() {
            return Err(Self::unsupported("Toolkit::find_adb_devices_with_adb"));
        }
        Self::find_adb_devices_impl(Some(adb_path))
    }

    fn find_adb_devices_impl(specified_adb: Option<&str>) -> MaaResult<Vec<AdbDevice>> {
        let list = unsafe { sys::MaaToolkitAdbDeviceListCreate() };
        if list.is_null() {
            return Err(MaaError::NullPointer);
        }

        let _guard = AdbDeviceListGuard(list);

        unsafe {
            let ret = if let Some(adb_path) = specified_adb {
                let c_path = CString::new(adb_path)?;
                sys::MaaToolkitAdbDeviceFindSpecified(c_path.as_ptr(), list)
            } else {
                sys::MaaToolkitAdbDeviceFind(list)
            };
            common::check_bool(ret)?;

            let count = sys::MaaToolkitAdbDeviceListSize(list);
            let mut devices = Vec::with_capacity(count as usize);

            for i in 0..count {
                let device_ptr = sys::MaaToolkitAdbDeviceListAt(list, i);
                if device_ptr.is_null() {
                    continue;
                }

                let name = CStr::from_ptr(sys::MaaToolkitAdbDeviceGetName(device_ptr))
                    .to_string_lossy()
                    .into_owned();

                let adb_path_str = CStr::from_ptr(sys::MaaToolkitAdbDeviceGetAdbPath(device_ptr))
                    .to_string_lossy()
                    .into_owned();

                let address = CStr::from_ptr(sys::MaaToolkitAdbDeviceGetAddress(device_ptr))
                    .to_string_lossy()
                    .into_owned();

                let screencap_methods =
                    sys::MaaToolkitAdbDeviceGetScreencapMethods(device_ptr) as u64;
                let input_methods = sys::MaaToolkitAdbDeviceGetInputMethods(device_ptr) as u64;

                let config_str =
                    CStr::from_ptr(sys::MaaToolkitAdbDeviceGetConfig(device_ptr)).to_string_lossy();
                let config = serde_json::from_str(&config_str).unwrap_or(serde_json::Value::Null);

                devices.push(AdbDevice {
                    name,
                    adb_path: PathBuf::from(adb_path_str),
                    address,
                    screencap_methods,
                    input_methods,
                    config,
                });
            }
            Ok(devices)
        }
    }

    /// Find all desktop windows (Win32 only).
    ///
    /// # Returns
    /// List of visible desktop windows.
    pub fn find_desktop_windows() -> MaaResult<Vec<DesktopWindow>> {
        if crate::is_agent_server_context() {
            return Err(Self::unsupported("Toolkit::find_desktop_windows"));
        }

        let list = unsafe { sys::MaaToolkitDesktopWindowListCreate() };
        if list.is_null() {
            return Err(MaaError::NullPointer);
        }

        let _guard = DesktopWindowListGuard(list);

        unsafe {
            let ret = sys::MaaToolkitDesktopWindowFindAll(list);
            common::check_bool(ret)?;

            let count = sys::MaaToolkitDesktopWindowListSize(list);
            let mut windows = Vec::with_capacity(count as usize);

            for i in 0..count {
                let win_ptr = sys::MaaToolkitDesktopWindowListAt(list, i);
                if win_ptr.is_null() {
                    continue;
                }

                let hwnd = sys::MaaToolkitDesktopWindowGetHandle(win_ptr) as usize;

                let class_name = CStr::from_ptr(sys::MaaToolkitDesktopWindowGetClassName(win_ptr))
                    .to_string_lossy()
                    .into_owned();

                let window_name =
                    CStr::from_ptr(sys::MaaToolkitDesktopWindowGetWindowName(win_ptr))
                        .to_string_lossy()
                        .into_owned();

                windows.push(DesktopWindow {
                    hwnd,
                    class_name,
                    window_name,
                });
            }
            Ok(windows)
        }
    }

    /// Check whether the current process has the specified macOS permission.
    pub fn macos_check_permission(permission: MacOSPermission) -> MaaResult<bool> {
        if crate::is_agent_server_context() {
            return Err(Self::unsupported("Toolkit::macos_check_permission"));
        }

        let ret =
            unsafe { sys::MaaToolkitMacOSCheckPermission(permission as sys::MaaMacOSPermission) };
        Ok(ret != 0)
    }

    /// Request the specified macOS permission from the system.
    ///
    /// A successful return means the request API call succeeded. It does not
    /// necessarily mean the user has already granted the permission.
    pub fn macos_request_permission(permission: MacOSPermission) -> MaaResult<bool> {
        if crate::is_agent_server_context() {
            return Err(Self::unsupported("Toolkit::macos_request_permission"));
        }

        let ret =
            unsafe { sys::MaaToolkitMacOSRequestPermission(permission as sys::MaaMacOSPermission) };
        Ok(ret != 0)
    }

    /// Open the corresponding macOS settings page for the permission.
    pub fn macos_reveal_permission_settings(permission: MacOSPermission) -> MaaResult<bool> {
        if crate::is_agent_server_context() {
            return Err(Self::unsupported(
                "Toolkit::macos_reveal_permission_settings",
            ));
        }

        let ret = unsafe {
            sys::MaaToolkitMacOSRevealPermissionSettings(permission as sys::MaaMacOSPermission)
        };
        Ok(ret != 0)
    }

    /// Find gamescope instances on the session.
    ///
    /// Each instance bundles a display number, a PipeWire capture node and an
    /// EIS socket. The `pipewire_node_id` / `eis_socket_path` can be passed to
    /// [`crate::common::LinuxControllerConfig`] to capture and control a
    /// gamescope window directly, without going through the ScreenCast portal.
    ///
    /// Returns an empty list when gamescope is not running, and on non-Linux
    /// platforms (where the underlying C API returns no instances).
    pub fn find_gamescope_instances() -> MaaResult<Vec<GamescopeInstance>> {
        if crate::is_agent_server_context() {
            return Err(Self::unsupported("Toolkit::find_gamescope_instances"));
        }

        let list = unsafe { sys::MaaToolkitGamescopeInstanceListCreate() };
        if list.is_null() {
            return Err(MaaError::NullPointer);
        }

        let _guard = GamescopeInstanceListGuard(list);

        unsafe {
            common::check_bool(sys::MaaToolkitGamescopeInstanceFindAll(list))?;

            let count = sys::MaaToolkitGamescopeInstanceListSize(list);
            let mut instances = Vec::with_capacity(count as usize);

            for i in 0..count {
                let instance_ptr = sys::MaaToolkitGamescopeInstanceListAt(list, i);
                if instance_ptr.is_null() {
                    continue;
                }

                let display_no = sys::MaaToolkitGamescopeInstanceGetDisplayNo(instance_ptr);
                let pipewire_node_id =
                    sys::MaaToolkitGamescopeInstanceGetPipeWireNodeId(instance_ptr);
                let eis_socket_path =
                    sys::MaaToolkitGamescopeInstanceGetEisSocketPath(instance_ptr);
                if eis_socket_path.is_null() {
                    return Err(MaaError::NullPointer);
                }
                let eis_socket_path = CStr::from_ptr(eis_socket_path)
                    .to_string_lossy()
                    .into_owned();

                instances.push(GamescopeInstance {
                    display_no,
                    pipewire_node_id,
                    eis_socket_path,
                });
            }
            Ok(instances)
        }
    }
}

struct AdbDeviceListGuard(*mut sys::MaaToolkitAdbDeviceList);
impl Drop for AdbDeviceListGuard {
    fn drop(&mut self) {
        unsafe { sys::MaaToolkitAdbDeviceListDestroy(self.0) }
    }
}

struct DesktopWindowListGuard(*mut sys::MaaToolkitDesktopWindowList);
impl Drop for DesktopWindowListGuard {
    fn drop(&mut self) {
        unsafe { sys::MaaToolkitDesktopWindowListDestroy(self.0) }
    }
}

struct GamescopeInstanceListGuard(*mut sys::MaaToolkitGamescopeInstanceList);
impl Drop for GamescopeInstanceListGuard {
    fn drop(&mut self) {
        unsafe { sys::MaaToolkitGamescopeInstanceListDestroy(self.0) }
    }
}

/// XDG Desktop Portal ScreenCast helper (Linux only).
///
/// Opens a ScreenCast portal session to obtain a PipeWire stream, whose FD and
/// node ID can be handed to [`crate::controller::Controller::new_linux`] via
/// [`crate::common::LinuxControllerConfig`]'s `pw_socket_fd` / `pw_node_id`.
///
/// On non-Linux platforms, [`PortalHelper::new`] returns
/// [`MaaError::NullPointer`] because the underlying C API is unavailable there.
pub struct PortalHelper {
    handle: *mut sys::MaaToolkitPortalHelper,
}

impl PortalHelper {
    /// Create a new portal helper.
    pub fn new() -> MaaResult<Self> {
        let handle = unsafe { sys::MaaToolkitPortalHelperCreate() };
        if handle.is_null() {
            return Err(MaaError::NullPointer);
        }
        Ok(Self { handle })
    }

    /// Open the ScreenCast portal stream (create DBus session, select sources,
    /// and start the stream).
    pub fn open_stream(&self) -> MaaResult<()> {
        common::check_bool(unsafe { sys::MaaToolkitPortalHelperOpenStream(self.handle) })
    }

    /// Whether the portal session is persistent (i.e. can be restored later).
    pub fn get_persist(&self) -> bool {
        unsafe { sys::MaaToolkitPortalHelperGetPersist(self.handle) != 0 }
    }

    /// Set whether the portal session should persist for later restoration.
    pub fn set_persist(&self, enable: bool) {
        unsafe { sys::MaaToolkitPortalHelperSetPersist(self.handle, enable as sys::MaaBool) };
    }

    /// The PipeWire socket FD, or `-1` if the stream has not been opened yet.
    pub fn get_pipewire_fd(&self) -> i32 {
        unsafe { sys::MaaToolkitPortalHelperGetPipeWireFD(self.handle) }
    }

    /// The PipeWire node ID, or `0` if the stream has not been opened yet.
    pub fn get_pipewire_node_id(&self) -> u32 {
        unsafe { sys::MaaToolkitPortalHelperGetPipeWireNodeID(self.handle) }
    }

    /// The restore token used to restore a persistent session.
    ///
    /// Returns an empty string when no token is available.
    pub fn get_restore_token(&self) -> String {
        let ptr = unsafe { sys::MaaToolkitPortalHelperGetRestoreToken(self.handle) };
        if ptr.is_null() {
            return String::new();
        }
        unsafe { CStr::from_ptr(ptr) }
            .to_string_lossy()
            .into_owned()
    }

    /// Set the restore token to restore a previous portal session.
    pub fn set_restore_token(&self, token: &str) -> MaaResult<()> {
        let c_token = CString::new(token)?;
        unsafe { sys::MaaToolkitPortalHelperSetRestoreToken(self.handle, c_token.as_ptr()) };
        Ok(())
    }
}

impl Drop for PortalHelper {
    fn drop(&mut self) {
        unsafe { sys::MaaToolkitPortalHelperDestroy(self.handle) };
    }
}