native-gui-mock 1.0.0

Headless Mock backend and in-process E2E testing framework for Native GUI
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
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
//! Out-of-process remote E2E driver, JSON protocol, and MCP bridge.
//!
//! Provides [`RemoteDriverServer`] to drive any `native-gui` application from external
//! tools, scripts, or agent environments over stdio, pipes, or sockets.
//! Supports both standard JSON-RPC 2.0 messages and line-delimited JSON commands.
//!
//! # Commands
//!
//! - `FindWidget`: Locates a widget by criteria (ID, name, test_id, text, kind, role, etc.).
//! - `Click`: Simulates clicking an actionable widget.
//! - `Fill`: Inputs/types text into an editable widget.
//! - `Screenshot`: Captures a viewport, window, or element screenshot, returning base64 PNG.
//! - `DumpTree`: Returns the full UI hierarchy as JSON nodes and formatted text.
//! - `Close`: Closes a target window or dialog.
//! - `Ping`: Healthcheck returning pong.

use std::io::{BufRead, Write};

use crate::e2e::{Driver, E2eBackend, Locator};
use native_gui_core::access::AccessibleRole;
use native_gui_core::error::{GuiError, GuiResult};
use native_gui_core::events::UiEvent;
use native_gui_core::ui::{LoopFlow, Ui};
use native_gui_core::widgets::{WidgetId, WidgetKind};

#[cfg(feature = "serde")]
use crate::e2e::{dump_widget_tree, CaptureTarget};
#[cfg(feature = "serde")]
use native_gui_core::widgets::WidgetSpec;
#[cfg(feature = "serde")]
use serde_json::{json, Value};

/// Standard base64 encoding alphabet without external dependencies.
const BASE64_ALPHABET: &[u8; 64] =
    b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/// Encodes raw bytes into a standard base64 string.
pub fn base64_encode(data: &[u8]) -> String {
    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
    let (chunks, remainder) = data.as_chunks::<3>();

    for chunk in chunks {
        let b = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | (chunk[2] as u32);
        out.push(BASE64_ALPHABET[((b >> 18) & 0x3F) as usize] as char);
        out.push(BASE64_ALPHABET[((b >> 12) & 0x3F) as usize] as char);
        out.push(BASE64_ALPHABET[((b >> 6) & 0x3F) as usize] as char);
        out.push(BASE64_ALPHABET[(b & 0x3F) as usize] as char);
    }

    match remainder.len() {
        1 => {
            let b = (remainder[0] as u32) << 16;
            out.push(BASE64_ALPHABET[((b >> 18) & 0x3F) as usize] as char);
            out.push(BASE64_ALPHABET[((b >> 12) & 0x3F) as usize] as char);
            out.push('=');
            out.push('=');
        }
        2 => {
            let b = ((remainder[0] as u32) << 16) | ((remainder[1] as u32) << 8);
            out.push(BASE64_ALPHABET[((b >> 18) & 0x3F) as usize] as char);
            out.push(BASE64_ALPHABET[((b >> 12) & 0x3F) as usize] as char);
            out.push(BASE64_ALPHABET[((b >> 6) & 0x3F) as usize] as char);
            out.push('=');
        }
        _ => {}
    }

    out
}

/// Bounding rectangle in logical layout units.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RemoteBounds {
    pub x: i32,
    pub y: i32,
    pub width: u32,
    pub height: u32,
}

/// Remote query criteria matching one or more widgets.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RemoteLocator {
    #[cfg_attr(feature = "serde", serde(default))]
    pub id: Option<u64>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub name: Option<String>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub test_id: Option<String>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub text: Option<String>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub kind: Option<String>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub role: Option<String>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub label: Option<String>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub dialog: Option<bool>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub window: Option<bool>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub top_level: Option<bool>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub child_of: Option<Box<RemoteLocator>>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub descendant_of: Option<Box<RemoteLocator>>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub in_window: Option<Box<RemoteLocator>>,
}

impl RemoteLocator {
    /// Creates a locator matching an exact widget ID.
    pub fn id(id: u64) -> Self {
        Self {
            id: Some(id),
            ..Default::default()
        }
    }

