maa-framework 1.15.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
//! Structured notification parsing for event callbacks.
//!
//! This module provides typed structures and parsing utilities for the event
//! notifications from MaaFramework. Instead of manually parsing JSON strings,
//! use these helpers to work with strongly-typed event data.
//!
//! # Example
//!
//! ```
//! use maa_framework::notification::{self, NotificationType};
//! use maa_framework::tasker::Tasker;
//!
//! fn example(tasker: &Tasker) -> maa_framework::error::MaaResult<()> {
//!     tasker.add_sink(|message, details| {
//!         let noti_type = notification::parse_type(message);
//!         
//!         if message.starts_with("Resource.Loading") {
//!             if let Some(detail) = notification::parse_resource_loading(details) {
//!                 println!("Resource {} loading: {:?}", detail.res_id, noti_type);
//!             }
//!         }
//!     })?;
//!     Ok(())
//! }
//! ```

use serde::{Deserialize, Serialize};
use serde_json::Value;

// === Notification Type ===

/// Type of notification event.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NotificationType {
    /// Operation is starting
    Starting,
    /// Operation succeeded
    Succeeded,
    /// Operation failed
    Failed,
    /// Unknown notification type
    Unknown,
}

impl NotificationType {
    /// Check if this is a starting notification.
    pub fn is_starting(&self) -> bool {
        matches!(self, Self::Starting)
    }

    /// Check if this is a succeeded notification.
    pub fn is_succeeded(&self) -> bool {
        matches!(self, Self::Succeeded)
    }

    /// Check if this is a failed notification.
    pub fn is_failed(&self) -> bool {
        matches!(self, Self::Failed)
    }

    /// Check if the operation is complete (succeeded or failed).
    pub fn is_complete(&self) -> bool {
        matches!(self, Self::Succeeded | Self::Failed)
    }
}

impl From<&str> for NotificationType {
    fn from(s: &str) -> Self {
        if s.ends_with(".Starting") {
            NotificationType::Starting
        } else if s.ends_with(".Succeeded") {
            NotificationType::Succeeded
        } else if s.ends_with(".Failed") {
            NotificationType::Failed
        } else {
            NotificationType::Unknown
        }
    }
}

// === Event Detail Structures ===

/// Resource loading event detail.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceLoadingDetail {
    /// Resource ID
    pub res_id: i64,
    /// Resource hash
    pub hash: String,
    /// Path being loaded
    pub path: String,
}

/// Controller action event detail.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ControllerActionDetail {
    /// Controller ID
    pub ctrl_id: i64,
    /// Device UUID
    pub uuid: String,
    /// Action name
    pub action: String,
    /// Action parameters
    #[serde(default)]
    pub param: Value,
    /// Controller information (type, constructor parameters, etc.)
    #[serde(default)]
    pub info: Value,
}

/// Tasker task event detail.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskerTaskDetail {
    /// Task ID
    pub task_id: i64,
    /// Entry node name
    pub entry: String,
    /// Device UUID
    #[serde(default)]
    pub uuid: String,
    /// Resource hash
    #[serde(default)]
    pub hash: String,
}

/// Next list item for node traversal.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NextListItem {
    /// Node name
    pub name: String,
    /// Whether to jump back after execution
    #[serde(default)]
    pub jump_back: bool,
    /// Whether this is an anchor node
    #[serde(default)]
    pub anchor: bool,
}

/// Node next list event detail.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeNextListDetail {
    /// Task ID
    pub task_id: i64,
    /// Current node name
    pub name: String,
    /// List of next nodes
    #[serde(default)]
    pub list: Vec<NextListItem>,
    /// Focus configuration
    #[serde(default)]
    pub focus: Value,
}

/// Node wait-freezes event detail.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeWaitFreezesDetail {
    /// Task ID
    pub task_id: i64,
    /// Wait-freezes ID
    pub wf_id: i64,
    /// Node name
    pub name: String,
    /// Phase name
    pub phase: String,
    /// ROI
    pub roi: crate::common::Rect,
    /// Wait-freezes parameters
    #[serde(default)]
    pub param: Value,
    /// Related recognition IDs
    #[serde(default)]
    pub reco_ids: Vec<i64>,
    /// Elapsed time in ms
    #[serde(default)]
    pub elapsed: Option<u64>,
    /// Focus configuration
    #[serde(default)]
    pub focus: Value,
}

