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
use serde::{Deserialize, Serialize};

use crate::{
    error::Error,
    instance::MaaInstance,
    internal,
    maa_bool, string, MaaResult,
};

#[cfg(feature = "win32")]
use crate::controller::win32::MaaWin32Hwnd;

#[cfg(feature = "adb")]
use crate::controller::adb::MaaAdbControllerType;

pub struct MaaToolkit;

impl MaaToolkit {
    /// Initialize the MaaToolkit
    ///
    /// # Errors
    ///
    /// Returns an error if the toolkit initialization fails
    pub fn new() -> MaaResult<Self> {
        let toolkit_init_ret = unsafe { internal::MaaToolkitInit() };

        if !maa_bool!(toolkit_init_ret) {
            return Err(Error::MaaToolkitInitError);
        }

        Ok(Self)
    }

    pub fn new_with_options<T: Serialize>(user_path: String, config: T) -> MaaResult<Self> {
        let user_path = internal::to_cstring(&user_path);
        let config = internal::to_cstring(&serde_json::to_string(&config).unwrap());

        let toolkit_init_ret = unsafe { internal::MaaToolkitInitOptionConfig(user_path, config) };

        if !maa_bool!(toolkit_init_ret) {
            return Err(Error::MaaToolkitInitError);
        }

        Ok(Self)
    }

    /// Find all the devices
    ///
    /// # Errors
    ///
    /// Return an error if fails to convert MaaStringView to String
    #[cfg(feature = "adb")]
    #[doc(cfg(feature = "adb"))]
    pub fn find_adb_device(&self) -> MaaResult<Vec<AdbDeviceInfo>> {
        let ret = unsafe { internal::MaaToolkitPostFindDevice() };

        if !maa_bool!(ret) {
            return Err(Error::MaaToolkitPostFindDeviceError);
        }

        let device_count = unsafe { internal::MaaToolkitWaitForFindDeviceToComplete() };

        self.get_adb_devices_info(device_count)
    }

    /// Find all the devices with a given adb path
    ///
    /// # Errors
    ///
    /// Return an error if fails to convert MaaStringView to String
    #[cfg(feature = "adb")]
    #[doc(cfg(feature = "adb"))]
    pub fn find_adb_device_with_adb(&self, adb_path: &str) -> MaaResult<Vec<AdbDeviceInfo>> {
        let adb_path = internal::to_cstring(adb_path);
        let ret = unsafe { internal::MaaToolkitPostFindDeviceWithAdb(adb_path) };

        if !maa_bool!(ret) {
            return Err(Error::MaaToolkitPostFindDeviceError);
        }

        let device_count = unsafe { internal::MaaToolkitWaitForFindDeviceToComplete() };

        self.get_adb_devices_info(device_count)
    }

    #[cfg(feature = "adb")]
    #[doc(cfg(feature = "adb"))]
    fn get_adb_devices_info(&self, device_count: u64) -> MaaResult<Vec<AdbDeviceInfo>> {
        let mut devices = Vec::with_capacity(device_count as usize);

        for i in 0..device_count {
            let name = unsafe { internal::MaaToolkitGetDeviceName(i) };
            let adb_path = unsafe { internal::MaaToolkitGetDeviceAdbPath(i) };
            let adb_serial = unsafe { internal::MaaToolkitGetDeviceAdbSerial(i) };
            let adb_controller_type = unsafe { internal::MaaToolkitGetDeviceAdbControllerType(i) };
            let adb_config = unsafe { internal::MaaToolkitGetDeviceAdbConfig(i) };

            let name = string!(name);
            let adb_path = string!(adb_path);
            let adb_serial = string!(adb_serial);
            let adb_config = string!(adb_config);
            let adb_controller_type = MaaAdbControllerType::try_from(adb_controller_type)?;

            devices.push(AdbDeviceInfo {
                name,
                adb_path,
                adb_serial,
                adb_controller_type,
                adb_config,
            });
        }

        Ok(devices)
    }

    pub fn register_custom_recognizer_executor<T>(
        &self,
        handle: MaaInstance<T>,
        recognizer_name: &str,
        recognizer_exec_path: &str,
        recognizer_exec_param_json: &str,
    ) -> MaaResult<()> {
        let recognizer_name = internal::to_cstring(recognizer_name);
        let recognizer_exec_path = internal::to_cstring(recognizer_exec_path);
        let recognizer_exec_param_json = internal::to_cstring(recognizer_exec_param_json);
        let ret = unsafe {
            internal::MaaToolkitRegisterCustomRecognizerExecutor(
                *handle,
                recognizer_name,
                recognizer_exec_path,
                recognizer_exec_param_json,
            )
        };

        if !maa_bool!(ret) {
            return Err(Error::MaaToolkitRegisterCustomRecognizerExecutorError);
        }

        Ok(())
    }