    /// Creates a locator matching an automation name.
    pub fn name(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
            ..Default::default()
        }
    }

    /// Creates a locator matching a test ID.
    pub fn test_id(test_id: impl Into<String>) -> Self {
        Self {
            test_id: Some(test_id.into()),
            ..Default::default()
        }
    }

    /// Creates a locator matching text.
    pub fn text(text: impl Into<String>) -> Self {
        Self {
            text: Some(text.into()),
            ..Default::default()
        }
    }

    /// Creates a locator matching a widget kind.
    pub fn kind(kind: impl Into<String>) -> Self {
        Self {
            kind: Some(kind.into()),
            ..Default::default()
        }
    }

    /// Converts this remote locator specification into an in-process [`Locator`].
    pub fn to_locator(&self) -> GuiResult<Locator> {
        let mut loc = if let Some(id) = self.id {
            Locator::id(WidgetId(id))
        } else if let Some(name) = &self.name {
            Locator::name(name)
        } else if let Some(tid) = &self.test_id {
            Locator::test_id(tid)
        } else if let Some(kind_str) = &self.kind {
            let kind = parse_widget_kind(kind_str)?;
            Locator::kind(kind)
        } else if let Some(role_str) = &self.role {
            let role = parse_accessible_role(role_str);
            let label = self.label.as_deref().unwrap_or_default();
            Locator::role(role, label)
        } else if self.dialog == Some(true) {
            Locator::dialog()
        } else if self.window == Some(true) {
            Locator::window()
        } else if self.top_level == Some(true) {
            Locator::top_level()
        } else if let Some(text) = &self.text {
            Locator::text(text)
        } else {
            return Err(GuiError::Backend(
                "e2e.remote: empty locator specification".into(),
            ));
        };

        // Combine additional selectors if present
        if self.id.is_none() {
            if let Some(kind_str) = &self.kind {
                if self.name.is_some() || self.test_id.is_some() || self.text.is_some() {
                    let kind = parse_widget_kind(kind_str)?;
                    loc = loc.with_kind(kind);
                }
            }
            if let Some(text) = &self.text {
                if self.name.is_some() || self.test_id.is_some() || self.kind.is_some() {
                    loc = loc.with_text(text);
                }
            }
        }

        if let Some(parent) = &self.child_of {
            loc = loc.child_of(parent.to_locator()?);
        }
        if let Some(ancestor) = &self.descendant_of {
            loc = loc.descendant_of(ancestor.to_locator()?);
        }
        if let Some(win) = &self.in_window {
            loc = loc.in_window(win.to_locator()?);
        }

        Ok(loc)
    }
}

fn parse_widget_kind(s: &str) -> GuiResult<WidgetKind> {
    let trimmed = s.trim();
    for kind in native_gui_core::widgets::abstractable_widget_types() {
        if trimmed.eq_ignore_ascii_case(&format!("{kind:?}")) {
            return Ok(*kind);
        }
    }
    Err(GuiError::Backend(format!("unknown widget kind: {s}")))
}

fn parse_accessible_role(s: &str) -> AccessibleRole {
    match s.trim().to_ascii_lowercase().as_str() {
        "button" => AccessibleRole::Button,
        "text" | "label" | "statictext" => AccessibleRole::Label,
        "textinput" | "entry" | "textfield" => AccessibleRole::TextInput,
        "textarea" => AccessibleRole::TextArea,
        "checkbox" | "check" => AccessibleRole::CheckBox,
        "radiobutton" | "radio" => AccessibleRole::RadioButton,
        "window" => AccessibleRole::Window,
        "dialog" => AccessibleRole::Dialog,
        "alert" => AccessibleRole::Alert,
        "slider" => AccessibleRole::Slider,
        "combobox" | "dropdown" => AccessibleRole::ComboBox,
        "list" | "listview" => AccessibleRole::List,
        "tree" | "treeview" => AccessibleRole::Tree,
        "grid" | "table" | "datagrid" => AccessibleRole::Table,
        _ => AccessibleRole::Label,
    }
}

/// Target surface specification for remote screenshots.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum RemoteCaptureTarget {
    Viewport,
    Window(u64),
    Element(RemoteLocator),
}

/// Result of a `FindWidget` remote call.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RemoteFindResult {
    pub found: bool,
    pub widget_id: Option<u64>,
    pub kind: Option<String>,
    pub text: Option<String>,
    pub bounds: Option<RemoteBounds>,
    pub enabled: Option<bool>,
    pub visible: Option<bool>,
}

/// Result of an action (`Click`, `Fill`, `Close`).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RemoteActionResult {
    pub success: bool,
    pub widget_id: Option<u64>,
    pub message: Option<String>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub closed: Option<bool>,
}