/// Node recognition event detail.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeRecognitionDetail {
    /// Task ID
    pub task_id: i64,
    /// Recognition ID
    pub reco_id: i64,
    /// Node name
    pub name: String,
    /// Focus configuration
    #[serde(default)]
    pub focus: Value,
    /// Anchor name
    pub anchor: Option<String>,
}

/// Node action event detail.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeActionDetail {
    /// Task ID
    pub task_id: i64,
    /// Action ID
    pub action_id: i64,
    /// Node name
    pub name: String,
    /// Focus configuration
    #[serde(default)]
    pub focus: Value,
}

/// Node pipeline node event detail.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodePipelineNodeDetail {
    /// Task ID
    pub task_id: i64,
    /// Node ID
    pub node_id: i64,
    /// Node name
    pub name: String,
    /// Focus configuration
    #[serde(default)]
    pub focus: Value,
}

// === Message Constants ===

/// Notification message constants.
pub mod msg {
    // Resource events
    pub const RESOURCE_LOADING_STARTING: &str = "Resource.Loading.Starting";
    pub const RESOURCE_LOADING_SUCCEEDED: &str = "Resource.Loading.Succeeded";
    pub const RESOURCE_LOADING_FAILED: &str = "Resource.Loading.Failed";

    // Controller events
    pub const CONTROLLER_ACTION_STARTING: &str = "Controller.Action.Starting";
    pub const CONTROLLER_ACTION_SUCCEEDED: &str = "Controller.Action.Succeeded";
    pub const CONTROLLER_ACTION_FAILED: &str = "Controller.Action.Failed";

    // Tasker events
    pub const TASKER_TASK_STARTING: &str = "Tasker.Task.Starting";
    pub const TASKER_TASK_SUCCEEDED: &str = "Tasker.Task.Succeeded";
    pub const TASKER_TASK_FAILED: &str = "Tasker.Task.Failed";

    // Node pipeline events
    pub const NODE_PIPELINE_NODE_STARTING: &str = "Node.PipelineNode.Starting";
    pub const NODE_PIPELINE_NODE_SUCCEEDED: &str = "Node.PipelineNode.Succeeded";
    pub const NODE_PIPELINE_NODE_FAILED: &str = "Node.PipelineNode.Failed";

    // Node recognition events
    pub const NODE_RECOGNITION_STARTING: &str = "Node.Recognition.Starting";
    pub const NODE_RECOGNITION_SUCCEEDED: &str = "Node.Recognition.Succeeded";
    pub const NODE_RECOGNITION_FAILED: &str = "Node.Recognition.Failed";

    // Node action events
    pub const NODE_ACTION_STARTING: &str = "Node.Action.Starting";
    pub const NODE_ACTION_SUCCEEDED: &str = "Node.Action.Succeeded";
    pub const NODE_ACTION_FAILED: &str = "Node.Action.Failed";

    // Node wait freezes events
    pub const NODE_WAIT_FREEZES_STARTING: &str = "Node.WaitFreezes.Starting";
    pub const NODE_WAIT_FREEZES_SUCCEEDED: &str = "Node.WaitFreezes.Succeeded";
    pub const NODE_WAIT_FREEZES_FAILED: &str = "Node.WaitFreezes.Failed";

    // Node next list events
    pub const NODE_NEXT_LIST_STARTING: &str = "Node.NextList.Starting";
    pub const NODE_NEXT_LIST_SUCCEEDED: &str = "Node.NextList.Succeeded";
    pub const NODE_NEXT_LIST_FAILED: &str = "Node.NextList.Failed";

    // Node recognition node trace events
    pub const NODE_RECOGNITION_NODE_STARTING: &str = "Node.RecognitionNode.Starting";
    pub const NODE_RECOGNITION_NODE_SUCCEEDED: &str = "Node.RecognitionNode.Succeeded";
    pub const NODE_RECOGNITION_NODE_FAILED: &str = "Node.RecognitionNode.Failed";

    // Node action node trace events
    pub const NODE_ACTION_NODE_STARTING: &str = "Node.ActionNode.Starting";
    pub const NODE_ACTION_NODE_SUCCEEDED: &str = "Node.ActionNode.Succeeded";
    pub const NODE_ACTION_NODE_FAILED: &str = "Node.ActionNode.Failed";
}