    pub fn unregister_custom_recognizer_executor<T>(
        &self,
        handle: MaaInstance<T>,
        recognizer_name: &str,
    ) -> MaaResult<()> {
        let recognizer_name = internal::to_cstring(recognizer_name);

        let ret = unsafe {
            internal::MaaToolkitUnregisterCustomRecognizerExecutor(*handle, recognizer_name)
        };

        if !maa_bool!(ret) {
            return Err(Error::MaaToolkitUnregisterCustomRecognizerExecutorError);
        }

        Ok(())
    }

    pub fn register_custom_action_executor<T>(
        &self,
        handle: MaaInstance<T>,
        action_name: &str,
        action_exec_path: &str,
        action_exec_param_json: &str,
    ) -> MaaResult<()> {
        let action_name = internal::to_cstring(action_name);
        let action_exec_path = internal::to_cstring(action_exec_path);
        let action_exec_param_json = internal::to_cstring(action_exec_param_json);

        let ret = unsafe {
            internal::MaaToolkitRegisterCustomActionExecutor(
                *handle,
                action_name,
                action_exec_path,
                action_exec_param_json,
            )
        };

        if !maa_bool!(ret) {
            return Err(Error::MaaToolkitRegisterCustomRecognizerExecutorError);
        }

        Ok(())
    }

    pub fn unregister_custom_action_executor<T>(
        &self,
        handle: MaaInstance<T>,
        action_name: &str,
    ) -> MaaResult<()> {
        let action_name = internal::to_cstring(action_name);

        let ret =
            unsafe { internal::MaaToolkitUnregisterCustomActionExecutor(*handle, action_name) };

        if !maa_bool!(ret) {
            return Err(Error::MaaToolkitUnregisterCustomRecognizerExecutorError);
        }

        Ok(())
    }

    /// Find all the windows with a given class name and window name
    ///
    /// # Parameters
    /// - `class_name`: The class name of the window
    /// - `window_name`: The window name of the window
    /// - `find`: If true, find the window using system win32 api, otherwise search the window with text match
    #[cfg(feature = "win32")]
    #[doc(cfg(feature = "win32"))]
    pub fn find_win32_window(
        &self,
        class_name: &str,
        window_name: &str,
        find: bool,
    ) -> Vec<MaaWin32Hwnd> {
        let class_name = internal::to_cstring(class_name);
        let window_name = internal::to_cstring(window_name);

        let hwnd_count = unsafe {
            if find {
                internal::MaaToolkitFindWindow(class_name, window_name)
            } else {
                internal::MaaToolkitSearchWindow(class_name, window_name)
            }
        };

        let mut hwnds = Vec::with_capacity(hwnd_count as usize);

        for i in 0..hwnd_count {
            let hwnd = unsafe { internal::MaaToolkitGetWindow(i) };
            hwnds.push(MaaWin32Hwnd(hwnd));
        }

        hwnds
    }

    #[cfg(feature = "win32")]
    #[doc(cfg(feature = "win32"))]
    pub fn get_cursor_window(&self) -> MaaWin32Hwnd {
        let hwnd = unsafe { internal::MaaToolkitGetCursorWindow() };
        MaaWin32Hwnd(hwnd)
    }

    #[cfg(feature = "win32")]
    #[doc(cfg(feature = "win32"))]
    pub fn get_desktop_window(&self) -> MaaWin32Hwnd {
        let hwnd = unsafe { internal::MaaToolkitGetDesktopWindow() };
        MaaWin32Hwnd(hwnd)
    }

    #[cfg(feature = "win32")]
    #[doc(cfg(feature = "win32"))]
    pub fn get_foreground_window(&self) -> MaaWin32Hwnd {
        let hwnd = unsafe { internal::MaaToolkitGetForegroundWindow() };
        MaaWin32Hwnd(hwnd)
    }
}

impl Drop for MaaToolkit {
    fn drop(&mut self) {
        unsafe { internal::MaaToolkitUninit() };
    }
}

unsafe impl Send for MaaToolkit {}
unsafe impl Sync for MaaToolkit {}

#[derive(Serialize, Deserialize)]
#[cfg(feature = "adb")]
pub struct AdbDeviceInfo {
    pub name: String,
    pub adb_path: String,
    pub adb_serial: String,
    pub adb_controller_type: MaaAdbControllerType,
    pub adb_config: String,
}

#[cfg(test)]
mod test {
    use super::MaaToolkit;

    #[test]
    fn test_init() {
        let toolkit = MaaToolkit::new();

        assert!(toolkit.is_ok());
    }
}