/// Result of a `Screenshot` call.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RemoteScreenshotResult {
    pub success: bool,
    pub width: u32,
    pub height: u32,
    pub base64: String,
    pub path: Option<String>,
}

/// Node representation in a remote widget tree dump.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RemoteTreeNode {
    pub id: u64,
    pub parent: Option<u64>,
    pub kind: String,
    pub text: Option<String>,
    pub enabled: bool,
    pub visible: bool,
    pub bounds: Option<RemoteBounds>,
    pub children: Vec<u64>,
}

/// Result of a `DumpTree` call.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RemoteTreeResult {
    pub widgets: Vec<RemoteTreeNode>,
    pub text_dump: String,
}

/// Out-of-process remote driver server.
///
/// Wraps an in-process [`Driver`] and handles line-delimited commands or
/// JSON-RPC 2.0 requests over stdio or any `BufRead` + `Write` streams.
pub struct RemoteDriverServer<B: E2eBackend, H> {
    driver: Driver<B, H>,
    session_token: Option<String>,
}

impl<B: E2eBackend, H> RemoteDriverServer<B, H>
where
    H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
    /// Creates a new server wrapping the given driver.
    pub fn new(driver: Driver<B, H>) -> Self {
        Self {
            driver,
            session_token: None,
        }
    }

    /// Sets an optional security token required for all incoming requests.
    pub fn with_token(mut self, token: impl Into<String>) -> Self {
        self.session_token = Some(token.into());
        self
    }

    /// Returns the active session token, if configured.
    pub fn session_token(&self) -> Option<&str> {
        self.session_token.as_deref()
    }

    /// Borrows the inner driver.
    pub fn driver(&self) -> &Driver<B, H> {
        &self.driver
    }

    /// Mutably borrows the inner driver.
    pub fn driver_mut(&mut self) -> &mut Driver<B, H> {
        &mut self.driver
    }

    /// Processes a single input line and returns a single JSON response string.
    pub fn handle_line(&mut self, line: &str) -> String {
        #[cfg(feature = "serde")]
        {
            let req_value: Value = match serde_json::from_str(line) {
                Ok(v) => v,
                Err(err) => {
                    return json!({
                        "jsonrpc": "2.0",
                        "id": Value::Null,
                        "error": {
                            "code": -32700,
                            "message": format!("parse error: {err}")
                        }
                    })
                    .to_string();
                }
            };

            let req_id = req_value.get("id").cloned();
            let is_json_rpc = req_id.is_some() || req_value.get("jsonrpc").is_some();

            // Check security token if configured
            if let Some(expected_token) = &self.session_token {
                let token_match = req_value.get("token").and_then(Value::as_str).or_else(|| {
                    req_value
                        .get("params")
                        .and_then(|p| p.get("token"))
                        .and_then(Value::as_str)
                }) == Some(expected_token);

                if !token_match {
                    let err_obj = json!({
                        "code": -32001,
                        "message": "unauthorized: invalid or missing session token"
                    });
                    return if is_json_rpc {
                        json!({
                            "jsonrpc": "2.0",
                            "id": req_id.unwrap_or(Value::Null),
                            "error": err_obj
                        })
                        .to_string()
                    } else {
                        json!({
                            "status": "error",
                            "error": err_obj
                        })
                        .to_string()
                    };
                }
            }

            let method = req_value
                .get("method")
                .and_then(Value::as_str)
                .or_else(|| req_value.get("command").and_then(Value::as_str))
                .or_else(|| req_value.get("action").and_then(Value::as_str))
                .unwrap_or_default();

            let params = req_value.get("params").unwrap_or(&req_value);

            let dispatch_res = self.dispatch_method(method, params);
            match dispatch_res {
                Ok(result_value) => {
                    if is_json_rpc {
                        json!({
                            "jsonrpc": "2.0",
                            "id": req_id.unwrap_or(Value::Null),
                            "result": result_value
                        })
                        .to_string()
                    } else {
                        json!({
                            "status": "ok",
                            "result": result_value
                        })
                        .to_string()
                    }
                }
                Err(err) => {
                    let err_obj = json!({
                        "code": -32603,
                        "message": err.to_string()
                    });
                    if is_json_rpc {
                        json!({
                            "jsonrpc": "2.0",
                            "id": req_id.unwrap_or(Value::Null),
                            "error": err_obj
                        })
                        .to_string()
                    } else {
                        json!({
                            "status": "error",
                            "error": err_obj
                        })
                        .to_string()
                    }
                }
            }
        }
        #[cfg(not(feature = "serde"))]
        {
            let _ = line;
            "{\"error\": \"remote driver requires serde feature\"}".to_string()
        }
    }

    #[cfg(feature = "serde")]
    fn dispatch_method(&mut self, method: &str, params: &Value) -> GuiResult<Value> {
        match method.to_ascii_lowercase().as_str() {
            "ping" => Ok(json!({ "pong": true })),
            "findwidget" | "find_widget" | "find" => {
                let loc = parse_locator_param(params)?;
                let res = self.execute_find(&loc)?;
                Ok(serde_json::to_value(&res).unwrap_or(json!({ "found": false })))
            }
            "click" => {
                let res = self.execute_click(params)?;
                Ok(serde_json::to_value(&res).unwrap_or(json!({ "success": true })))
            }
            "fill" | "type_text" | "typetext" => {
                let res = self.execute_fill(params)?;
                Ok(serde_json::to_value(&res).unwrap_or(json!({ "success": true })))
            }
            "screenshot" => {
                let res = self.execute_screenshot(params)?;
                Ok(serde_json::to_value(&res).unwrap_or(json!({ "success": true })))
            }
            "dumptree" | "dump_tree" | "tree" => {
                let res = self.execute_dump_tree()?;
                Ok(serde_json::to_value(&res).unwrap_or(json!({})))
            }
            "close" => {
                let res = self.execute_close(params)?;
                Ok(serde_json::to_value(&res).unwrap_or(json!({ "success": true })))
            }
            other => Err(GuiError::Backend(format!(
                "e2e.remote: unknown method '{other}'"
            ))),
        }
    }

    #[cfg(feature = "serde")]
    fn execute_find(&self, locator: &RemoteLocator) -> GuiResult<RemoteFindResult> {
        let loc = locator.to_locator()?;
        match self.driver.find(&loc)? {
            Some(elem) => {
                let id = elem.id();
                let spec = self.driver.ui().widget(id);
                let bounds = spec.map(|s| {
                    let pos = s.position.unwrap_or((0, 0));
                    let size = s.size.unwrap_or((0, 0));
                    RemoteBounds {
                        x: pos.0,
                        y: pos.1,
                        width: size.0.max(0) as u32,
                        height: size.1.max(0) as u32,
                    }
                });
                let kind_str = spec.map(|s| format!("{:?}", s.kind));
                let text_val = spec.and_then(|s| s.text.clone());
                let enabled_val = spec.map(|s| s.enabled.unwrap_or(true));
                let visible_val = Some(self.driver.ui().is_visible(id));

                Ok(RemoteFindResult {
                    found: true,
                    widget_id: Some(id.0),
                    kind: kind_str,
                    text: text_val,
                    bounds,
                    enabled: enabled_val,
                    visible: visible_val,
                })
            }
            None => Ok(RemoteFindResult {
                found: false,
                widget_id: None,
                kind: None,
                text: None,
                bounds: None,
                enabled: None,
                visible: None,
            }),
        }
    }

    #[cfg(feature = "serde")]
    fn execute_click(&mut self, params: &Value) -> GuiResult<RemoteActionResult> {
        let elem = if let Some(wid) = params.get("widget_id").and_then(Value::as_u64) {
            self.driver.expect_one(&Locator::id(WidgetId(wid)))?
        } else {
            let loc = parse_locator_param(params)?;
            self.driver.expect_one(&loc.to_locator()?)?
        };

        let target_id = elem.id();
        elem.click(&mut self.driver)?;
        Ok(RemoteActionResult {
            success: true,
            widget_id: Some(target_id.0),
            message: None,
            closed: None,
        })
    }

    #[cfg(feature = "serde")]
    fn execute_fill(&mut self, params: &Value) -> GuiResult<RemoteActionResult> {
        let text = params
            .get("text")
            .and_then(Value::as_str)
            .ok_or_else(|| GuiError::Backend("fill requires 'text' parameter".into()))?;

        let elem = if let Some(wid) = params.get("widget_id").and_then(Value::as_u64) {
            self.driver.expect_one(&Locator::id(WidgetId(wid)))?
        } else {
            let loc = parse_locator_param(params)?;
            self.driver.expect_one(&loc.to_locator()?)?
        };

        let target_id = elem.id();
        elem.type_text(&mut self.driver, text)?;
        Ok(RemoteActionResult {
            success: true,
            widget_id: Some(target_id.0),
            message: Some(text.to_owned()),
            closed: None,
        })
    }

    #[cfg(feature = "serde")]
    fn execute_screenshot(&mut self, params: &Value) -> GuiResult<RemoteScreenshotResult> {
        let target = if let Some(target_val) = params.get("target") {
            if target_val.is_string() {
                // A string target always means the viewport; windows and elements are
                // addressed by their JSON object shape.
                CaptureTarget::Viewport
            } else if let Some(wid) = target_val.get("window").and_then(Value::as_u64) {
                CaptureTarget::Window(WidgetId(wid))
            } else if let Some(elem_loc) = target_val.get("element") {
                let r_loc: RemoteLocator = serde_json::from_value(elem_loc.clone())
                    .map_err(|e| GuiError::Backend(format!("invalid element locator: {e}")))?;
                CaptureTarget::Element(r_loc.to_locator()?)
            } else {
                CaptureTarget::Viewport
            }
        } else {
            CaptureTarget::Viewport
        };

        let img = self.driver.screenshot(target)?;
        let png_bytes = img.to_png()?;

        let save_path = params
            .get("path")
            .and_then(Value::as_str)
            .map(str::to_owned);

        if let Some(p) = &save_path {
            std::fs::write(p, &png_bytes).map_err(|e| {
                GuiError::Backend(format!("failed to save screenshot to '{p}': {e}"))
            })?;
        }

        let b64 = base64_encode(&png_bytes);

        Ok(RemoteScreenshotResult {
            success: true,
            width: img.width(),
            height: img.height(),
            base64: b64,
            path: save_path,
        })
    }

    #[cfg(feature = "serde")]
    fn execute_dump_tree(&self) -> GuiResult<RemoteTreeResult> {
        let text_dump = dump_widget_tree(self.driver.ui());
        let specs: Vec<WidgetSpec> = self.driver.ui().e2e_widget_specs().cloned().collect();

        let mut nodes = Vec::new();
        for spec in &specs {
            let bounds = spec.position.and_then(|(x, y)| {
                spec.size.map(|(w, h)| RemoteBounds {
                    x,
                    y,
                    width: w.max(0) as u32,
                    height: h.max(0) as u32,
                })
            });

            let children: Vec<u64> = specs
                .iter()
                .filter(|s| s.parent == Some(spec.id))
                .map(|s| s.id.0)
                .collect();

            nodes.push(RemoteTreeNode {
                id: spec.id.0,
                parent: spec.parent.map(|p| p.0),
                kind: format!("{:?}", spec.kind),
                text: spec.text.clone(),
                enabled: spec.enabled.unwrap_or(true),
                visible: self.driver.ui().is_visible(spec.id),
                bounds,
                children,
            });
        }

        Ok(RemoteTreeResult {
            widgets: nodes,
            text_dump,
        })
    }

    #[cfg(feature = "serde")]
    fn execute_close(&mut self, params: &Value) -> GuiResult<RemoteActionResult> {
        if let Some(wid) = params.get("widget_id").and_then(Value::as_u64) {
            let elem = self.driver.expect_one(&Locator::id(WidgetId(wid)))?;
            elem.close(&mut self.driver)?;
            return Ok(RemoteActionResult {
                success: true,
                widget_id: Some(wid),
                message: None,
                closed: Some(true),
            });
        }

        if let Ok(loc) = parse_locator_param(params) {
            if let Ok(elem) = self.driver.expect_one(&loc.to_locator()?) {
                let id = elem.id();
                elem.close(&mut self.driver)?;
                return Ok(RemoteActionResult {
                    success: true,
                    widget_id: Some(id.0),
                    message: None,
                    closed: Some(true),
                });
            }
        }

        // Default to closing top-level window or active modal
        let target = self
            .driver
            .active_modal()
            .or_else(|| {
                self.driver
                    .ui()
                    .e2e_widget_specs()
                    .find(|s| s.kind == WidgetKind::Window)
                    .map(|s| s.id)
            })
            .ok_or_else(|| GuiError::Backend("no active window or modal to close".into()))?;

        let elem = self.driver.expect_one(&Locator::id(target))?;
        elem.close(&mut self.driver)?;
        Ok(RemoteActionResult {
            success: true,
            widget_id: Some(target.0),
            message: None,
            closed: Some(true),
        })
    }

    /// Serves incoming lines from `reader` and writes responses to `writer`.
    pub fn serve<R: BufRead, W: Write>(&mut self, reader: R, mut writer: W) -> std::io::Result<()> {
        for line_res in reader.lines() {
            let line = line_res?;
            let trimmed = line.trim();
            if trimmed.is_empty() {
                continue;
            }
            let resp = self.handle_line(trimmed);
            writeln!(writer, "{resp}")?;
            writer.flush()?;
        }
        Ok(())
    }

    /// Serves requests over the current process's standard input and output.
    pub fn serve_stdio(&mut self) -> std::io::Result<()> {
        let stdin = std::io::stdin();
        let stdout = std::io::stdout();
        self.serve(stdin.lock(), stdout.lock())
    }
}