// === Parse Functions ===

/// Parse notification type from message string.
///
/// # Example
/// ```
/// use maa_framework::notification::{self, NotificationType};
///
/// let noti_type = notification::parse_type("Resource.Loading.Succeeded");
/// assert_eq!(noti_type, NotificationType::Succeeded);
/// ```
pub fn parse_type(msg: &str) -> NotificationType {
    NotificationType::from(msg)
}

/// Parse resource loading event detail from JSON.
pub fn parse_resource_loading(details: &str) -> Option<ResourceLoadingDetail> {
    serde_json::from_str(details).ok()
}

/// Parse controller action event detail from JSON.
pub fn parse_controller_action(details: &str) -> Option<ControllerActionDetail> {
    serde_json::from_str(details).ok()
}

/// Parse tasker task event detail from JSON.
pub fn parse_tasker_task(details: &str) -> Option<TaskerTaskDetail> {
    serde_json::from_str(details).ok()
}

/// Parse node next list event detail from JSON.
pub fn parse_node_next_list(details: &str) -> Option<NodeNextListDetail> {
    serde_json::from_str(details).ok()
}

/// Parse node wait-freezes event detail from JSON.
pub fn parse_node_wait_freezes(details: &str) -> Option<NodeWaitFreezesDetail> {
    serde_json::from_str(details).ok()
}

/// Parse node recognition event detail from JSON.
pub fn parse_node_recognition(details: &str) -> Option<NodeRecognitionDetail> {
    serde_json::from_str(details).ok()
}

/// Parse node action event detail from JSON.
pub fn parse_node_action(details: &str) -> Option<NodeActionDetail> {
    serde_json::from_str(details).ok()
}

/// Parse node pipeline node event detail from JSON.
pub fn parse_node_pipeline_node(details: &str) -> Option<NodePipelineNodeDetail> {
    serde_json::from_str(details).ok()
}

// === Context Event ===

/// Enum representing parsed Context events.
#[derive(Debug, Clone)]
pub enum ContextEvent {
    NodeNextList(NotificationType, NodeNextListDetail),
    NodeRecognition(NotificationType, NodeRecognitionDetail),
    NodeAction(NotificationType, NodeActionDetail),
    NodeWaitFreezes(NotificationType, NodeWaitFreezesDetail),
    NodePipelineNode(NotificationType, NodePipelineNodeDetail),
    NodeRecognitionNode(NotificationType, NodePipelineNodeDetail),
    NodeActionNode(NotificationType, NodePipelineNodeDetail),
    Unknown(String, Value),
}

impl ContextEvent {
    /// Parse a raw notification into a strongly-typed ContextEvent.
    pub fn from_notification(msg: &str, details: &str) -> Option<Self> {
        let noti_type = NotificationType::from(msg);

        let parse_json = || -> Option<Value> { serde_json::from_str(details).ok() };

        if msg.starts_with("Node.NextList") {
            let detail = parse_node_next_list(details)?;
            return Some(ContextEvent::NodeNextList(noti_type, detail));
        }

        if msg.starts_with("Node.Recognition.") {
            let detail = parse_node_recognition(details)?;
            return Some(ContextEvent::NodeRecognition(noti_type, detail));
        }

        if msg.starts_with("Node.Action.") {
            let detail = parse_node_action(details)?;
            return Some(ContextEvent::NodeAction(noti_type, detail));
        }

        if msg.starts_with("Node.WaitFreezes") {
            let detail = parse_node_wait_freezes(details)?;
            return Some(ContextEvent::NodeWaitFreezes(noti_type, detail));
        }

        if msg.starts_with("Node.PipelineNode") {
            let detail = parse_node_pipeline_node(details)?;
            return Some(ContextEvent::NodePipelineNode(noti_type, detail));
        }

        if msg.starts_with("Node.RecognitionNode") {
            let detail = parse_node_pipeline_node(details)?;
            return Some(ContextEvent::NodeRecognitionNode(noti_type, detail));
        }

        if msg.starts_with("Node.ActionNode") {
            let detail = parse_node_pipeline_node(details)?;
            return Some(ContextEvent::NodeActionNode(noti_type, detail));
        }

        Some(ContextEvent::Unknown(
            msg.to_string(),
            parse_json().unwrap_or(Value::Null),
        ))
    }
}

// === Event Sink Traits ===

/// Trait for handling resource events.
pub trait ResourceEventHandler: Send + Sync {
    /// Called when a resource loading event occurs.
    fn on_resource_loading(&self, _noti_type: NotificationType, _detail: ResourceLoadingDetail) {}

    /// Called when an unknown notification is received.
    fn on_unknown(&self, _msg: &str, _details: &Value) {}
}

/// Trait for handling controller events.
pub trait ControllerEventHandler: Send + Sync {
    /// Called when a controller action event occurs.
    fn on_controller_action(&self, _noti_type: NotificationType, _detail: ControllerActionDetail) {}

    /// Called when an unknown notification is received.
    fn on_unknown(&self, _msg: &str, _details: &Value) {}
}

/// Trait for handling tasker events.
pub trait TaskerEventHandler: Send + Sync {
    /// Called when a tasker task event occurs.
    fn on_tasker_task(&self, _noti_type: NotificationType, _detail: TaskerTaskDetail) {}

    /// Called when an unknown notification is received.
    fn on_unknown(&self, _msg: &str, _details: &Value) {}
}

/// Trait for handling context/node events.
pub trait ContextEventHandler: Send + Sync {
    /// Called when a node next list event occurs.
    fn on_node_next_list(&self, _noti_type: NotificationType, _detail: NodeNextListDetail) {}

    /// Called when a node recognition event occurs.
    fn on_node_recognition(&self, _noti_type: NotificationType, _detail: NodeRecognitionDetail) {}

    /// Called when a node action event occurs.
    fn on_node_action(&self, _noti_type: NotificationType, _detail: NodeActionDetail) {}

    /// Called when a node wait-freezes event occurs.
    fn on_node_wait_freezes(&self, _noti_type: NotificationType, _detail: NodeWaitFreezesDetail) {}

    /// Called when a node pipeline node event occurs.
    fn on_node_pipeline_node(&self, _noti_type: NotificationType, _detail: NodePipelineNodeDetail) {
    }

    /// Called when a node recognition node (trace) event occurs.
    fn on_node_recognition_node(
        &self,
        _noti_type: NotificationType,
        _detail: NodePipelineNodeDetail,
    ) {
    }

    /// Called when a node action node (trace) event occurs.
    fn on_node_action_node(&self, _noti_type: NotificationType, _detail: NodePipelineNodeDetail) {}

    /// Called when an unknown notification is received.
    fn on_unknown(&self, _msg: &str, _details: &Value) {}
}

// === MaaEvent ===

/// Unified event enum for all framework notifications.
///
/// This enum encapsulates all possible event types emitted by the framework, providing
/// a type-safe way to handle notifications from `Tasker`, `Controller`, or `Resource`.
/// Each variant wraps a detailed structure containing relevant information about the event.
///
/// # See Also
/// * [`EventSink`](crate::event_sink::EventSink) - The trait for receiving these events.
/// * [`Tasker::add_event_sink`](crate::tasker::Tasker::add_event_sink) - Registering an event sink.
#[derive(Debug, Clone)]
pub enum MaaEvent {
    // --- Resource Events ---
    /// Triggered when a resource starts loading.
    ResourceLoadingStarting(ResourceLoadingDetail),
    /// Triggered when a resource is successfully loaded.
    ResourceLoadingSucceeded(ResourceLoadingDetail),
    /// Triggered when resource loading fails.
    ResourceLoadingFailed(ResourceLoadingDetail),

    // --- Controller Events ---
    /// Triggered before a controller performs an action (e.g., click, swipe).
    ControllerActionStarting(ControllerActionDetail),
    /// Triggered after a controller action completes successfully.
    ControllerActionSucceeded(ControllerActionDetail),
    /// Triggered if a controller action fails.
    ControllerActionFailed(ControllerActionDetail),

    // --- Tasker Events ---
    /// Triggered when a task begins execution.
    TaskerTaskStarting(TaskerTaskDetail),
    /// Triggered when a task completes successfully.
    TaskerTaskSucceeded(TaskerTaskDetail),
    /// Triggered when a task fails.
    TaskerTaskFailed(TaskerTaskDetail),