#[cfg(feature = "serde")]
fn parse_locator_param(params: &Value) -> GuiResult<RemoteLocator> {
    if let Some(loc_val) = params.get("locator") {
        serde_json::from_value(loc_val.clone())
            .map_err(|e| GuiError::Backend(format!("invalid locator parameter: {e}")))
    } else {
        serde_json::from_value(params.clone())
            .map_err(|e| GuiError::Backend(format!("invalid locator parameters: {e}")))
    }
}

/// Out-of-process client helper for driving a [`RemoteDriverServer`] over streams.
pub struct RemoteDriverClient<R, W> {
    #[allow(dead_code)]
    reader: R,
    #[allow(dead_code)]
    writer: W,
    token: Option<String>,
    #[allow(dead_code)]
    next_id: u64,
}

impl<R: BufRead, W: Write> RemoteDriverClient<R, W> {
    /// Creates a new remote client over the given read and write handles.
    pub fn new(reader: R, writer: W) -> Self {
        Self {
            reader,
            writer,
            token: None,
            next_id: 1,
        }
    }

    /// Sets the session token to include in all requests.
    pub fn with_token(mut self, token: impl Into<String>) -> Self {
        self.token = Some(token.into());
        self
    }

    /// Sends a JSON-RPC request and parses the result.
    #[cfg(feature = "serde")]
    pub fn send_request(&mut self, method: &str, params: Value) -> GuiResult<Value> {
        let id = self.next_id;
        self.next_id += 1;

        let mut req = json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": method,
            "params": params,
        });

        if let Some(token) = &self.token {
            req["token"] = json!(token);
        }

        let mut payload = req.to_string();
        payload.push('\n');
        self.writer
            .write_all(payload.as_bytes())
            .map_err(|e| GuiError::Backend(format!("client write error: {e}")))?;
        self.writer
            .flush()
            .map_err(|e| GuiError::Backend(format!("client flush error: {e}")))?;

        let mut resp_line = String::new();
        self.reader
            .read_line(&mut resp_line)
            .map_err(|e| GuiError::Backend(format!("client read error: {e}")))?;

        let resp_val: Value = serde_json::from_str(resp_line.trim())
            .map_err(|e| GuiError::Backend(format!("invalid response JSON: {e}")))?;

        if let Some(err) = resp_val.get("error") {
            let msg = err
                .get("message")
                .and_then(Value::as_str)
                .unwrap_or("unknown remote error");
            return Err(GuiError::Backend(msg.to_owned()));
        }

        resp_val
            .get("result")
            .cloned()
            .ok_or_else(|| GuiError::Backend("response missing 'result' field".into()))
    }

    /// Locates a widget matching `locator`.
    #[cfg(feature = "serde")]
    pub fn find_widget(&mut self, locator: &RemoteLocator) -> GuiResult<RemoteFindResult> {
        let params = json!({
            "locator": locator,
        });
        let res = self.send_request("FindWidget", params)?;
        serde_json::from_value(res)
            .map_err(|e| GuiError::Backend(format!("failed to deserialize find result: {e}")))
    }

    /// Clicks a widget matching `locator`.
    #[cfg(feature = "serde")]
    pub fn click(&mut self, locator: &RemoteLocator) -> GuiResult<RemoteActionResult> {
        let params = json!({
            "locator": locator,
        });
        let res = self.send_request("Click", params)?;
        serde_json::from_value(res)
            .map_err(|e| GuiError::Backend(format!("failed to deserialize action result: {e}")))
    }

    /// Fills/types text into a widget matching `locator`.
    #[cfg(feature = "serde")]
    pub fn fill(&mut self, locator: &RemoteLocator, text: &str) -> GuiResult<RemoteActionResult> {
        let params = json!({
            "locator": locator,
            "text": text,
        });
        let res = self.send_request("Fill", params)?;
        serde_json::from_value(res)
            .map_err(|e| GuiError::Backend(format!("failed to deserialize action result: {e}")))
    }

    /// Captures a screenshot from the remote application.
    #[cfg(feature = "serde")]
    pub fn screenshot(
        &mut self,
        target: Option<RemoteCaptureTarget>,
        path: Option<&str>,
    ) -> GuiResult<RemoteScreenshotResult> {
        let mut params = json!({});
        if let Some(t) = target {
            params["target"] = serde_json::to_value(t).unwrap_or(Value::Null);
        }
        if let Some(p) = path {
            params["path"] = json!(p);
        }
        let res = self.send_request("Screenshot", params)?;
        serde_json::from_value(res)
            .map_err(|e| GuiError::Backend(format!("failed to deserialize screenshot result: {e}")))
    }

    /// Dumps the remote widget tree hierarchy.
    #[cfg(feature = "serde")]
    pub fn dump_tree(&mut self) -> GuiResult<RemoteTreeResult> {
        let res = self.send_request("DumpTree", json!({}))?;
        serde_json::from_value(res)
            .map_err(|e| GuiError::Backend(format!("failed to deserialize tree result: {e}")))
    }

    /// Closes a target window or the active surface.
    #[cfg(feature = "serde")]
    pub fn close(&mut self, locator: Option<&RemoteLocator>) -> GuiResult<RemoteActionResult> {
        let mut params = json!({});
        if let Some(loc) = locator {
            params["locator"] = serde_json::to_value(loc).unwrap_or(Value::Null);
        }
        let res = self.send_request("Close", params)?;
        serde_json::from_value(res)
            .map_err(|e| GuiError::Backend(format!("failed to deserialize action result: {e}")))
    }

    /// Sends a ping healthcheck.
    #[cfg(feature = "serde")]
    pub fn ping(&mut self) -> GuiResult<bool> {
        let res = self.send_request("Ping", json!({}))?;
        Ok(res.get("pong").and_then(Value::as_bool).unwrap_or(false))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::MockBackend;
    use std::io::Cursor;

    #[test]
    fn base64_encode_round_trip() {
        assert_eq!(base64_encode(b""), "");
        assert_eq!(base64_encode(b"f"), "Zg==");
        assert_eq!(base64_encode(b"fo"), "Zm8=");
        assert_eq!(base64_encode(b"foo"), "Zm9v");
        assert_eq!(base64_encode(b"foob"), "Zm9vYg==");
        assert_eq!(base64_encode(b"fooba"), "Zm9vYmE=");
        assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
    }

    #[test]
    #[cfg(feature = "serde")]
    fn remote_driver_server_ping_and_tree() {
        let mut ui = Ui::new(MockBackend::default());
        let win = ui.create(WidgetKind::Window, Some("Remote Test")).unwrap();
        let btn = ui.create(WidgetKind::Button, Some("Click Me")).unwrap();
        ui.attach(btn, win).unwrap();
        ui.show(win).unwrap();

        let driver = Driver::new(ui, |_ui, _ev| Ok(LoopFlow::Continue));
        let mut server = RemoteDriverServer::new(driver);

        // 1. Ping
        let resp = server.handle_line(r#"{"id":1,"method":"ping"}"#);
        assert!(resp.contains("\"pong\":true"));
        assert!(resp.contains("\"id\":1"));

        // 2. DumpTree
        let tree_resp = server.handle_line(r#"{"id":2,"method":"DumpTree"}"#);
        assert!(tree_resp.contains("Remote Test"));
        assert!(tree_resp.contains("Click Me"));
        assert!(tree_resp.contains("\"id\":2"));

        // 3. FindWidget
        let find_resp = server.handle_line(
            r#"{"id":3,"method":"FindWidget","params":{"locator":{"kind":"Button"}}}"#,
        );
        assert!(find_resp.contains("\"found\":true"));
        assert!(find_resp.contains("\"Click Me\""));
    }

    #[test]
    #[cfg(feature = "serde")]
    fn remote_driver_server_session_token_security() {
        let mut ui = Ui::new(MockBackend::default());
        let win = ui
            .create(WidgetKind::Window, Some("Secured Window"))
            .unwrap();
        ui.show(win).unwrap();

        let driver = Driver::new(ui, |_ui, _ev| Ok(LoopFlow::Continue));
        let mut server = RemoteDriverServer::new(driver).with_token("secret-session-token");

        // Request without token should fail
        let unauthorized = server.handle_line(r#"{"id":1,"method":"ping"}"#);
        assert!(unauthorized.contains("unauthorized"));
        assert!(unauthorized.contains("-32001"));

        // Request with wrong token should fail
        let wrong_token = server.handle_line(r#"{"id":2,"method":"ping","token":"wrong"}"#);
        assert!(wrong_token.contains("unauthorized"));

        // Request with correct token succeeds
        let authorized =
            server.handle_line(r#"{"id":3,"method":"ping","token":"secret-session-token"}"#);
        assert!(authorized.contains("\"pong\":true"));
    }

    #[test]
    #[cfg(all(feature = "serde", feature = "widgets-text"))]
    fn remote_driver_click_and_fill() {
        let mut ui = Ui::new(MockBackend::default());
        let win = ui.create(WidgetKind::Window, Some("Form Window")).unwrap();
        let input = ui.create(WidgetKind::TextInput, Some("Initial")).unwrap();
        let btn = ui.create(WidgetKind::Button, Some("Submit")).unwrap();
        ui.attach(input, win).unwrap();
        ui.attach(btn, win).unwrap();
        ui.show(win).unwrap();

        let mut events_captured = Vec::new();
        let driver = Driver::new(ui, move |_ui, ev| {
            events_captured.push(ev);
            Ok(LoopFlow::Continue)
        });
        let mut server = RemoteDriverServer::new(driver);

        // Fill text into TextInput
        let fill_resp = server.handle_line(r#"{"id":1,"method":"Fill","params":{"locator":{"kind":"TextInput"},"text":"New Value"}}"#);
        assert!(fill_resp.contains("\"success\":true"));

        // Click Button
        let click_resp = server
            .handle_line(r#"{"id":2,"method":"Click","params":{"locator":{"kind":"Button"}}}"#);
        assert!(click_resp.contains("\"success\":true"));
    }

    #[test]
    #[cfg(feature = "serde")]
    fn remote_driver_screenshot_and_close() {
        let mut ui = Ui::new(MockBackend::default());
        let win = ui
            .create(WidgetKind::Window, Some("Screenshot Window"))
            .unwrap();
        ui.set_size(win, 320, 240).unwrap();
        ui.show(win).unwrap();

        let driver = Driver::new(ui, |_ui, _ev| Ok(LoopFlow::Continue));
        let mut server = RemoteDriverServer::new(driver);

        let shot_resp = server.handle_line(r#"{"id":1,"method":"Screenshot"}"#);
        assert!(shot_resp.contains("\"success\":true"));
        assert!(shot_resp.contains("\"base64\":"));

        let close_resp = server.handle_line(r#"{"id":2,"method":"Close"}"#);
        assert!(close_resp.contains("\"closed\":true"));
    }

    #[test]
    #[cfg(feature = "serde")]
    fn remote_driver_client_round_trip() {
        let mut ui = Ui::new(MockBackend::default());
        let win = ui
            .create(WidgetKind::Window, Some("Client Window"))
            .unwrap();
        let btn = ui
            .create(WidgetKind::Button, Some("Client Button"))
            .unwrap();
        ui.attach(btn, win).unwrap();
        ui.show(win).unwrap();

        let driver = Driver::new(ui, |_ui, _ev| Ok(LoopFlow::Continue));
        let mut server = RemoteDriverServer::new(driver).with_token("token-xyz");

        // Simulate request and response channels with Cursor
        let mut req_buf = Vec::new();
        let resp_buf = Vec::new();

        let _client =
            RemoteDriverClient::new(Cursor::new(resp_buf), &mut req_buf).with_token("token-xyz");

        // Format a request from client to string
        let ping_req =
            r#"{"jsonrpc":"2.0","id":1,"method":"Ping","params":{},"token":"token-xyz"}"#;

        let resp_str = server.handle_line(ping_req);
        assert!(resp_str.contains("\"pong\":true"));

        let find_req = r#"{"jsonrpc":"2.0","id":2,"method":"FindWidget","params":{"locator":{"kind":"Button"}},"token":"token-xyz"}"#;

        let find_resp = server.handle_line(find_req);
        assert!(find_resp.contains("\"found\":true"));
        assert!(find_resp.contains("\"Client Button\""));
    }
}