    // --- Node Pipeline Events ---
    /// Triggered when a node in the pipeline starts execution.
    NodePipelineNodeStarting(NodePipelineNodeDetail),
    /// Triggered when a node in the pipeline completes successfully.
    NodePipelineNodeSucceeded(NodePipelineNodeDetail),
    /// Triggered when a node in the pipeline fails.
    NodePipelineNodeFailed(NodePipelineNodeDetail),

    // --- Node Recognition Events ---
    /// Triggered when image recognition begins for a node.
    NodeRecognitionStarting(NodeRecognitionDetail),
    /// Triggered when image recognition succeeds.
    NodeRecognitionSucceeded(NodeRecognitionDetail),
    /// Triggered when image recognition fails.
    NodeRecognitionFailed(NodeRecognitionDetail),

    // --- Node Action Events ---
    /// Triggered before a node action is executed.
    NodeActionStarting(NodeActionDetail),
    /// Triggered after a node action completes successfully.
    NodeActionSucceeded(NodeActionDetail),
    /// Triggered if a node action fails.
    NodeActionFailed(NodeActionDetail),

    // --- Node Wait Freezes Events ---
    /// Triggered when wait-freezes processing starts.
    NodeWaitFreezesStarting(NodeWaitFreezesDetail),
    /// Triggered when wait-freezes processing succeeds.
    NodeWaitFreezesSucceeded(NodeWaitFreezesDetail),
    /// Triggered when wait-freezes processing fails.
    NodeWaitFreezesFailed(NodeWaitFreezesDetail),

    // --- Node Next List Events ---
    /// Triggered when processing the "next" list for a node.
    NodeNextListStarting(NodeNextListDetail),
    /// Triggered when the "next" list processing succeeds.
    NodeNextListSucceeded(NodeNextListDetail),
    /// Triggered when the "next" list processing fails.
    NodeNextListFailed(NodeNextListDetail),

    // --- Trace Events ---
    /// Trace event: Recognition node starting.
    NodeRecognitionNodeStarting(NodePipelineNodeDetail),
    /// Trace event: Recognition node succeeded.
    NodeRecognitionNodeSucceeded(NodePipelineNodeDetail),
    /// Trace event: Recognition node failed.
    NodeRecognitionNodeFailed(NodePipelineNodeDetail),

    /// Trace event: Action node starting.
    NodeActionNodeStarting(NodePipelineNodeDetail),
    /// Trace event: Action node succeeded.
    NodeActionNodeSucceeded(NodePipelineNodeDetail),
    /// Trace event: Action node failed.
    NodeActionNodeFailed(NodePipelineNodeDetail),

    // --- Fallback ---
    /// Represents an unknown or unparsable event.
    ///
    /// This variant is used as a fallback when the event message is not recognized
    /// or if JSON deserialization fails.
    Unknown {
        /// The raw message string.
        msg: String,
        /// The raw JSON detail string.
        raw_json: String,
        err: Option<String>,
    },
}

impl MaaEvent {
    /// Parses a notification message and detail string into a `MaaEvent`.
    ///
    /// This function handles the conversion from the raw C-string values provided by the
    /// framework callback into safe, typed Rust structures.
    ///
    /// # Arguments
    /// * `msg` - The notification type identifier (e.g., "Resource.Loading.Starting").
    /// * `details` - The JSON string containing event details.
    pub fn from_json(msg: &str, details: &str) -> Self {
        match msg {
            // Resource
            msg::RESOURCE_LOADING_STARTING => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::ResourceLoadingStarting(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::RESOURCE_LOADING_SUCCEEDED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::ResourceLoadingSucceeded(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::RESOURCE_LOADING_FAILED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::ResourceLoadingFailed(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },

            // Controller
            msg::CONTROLLER_ACTION_STARTING => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::ControllerActionStarting(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::CONTROLLER_ACTION_SUCCEEDED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::ControllerActionSucceeded(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::CONTROLLER_ACTION_FAILED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::ControllerActionFailed(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },

            // Tasker
            msg::TASKER_TASK_STARTING => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::TaskerTaskStarting(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::TASKER_TASK_SUCCEEDED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::TaskerTaskSucceeded(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::TASKER_TASK_FAILED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::TaskerTaskFailed(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },

            // Node Pipeline
            msg::NODE_PIPELINE_NODE_STARTING => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodePipelineNodeStarting(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::NODE_PIPELINE_NODE_SUCCEEDED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodePipelineNodeSucceeded(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::NODE_PIPELINE_NODE_FAILED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodePipelineNodeFailed(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },

            // Node Recognition
            msg::NODE_RECOGNITION_STARTING => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeRecognitionStarting(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::NODE_RECOGNITION_SUCCEEDED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeRecognitionSucceeded(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::NODE_RECOGNITION_FAILED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeRecognitionFailed(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },

            // Node Action
            msg::NODE_ACTION_STARTING => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeActionStarting(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::NODE_ACTION_SUCCEEDED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeActionSucceeded(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::NODE_ACTION_FAILED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeActionFailed(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },

            // Node Wait Freezes
            msg::NODE_WAIT_FREEZES_STARTING => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeWaitFreezesStarting(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::NODE_WAIT_FREEZES_SUCCEEDED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeWaitFreezesSucceeded(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::NODE_WAIT_FREEZES_FAILED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeWaitFreezesFailed(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },

            // Node Next List
            msg::NODE_NEXT_LIST_STARTING => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeNextListStarting(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::NODE_NEXT_LIST_SUCCEEDED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeNextListSucceeded(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::NODE_NEXT_LIST_FAILED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeNextListFailed(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },

            // Node Recognition Node
            msg::NODE_RECOGNITION_NODE_STARTING => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeRecognitionNodeStarting(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::NODE_RECOGNITION_NODE_SUCCEEDED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeRecognitionNodeSucceeded(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::NODE_RECOGNITION_NODE_FAILED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeRecognitionNodeFailed(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },

            // Node Action Node
            msg::NODE_ACTION_NODE_STARTING => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeActionNodeStarting(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::NODE_ACTION_NODE_SUCCEEDED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeActionNodeSucceeded(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },
            msg::NODE_ACTION_NODE_FAILED => match serde_json::from_str(details) {
                Ok(d) => MaaEvent::NodeActionNodeFailed(d),
                Err(e) => MaaEvent::Unknown {
                    msg: msg.to_string(),
                    raw_json: details.to_string(),
                    err: Some(e.to_string()),
                },
            },

            _ => MaaEvent::Unknown {
                msg: msg.to_string(),
                raw_json: details.to_string(),
                err: None,
            },
        }
    }
}

// === Tests ===

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_context_event_parsing_logic() {
        let msg_wf = "Node.WaitFreezes.Succeeded";
        let detail_wf = json!({
            "task_id": 1,
            "wf_id": 10,
            "name": "WF",
            "phase": "pre",
            "roi": [1, 2, 3, 4],
            "param": {},
            "reco_ids": [100, 101],
            "elapsed": 233,
            "focus": null
        }).to_string();

        if let Some(ContextEvent::NodeWaitFreezes(t, d)) =
            ContextEvent::from_notification(msg_wf, &detail_wf)
        {
            assert_eq!(t, NotificationType::Succeeded);
            assert_eq!(d.wf_id, 10);
            assert_eq!(d.reco_ids, vec![100, 101]);
            assert_eq!(d.elapsed, Some(233));
        } else {
            panic!("Node.WaitFreezes parse failed");
        }
        let msg_reco = "Node.Recognition.Succeeded";
        let detail_reco =
            json!({ "task_id": 1, "reco_id": 100, "name": "R", "focus": null, "anchor": "A1" }).to_string();

        if let Some(ContextEvent::NodeRecognition(t, d)) =
            ContextEvent::from_notification(msg_reco, &detail_reco)
        {
            assert_eq!(t, NotificationType::Succeeded);
            assert_eq!(d.anchor.as_deref(), Some("A1"));
        } else {
            panic!("Node.Recognition parse failed");
        }

        let msg_node = "Node.RecognitionNode.Starting";
        let detail_node =
            json!({ "task_id": 1, "node_id": 200, "name": "N", "focus": null }).to_string();

        if let Some(ContextEvent::NodeRecognitionNode(t, _)) =
            ContextEvent::from_notification(msg_node, &detail_node)
        {
            assert_eq!(t, NotificationType::Starting);
        } else {
            panic!("Node.RecognitionNode parse failed");
        }
    }
}