wasma-sys 1.3.0-beta-stable

WASMA Windows Assignment System Monitoring Architecture — client and protocol layer
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
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
// WASMA - Windows Assignment System Monitoring Architecture
// wasma_protocol_unix_posix_window.rs
// Normal (non-raw) POSIX Window Launch Protocol
// Manages window creation, lifecycle, and rendering via direct client specification.
// Launch triggers: client spec (manifest/config) or runtime API call — both supported.
// Window mode: Singularity (single) or Multitary (multi), runtime selection.
// Integrations: PosixOpt (auto), WindowClient (optional), RawWindowClient (optional delegate)
// Implements UClientEngine.
// January 2026

use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use std::time::SystemTime;

use crate::parser::WasmaConfig;
use crate::uclient::SectionMemory;
use crate::wasma_client_unix_posix_raw_app::UClientEngine;
use crate::wasma_client_unix_posix_raw_window::RawWindowClient;
use crate::wasma_protocol_unix_posix_opt::{
    DisplayBackend, PosixOpt, RuntimeOptStore, ToolkitTheme,
};
use crate::window_client::WindowClient;
use crate::window_handling::{WindowGeometry, WindowState, WindowType};

// ============================================================================
// WINDOW MODE — Singularity or Multitary
// ============================================================================

/// Window mode — controls how many windows can be active simultaneously
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum WindowMode {
    /// Singularity: only one window active at a time
    /// New launch replaces the existing window
    Singularity,
    /// Multitary: multiple windows can coexist
    /// Each launch creates a new independent window
    Multitary,
}

impl WindowMode {
    pub fn name(&self) -> &'static str {
        match self {
            Self::Singularity => "singularity",
            Self::Multitary => "multitary",
        }
    }

    pub fn from_config(config: &WasmaConfig) -> Self {
        if config.uri_handling.singularity_instances {
            Self::Singularity
        } else {
            Self::Multitary
        }
    }
}

// ============================================================================
// WINDOW SPEC — Client specification for window launch
// ============================================================================

/// Window spec source — where did this spec come from?
#[derive(Debug, Clone, PartialEq)]
pub enum SpecSource {
    /// Parsed from manifest/config file
    Manifest(String),
    /// Provided at runtime via API
    Runtime,
    /// Derived from WasmaConfig
    Config,
}

impl SpecSource {
    pub fn label(&self) -> String {
        match self {
            Self::Manifest(path) => format!("manifest:{}", path),
            Self::Runtime => "runtime".to_string(),
            Self::Config => "config".to_string(),
        }
    }
}

/// Decoration style for the window
#[derive(Debug, Clone, PartialEq)]
pub enum DecorationStyle {
    /// Full server-side decorations (title bar, borders)
    ServerSide,
    /// Client-side decorations (app draws its own title bar)
    ClientSide,
    /// No decorations (borderless)
    None,
    /// Auto: let the compositor decide
    Auto,
}

/// Window launch specification — complete description of a window to be created
#[derive(Debug, Clone)]
pub struct WindowSpec {
    /// Application identifier
    pub app_id: String,
    /// Window title
    pub title: String,
    /// Window type (Normal, Dialog, Utility, etc.)
    pub window_type: WindowType,
    /// Initial geometry in logical pixels
    pub geometry: WindowGeometry,
    /// Decoration style
    pub decoration: DecorationStyle,
    /// Initial window state
    pub initial_state: WindowState,
    /// Start visible
    pub start_visible: bool,
    /// Start focused
    pub start_focused: bool,
    /// Parent window ID (for dialogs/popups)
    pub parent_id: Option<u64>,
    /// Custom key-value properties (from manifest)
    pub properties: HashMap<String, String>,
    /// Spec source
    pub source: SpecSource,
    /// Spec creation time
    pub created_at: SystemTime,
}

impl WindowSpec {
    /// Create a minimal spec with defaults
    pub fn new(app_id: impl Into<String>, title: impl Into<String>) -> Self {
        Self {
            app_id: app_id.into(),
            title: title.into(),
            window_type: WindowType::Normal,
            geometry: WindowGeometry {
                x: 0,
                y: 0,
                width: 800,
                height: 600,
            },
            decoration: DecorationStyle::Auto,
            initial_state: WindowState::Normal,
            start_visible: true,
            start_focused: true,
            parent_id: None,
            properties: HashMap::new(),
            source: SpecSource::Runtime,
            created_at: SystemTime::now(),
        }
    }

    pub fn from_config(config: &WasmaConfig) -> Self {
        let mut spec = Self::new(
            config.uri_handling.window_app_spec.clone(),
            "Wasma App".to_string(),
        );
        spec.source = SpecSource::Config;
        spec.geometry = WindowGeometry {
            x: 0,
            y: 0,
            width: config.resource_limits.scope_level.max(1) as u32 * 100 + 800,
            height: 600,
        };
        spec
    }

    /// Parse spec from a simple manifest key=value format
    pub fn from_manifest(content: &str, path: impl Into<String>) -> Self {
        let path = path.into();
        let mut spec = Self::new("unknown.app", "Untitled");
        spec.source = SpecSource::Manifest(path);

        for line in content.lines() {
            let line = line.trim();
            if line.starts_with('#') || line.is_empty() {
                continue;
            }
            if let Some((key, val)) = line.split_once('=') {
                let key = key.trim();
                let val = val.trim();
                match key {
                    "app_id" => spec.app_id = val.to_string(),
                    "title" => spec.title = val.to_string(),
                    "width" => spec.geometry.width = val.parse().unwrap_or(800),
                    "height" => spec.geometry.height = val.parse().unwrap_or(600),
                    "x" => spec.geometry.x = val.parse().unwrap_or(0),
                    "y" => spec.geometry.y = val.parse().unwrap_or(0),
                    "visible" => spec.start_visible = val == "true",
                    "focused" => spec.start_focused = val == "true",
                    "decoration" => {
                        spec.decoration = match val {
                            "server" => DecorationStyle::ServerSide,
                            "client" => DecorationStyle::ClientSide,
                            "none" => DecorationStyle::None,
                            _ => DecorationStyle::Auto,
                        }
                    }
                    "type" => {
                        spec.window_type = match val {
                            "dialog" => WindowType::Dialog,
                            "utility" => WindowType::Utility,
                            _ => WindowType::Normal,
                        }
                    }
                    "state" => {
                        spec.initial_state = match val {
                            "minimized" => WindowState::Minimized,
                            "maximized" => WindowState::Maximized,
                            "fullscreen" => WindowState::Fullscreen,
                            "hidden" => WindowState::Hidden,
                            _ => WindowState::Normal,
                        }
                    }
                    _ => {
                        spec.properties.insert(key.to_string(), val.to_string());
                    }
                }
            }
        }
        spec
    }

    /// Validate spec fields
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();
        if self.app_id.is_empty() {
            errors.push("app_id cannot be empty".to_string());
        }
        if self.title.is_empty() {
            errors.push("title cannot be empty".to_string());
        }
        if self.geometry.width == 0 || self.geometry.height == 0 {
            errors.push(format!(
                "Invalid geometry: {}x{} (must be > 0)",
                self.geometry.width, self.geometry.height
            ));
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

/// WindowSpec builder — chainable
pub struct WindowSpecBuilder {
    spec: WindowSpec,
}

impl WindowSpecBuilder {
    pub fn new(app_id: impl Into<String>, title: impl Into<String>) -> Self {
        Self {
            spec: WindowSpec::new(app_id, title),
        }
    }

    pub fn geometry(mut self, x: i32, y: i32, w: u32, h: u32) -> Self {
        self.spec.geometry = WindowGeometry {
            x,
            y,
            width: w,
            height: h,
        };
        self
    }

    pub fn window_type(mut self, t: WindowType) -> Self {
        self.spec.window_type = t;
        self
    }

    pub fn decoration(mut self, d: DecorationStyle) -> Self {
        self.spec.decoration = d;
        self
    }

    pub fn initial_state(mut self, s: WindowState) -> Self {
        self.spec.initial_state = s;
        self
    }

    pub fn start_visible(mut self, v: bool) -> Self {
        self.spec.start_visible = v;
        self
    }

    pub fn start_focused(mut self, f: bool) -> Self {
        self.spec.start_focused = f;
        self
    }

    pub fn parent(mut self, id: u64) -> Self {
        self.spec.parent_id = Some(id);
        self
    }

    pub fn property(mut self, key: impl Into<String>, val: impl Into<String>) -> Self {
        self.spec.properties.insert(key.into(), val.into());
        self
    }

    pub fn source(mut self, s: SpecSource) -> Self {
        self.spec.source = s;
        self
    }

    pub fn build(self) -> Result<WindowSpec, Vec<String>> {
        self.spec.validate()?;
        Ok(self.spec)
    }

    pub fn build_unchecked(self) -> WindowSpec {
        self.spec
    }
}

// ============================================================================
// POSIX WINDOW — Active window handle
// ============================================================================

/// A launched and active POSIX window
#[derive(Debug, Clone)]
pub struct PosixWindow {
    /// Unique window ID
    pub id: u64,
    /// The spec used to create this window
    pub spec: WindowSpec,
    /// Current geometry (may differ from spec after user resizing)
    pub geometry: WindowGeometry,
    /// Current state
    pub state: WindowState,
    /// Current visibility
    pub visible: bool,
    /// Current focus
    pub focused: bool,
    /// Which opt group was applied at launch time
    pub applied_opt_source: String,
    /// Launch timestamp
    pub launched_at: SystemTime,
    /// Backend used for this window
    pub backend: DisplayBackend,
}

impl PosixWindow {
    fn from_spec(id: u64, spec: WindowSpec, opt: &PosixOpt) -> Self {
        let backend = opt.backend.effective_backend();
        let geometry = WindowGeometry {
            x: spec.geometry.x,
            y: spec.geometry.y,
            // Apply PosixOpt min size constraints
            width: spec.geometry.width.max(opt.draw.size.min_width),
            height: spec.geometry.height.max(opt.draw.size.min_height),
        };
        let state = spec.initial_state.clone();
        let visible = spec.start_visible;
        let focused = spec.start_focused;

        Self {
            id,
            geometry,
            state,
            visible,
            focused,
            applied_opt_source: opt.source.clone(),
            launched_at: SystemTime::now(),
            backend,
            spec,
        }
    }

    pub fn is_alive(&self) -> bool {
        self.visible || matches!(self.state, WindowState::Minimized)
    }
}

// ============================================================================
// POSIX WINDOW LAUNCHER — Core launch manager
// ============================================================================

/// PosixWindowLauncher
///
/// Manages normal (non-raw) POSIX window creation and lifecycle.
/// Supports both manifest/config-based and runtime API launch.
/// Mode: Singularity (one window) or Multitary (many), runtime selectable.
///
/// Integrations (all optional except PosixOpt):
///   - PosixOpt: automatically applied to every launch
///   - WindowClient: optional rendering delegate
///   - RawWindowClient: optional low-level delegate
///   - UClientEngine: implemented for WASMA engine compatibility
pub struct PosixWindowLauncher {
    config: Arc<WasmaConfig>,

    /// Option store — applied to every launched window
    opt_store: Arc<RuntimeOptStore>,

    /// Window mode — singularity or multitary
    mode: WindowMode,

    /// Active windows
    windows: Arc<RwLock<HashMap<u64, PosixWindow>>>,

    /// Window ID counter
    next_id: Arc<Mutex<u64>>,

    /// Optional: WindowClient for rendering
    window_client: Option<Arc<Mutex<WindowClient>>>,

    /// Optional: RawWindowClient for low-level delegate
    raw_client: Option<Arc<Mutex<RawWindowClient>>>,

    /// Engine active flag
    active: bool,

    /// SectionMemory for UClientEngine
    memory: SectionMemory,
}

impl PosixWindowLauncher {
    pub fn new(config: WasmaConfig) -> Self {
        let mode = WindowMode::from_config(&config);
        let opt = PosixOpt::from_config(&config);
        let level = config.resource_limits.scope_level;

        Self {
            mode,
            opt_store: Arc::new(RuntimeOptStore::new(opt)),
            windows: Arc::new(RwLock::new(HashMap::new())),
            next_id: Arc::new(Mutex::new(1)),
            window_client: None,
            raw_client: None,
            active: false,
            memory: SectionMemory::new(level),
            config: Arc::new(config),
        }
    }

    pub fn from_config(config: Arc<WasmaConfig>) -> Self {
        let mode = WindowMode::from_config(&config);
        let opt = PosixOpt::from_config(&config);
        let level = config.resource_limits.scope_level;

        Self {
            mode,
            opt_store: Arc::new(RuntimeOptStore::new(opt)),
            windows: Arc::new(RwLock::new(HashMap::new())),
            next_id: Arc::new(Mutex::new(1)),
            window_client: None,
            raw_client: None,
            active: false,
            memory: SectionMemory::new(level),
            config,
        }
    }

    // -------------------------------------------------------------------------
    // OPTIONAL DELEGATE ATTACHMENT
    // -------------------------------------------------------------------------

    /// Attach WindowClient for rendering (optional)
    pub fn attach_window_client(&mut self, wc: Arc<Mutex<WindowClient>>) {
        self.window_client = Some(wc);
        println!("🔗 PosixWindowLauncher: WindowClient attached (rendering delegate)");
    }

    /// Attach RawWindowClient for low-level delegate (optional)
    pub fn attach_raw_client(&mut self, rc: Arc<Mutex<RawWindowClient>>) {
        self.raw_client = Some(rc);
        println!("🔗 PosixWindowLauncher: RawWindowClient attached (low-level delegate)");
    }

    /// Detach WindowClient
    pub fn detach_window_client(&mut self) {
        self.window_client = None;
        println!("🔌 PosixWindowLauncher: WindowClient detached");
    }

    /// Detach RawWindowClient
    pub fn detach_raw_client(&mut self) {
        self.raw_client = None;
        println!("🔌 PosixWindowLauncher: RawWindowClient detached");
    }

    // -------------------------------------------------------------------------
    // MODE CONTROL
    // -------------------------------------------------------------------------

    /// Switch window mode at runtime
    pub fn set_mode(&mut self, mode: WindowMode) {
        println!(
            "🔄 PosixWindowLauncher: Mode {}{}",
            self.mode.name(),
            mode.name()
        );
        self.mode = mode;
    }

    pub fn mode(&self) -> WindowMode {
        self.mode
    }

    // -------------------------------------------------------------------------
    // OPT OVERRIDE
    // -------------------------------------------------------------------------

    /// Apply a runtime opt override
    pub fn override_opt<F>(&self, f: F)
    where
        F: FnOnce(&mut PosixOpt),
    {
        self.opt_store.override_with(f);
    }

    pub fn opt_store(&self) -> Arc<RuntimeOptStore> {
        self.opt_store.clone()
    }

    // -------------------------------------------------------------------------
    // ID ALLOCATION
    // -------------------------------------------------------------------------

    fn alloc_id(&self) -> u64 {
        let mut n = self.next_id.lock().unwrap();
        let id = *n;
        *n += 1;
        id
    }

    // -------------------------------------------------------------------------
    // WINDOW LAUNCH — Core
    // -------------------------------------------------------------------------

    /// Launch a window from a WindowSpec
    /// In Singularity mode: closes existing window before launching
    /// In Multitary mode: creates alongside existing windows
    pub fn launch(&self, spec: WindowSpec) -> Result<u64, String> {
        // Validate spec
        spec.validate().map_err(|e| e.join(", "))?;

        // Singularity: close all existing windows first
        if self.mode == WindowMode::Singularity {
            let ids: Vec<u64> = { self.windows.read().unwrap().keys().cloned().collect() };
            for id in ids {
                self.close_window(id).ok();
            }
        }

        let id = self.alloc_id();
        let opt = self.opt_store.read();

        // Apply PosixOpt constraints to spec
        let window = PosixWindow::from_spec(id, spec.clone(), &opt);

        println!(
            "🪟 PosixWindowLauncher [{}]: Launching window {} — '{}' [{}x{}] via {} (source: {})",
            self.mode.name(),
            id,
            spec.title,
            window.geometry.width,
            window.geometry.height,
            window.backend.name(),
            spec.source.label(),
        );

        // Optional: delegate to RawWindowClient
        if let Some(ref rc) = self.raw_client {
            let raw = rc.lock().unwrap();
            match raw.create_window(
                &spec.title,
                &spec.app_id,
                window.geometry,
                spec.window_type.clone(),
            ) {
                Ok(raw_id) => println!("   ↳ RawWindowClient delegate: raw window id={}", raw_id),
                Err(e) => println!("   ⚠️  RawWindowClient delegate failed (non-fatal): {}", e),
            }
        }

        // Optional: WindowClient rendering setup
        if let Some(ref wc) = self.window_client {
            let mut client = wc.lock().unwrap();
            client.resize(window.geometry.width, window.geometry.height);
            println!(
                "   ↳ WindowClient rendering configured: {}x{}",
                window.geometry.width, window.geometry.height
            );
        }

        // Apply toolkit theme from PosixOpt
        self.apply_toolkit_theme(&opt, id);

        // Store window
        self.windows.write().unwrap().insert(id, window);
        Ok(id)
    }

    /// Launch from WasmaConfig (config-based launch)
    pub fn launch_from_config(&self) -> Result<u64, String> {
        let spec = WindowSpec::from_config(&self.config);
        println!("📋 PosixWindowLauncher: Launching from config");
        self.launch(spec)
    }

    /// Launch from manifest file content (manifest-based launch)
    pub fn launch_from_manifest(
        &self,
        content: &str,
        path: impl Into<String>,
    ) -> Result<u64, String> {
        let path = path.into();
        let spec = WindowSpec::from_manifest(content, &path);
        println!("📄 PosixWindowLauncher: Launching from manifest: {}", path);
        self.launch(spec)
    }

    /// Apply toolkit theme — PosixOpt auto-application
    fn apply_toolkit_theme(&self, opt: &PosixOpt, window_id: u64) {
        match &opt.draw.toolkit {
            ToolkitTheme::Gtk(gtk) => {
                println!(
                    "   🎨 Toolkit: GTK{} theme='{}' dark={}",
                    gtk.version, gtk.theme_name, gtk.dark_mode
                );
            }
            ToolkitTheme::Iced(iced) => {
                println!("   🎨 Toolkit: Iced theme={:?}", iced.variant);
            }
            ToolkitTheme::Qt(qt) => {
                println!(
                    "   🎨 Toolkit: Qt{} style='{}' dark={}",
                    qt.version, qt.style_name, qt.dark_mode
                );
            }
            ToolkitTheme::None => {
                println!("   🎨 Toolkit: None (raw drawing) for window {}", window_id);
            }
        }
    }

    // -------------------------------------------------------------------------
    // WINDOW OPERATIONS
    // -------------------------------------------------------------------------

    /// Close a window by ID
    pub fn close_window(&self, id: u64) -> Result<(), String> {
        // Optional: notify RawWindowClient delegate
        if let Some(ref rc) = self.raw_client {
            let raw = rc.lock().unwrap();
            let _ = raw.destroy_window(id);
        }

        let mut windows = self.windows.write().unwrap();
        if windows.remove(&id).is_some() {
            println!("🗑️  PosixWindowLauncher: Window {} closed", id);
            Ok(())
        } else {
            Err(format!("Window {} not found", id))
        }
    }

    /// Close all windows
    pub fn close_all(&self) {
        let ids: Vec<u64> = self.windows.read().unwrap().keys().cloned().collect();
        for id in ids {
            self.close_window(id).ok();
        }
        println!("🗑️  PosixWindowLauncher: All windows closed");
    }

    /// Set geometry for a window
    pub fn set_geometry(&self, id: u64, geo: WindowGeometry) -> Result<(), String> {
        // Delegate to RawWindowClient if attached
        if let Some(ref rc) = self.raw_client {
            let raw = rc.lock().unwrap();
            let _ = raw.set_geometry(id, geo);
        }

        let mut windows = self.windows.write().unwrap();
        match windows.get_mut(&id) {
            Some(w) => {
                w.geometry = geo;
                // Notify WindowClient if attached
                if let Some(ref wc) = self.window_client {
                    let mut client = wc.lock().unwrap();
                    client.resize(geo.width, geo.height);
                }
                Ok(())
            }
            None => Err(format!("Window {} not found", id)),
        }
    }

    /// Set window state
    pub fn set_state(&self, id: u64, state: WindowState) -> Result<(), String> {
        if let Some(ref rc) = self.raw_client {
            let raw = rc.lock().unwrap();
            let _ = raw.set_state(id, state.clone());
        }
        let mut windows = self.windows.write().unwrap();
        match windows.get_mut(&id) {
            Some(w) => {
                w.state = state;
                Ok(())
            }
            None => Err(format!("Window {} not found", id)),
        }
    }

    /// Set window focus
    pub fn set_focus(&self, id: u64) -> Result<(), String> {
        // Unfocus all
        {
            let mut windows = self.windows.write().unwrap();
            for w in windows.values_mut() {
                w.focused = false;
            }
        }
        if let Some(ref rc) = self.raw_client {
            let raw = rc.lock().unwrap();
            let _ = raw.set_focus(id);
        }
        let mut windows = self.windows.write().unwrap();
        match windows.get_mut(&id) {
            Some(w) => {
                w.focused = true;
                Ok(())
            }
            None => Err(format!("Window {} not found", id)),
        }
    }

    /// Set window visibility
    pub fn set_visible(&self, id: u64, visible: bool) -> Result<(), String> {
        if let Some(ref rc) = self.raw_client {
            let raw = rc.lock().unwrap();
            let _ = raw.set_visible(id, visible);
        }
        let mut windows = self.windows.write().unwrap();
        match windows.get_mut(&id) {
            Some(w) => {
                w.visible = visible;
                Ok(())
            }
            None => Err(format!("Window {} not found", id)),
        }
    }

    /// Set window title
    pub fn set_title(&self, id: u64, title: impl Into<String>) -> Result<(), String> {
        let title = title.into();
        if let Some(ref rc) = self.raw_client {
            let raw = rc.lock().unwrap();
            let _ = raw.set_title(id, &title);
        }
        let mut windows = self.windows.write().unwrap();
        match windows.get_mut(&id) {
            Some(w) => {
                w.spec.title = title;
                Ok(())
            }
            None => Err(format!("Window {} not found", id)),
        }
    }

    /// Render a frame to a window
    /// Routes to WindowClient if attached, otherwise via dispatch_data
pub fn render_frame(&self, id: u64, data: &[u8]) -> Result<(), String> {
    let visible = {
        let windows = self.windows.read().unwrap();
        match windows.get(&id) {
            Some(w) => w.visible && !matches!(w.state, WindowState::Hidden),
            None => return Err(format!("Window {} not found", id)),
        }
    };
    if !visible {
        return Ok(());
    }

    // wsdg-open modeli: uygulama kendi render eder, biz dispatch_data ile devam ederiz
    self.dispatch_data(data);
    Ok(())
}
    // -------------------------------------------------------------------------
    // ACCESSORS
    // -------------------------------------------------------------------------

    pub fn get_window(&self, id: u64) -> Option<PosixWindow> {
        self.windows.read().unwrap().get(&id).cloned()
    }

    pub fn list_windows(&self) -> Vec<PosixWindow> {
        let windows = self.windows.read().unwrap();
        let mut v: Vec<_> = windows.values().cloned().collect();
        v.sort_by_key(|w| w.id);
        v
    }

    pub fn window_count(&self) -> usize {
        self.windows.read().unwrap().len()
    }

    pub fn focused_window(&self) -> Option<PosixWindow> {
        let windows = self.windows.read().unwrap();
        windows.values().find(|w| w.focused).cloned()
    }

    pub fn has_window_client(&self) -> bool {
        self.window_client.is_some()
    }
    pub fn has_raw_client(&self) -> bool {
        self.raw_client.is_some()
    }
}

// ============================================================================
// UCLIENTENGINE TRAIT IMPLEMENTATION
// ============================================================================

impl UClientEngine for PosixWindowLauncher {
    fn start_engine(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        self.active = true;

        let opt = self.opt_store.read();
        println!("🟢 WASMA PosixWindowLauncher: Engine Started");
        println!("   Mode:      {}", self.mode.name());
        println!("   Backend:   {}", opt.backend.effective_backend().name());
        println!("   Toolkit:   {}", opt.draw.toolkit.name());
        println!(
            "   Xlinx:     {} | cache={}",
            opt.xlinx.arch.name(),
            opt.xlinx.cache_mode.name()
        );
        println!(
            "   Delegates: WindowClient={} RawClient={}",
            self.window_client.is_some(),
            self.raw_client.is_some()
        );
        drop(opt);

        // Auto-launch from config if no windows exist
        if self.windows.read().unwrap().is_empty() {
            println!("   Auto-launching from config...");
            match self.launch_from_config() {
                Ok(id) => println!("   Auto-launch OK: window id={}", id),
                Err(e) => eprintln!("   ⚠️  Auto-launch failed: {}", e),
            }
        }

        // Simple event loop — yield until stopped
        loop {
            if !self.active {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(16)); // ~60fps tick
        }

        Ok(())
    }

    fn dispatch_data(&self, data: &[u8]) {
        // Dispatch to focused window if any
        if let Some(w) = self.focused_window() {
            let _ = self.render_frame(w.id, data);
        }
    }

    fn memory_usage(&self) -> (usize, usize, usize) {
        (
            self.memory.raw_storage.len(),
            self.memory.cell_count,
            self.memory.cell_size,
        )
    }

    fn get_config(&self) -> &WasmaConfig {
        &self.config
    }

    fn shutdown(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        self.active = false;
        self.close_all();
        println!("🛑 PosixWindowLauncher: Shutdown complete");
        Ok(())
    }

    fn is_active(&self) -> bool {
        self.active
    }
}

// ============================================================================
// BUILDER
// ============================================================================

pub struct PosixWindowLauncherBuilder {
    config: Option<WasmaConfig>,
    mode: Option<WindowMode>,
    opt_overrides: Vec<Box<dyn FnOnce(&mut PosixOpt)>>,
    window_client: Option<Arc<Mutex<WindowClient>>>,
    raw_client: Option<Arc<Mutex<RawWindowClient>>>,
}

impl PosixWindowLauncherBuilder {
    pub fn new() -> Self {
        Self {
            config: None,
            mode: None,
            opt_overrides: Vec::new(),
            window_client: None,
            raw_client: None,
        }
    }

    pub fn with_config(mut self, config: WasmaConfig) -> Self {
        self.config = Some(config);
        self
    }

    pub fn with_mode(mut self, mode: WindowMode) -> Self {
        self.mode = Some(mode);
        self
    }

    pub fn with_window_client(mut self, wc: Arc<Mutex<WindowClient>>) -> Self {
        self.window_client = Some(wc);
        self
    }

    pub fn with_raw_client(mut self, rc: Arc<Mutex<RawWindowClient>>) -> Self {
        self.raw_client = Some(rc);
        self
    }

    pub fn opt_override<F: FnOnce(&mut PosixOpt) + 'static>(mut self, f: F) -> Self {
        self.opt_overrides.push(Box::new(f));
        self
    }

    pub fn build(self) -> Result<PosixWindowLauncher, String> {
        let config = self.config.ok_or("WasmaConfig required")?;
        let mut launcher = PosixWindowLauncher::new(config);

        if let Some(mode) = self.mode {
            launcher.mode = mode;
        }

        for f in self.opt_overrides {
            launcher.opt_store.override_with(f);
        }

        if let Some(wc) = self.window_client {
            launcher.attach_window_client(wc);
        }
        if let Some(rc) = self.raw_client {
            launcher.attach_raw_client(rc);
        }

        Ok(launcher)
    }
}

impl Default for PosixWindowLauncherBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::ConfigParser;
    use crate::wasma_protocol_unix_posix_opt::XlinxCacheMode;

    fn make_config() -> WasmaConfig {
        let parser = ConfigParser::new(None);
        let content = parser.generate_default_config();
        parser.parse(&content).unwrap()
    }

    fn make_launcher() -> PosixWindowLauncher {
        PosixWindowLauncher::new(make_config())
    }

    #[test]
    fn test_launcher_creation() {
        let launcher = make_launcher();
        assert!(!launcher.is_active());
        assert_eq!(launcher.window_count(), 0);
        assert!(!launcher.has_window_client());
        assert!(!launcher.has_raw_client());
        println!(
            "✅ PosixWindowLauncher creation working (mode: {})",
            launcher.mode().name()
        );
    }

    #[test]
    fn test_launch_runtime_spec() {
        let launcher = make_launcher();
        let spec = WindowSpecBuilder::new("test.app", "Test Window")
            .geometry(100, 100, 1280, 720)
            .window_type(WindowType::Normal)
            .decoration(DecorationStyle::ServerSide)
            .build()
            .unwrap();

        let id = launcher.launch(spec).unwrap();
        assert_eq!(launcher.window_count(), 1);

        let window = launcher.get_window(id).unwrap();
        assert_eq!(window.spec.app_id, "test.app");
        assert_eq!(window.geometry.width, 1280);
        assert_eq!(window.geometry.height, 720);
        println!("✅ Runtime spec launch working: id={}", id);
    }

    #[test]
    fn test_launch_from_config() {
        let launcher = make_launcher();
        let id = launcher.launch_from_config().unwrap();
        assert_eq!(launcher.window_count(), 1);
        assert!(launcher.get_window(id).is_some());
        println!("✅ Config-based launch working: id={}", id);
    }

    #[test]
    fn test_launch_from_manifest() {
        let launcher = make_launcher();
        let manifest = "
# Test manifest
app_id=manifest.app
title=Manifest Window
width=1024
height=768
decoration=client
visible=true
focused=false
custom_key=custom_value
";
        let id = launcher
            .launch_from_manifest(manifest, "/etc/wasma/test.spec")
            .unwrap();
        let window = launcher.get_window(id).unwrap();
        assert_eq!(window.spec.app_id, "manifest.app");
        assert_eq!(window.spec.title, "Manifest Window");
        assert_eq!(window.geometry.width, 1024);
        assert_eq!(window.geometry.height, 768);
        assert!(!window.focused);
        assert_eq!(
            window.spec.properties.get("custom_key").map(|s| s.as_str()),
            Some("custom_value")
        );
        println!("✅ Manifest launch working: id={}", id);
    }

    #[test]
    fn test_singularity_mode_replaces() {
        let mut launcher = make_launcher();
        launcher.set_mode(WindowMode::Singularity);

        let spec1 = WindowSpecBuilder::new("app1", "Win1").build_unchecked();
        let spec2 = WindowSpecBuilder::new("app2", "Win2").build_unchecked();
        let spec3 = WindowSpecBuilder::new("app3", "Win3").build_unchecked();

        launcher.launch(spec1).unwrap();
        assert_eq!(launcher.window_count(), 1);
        launcher.launch(spec2).unwrap();
        assert_eq!(launcher.window_count(), 1); // replaced
        launcher.launch(spec3).unwrap();
        assert_eq!(launcher.window_count(), 1); // replaced again

        let w = launcher.list_windows();
        assert_eq!(w[0].spec.app_id, "app3");
        println!("✅ Singularity mode replacement working");
    }

    #[test]
    fn test_multitary_mode_accumulates() {
        let mut launcher = make_launcher();
        launcher.set_mode(WindowMode::Multitary);

        for i in 0..4 {
            let spec =
                WindowSpecBuilder::new(format!("app{}", i), format!("Win{}", i)).build_unchecked();
            launcher.launch(spec).unwrap();
        }
        assert_eq!(launcher.window_count(), 4);
        println!(
            "✅ Multitary mode accumulation working: {} windows",
            launcher.window_count()
        );
    }

    #[test]
    fn test_mode_switch_at_runtime() {
        let mut launcher = make_launcher();
        launcher.set_mode(WindowMode::Multitary);

        for i in 0..3 {
            let spec =
                WindowSpecBuilder::new(format!("a{}", i), format!("W{}", i)).build_unchecked();
            launcher.launch(spec).unwrap();
        }
        assert_eq!(launcher.window_count(), 3);

        // Switch to singularity — next launch clears all
        launcher.set_mode(WindowMode::Singularity);
        let spec = WindowSpecBuilder::new("final.app", "Final").build_unchecked();
        launcher.launch(spec).unwrap();
        assert_eq!(launcher.window_count(), 1);
        println!("✅ Runtime mode switch working");
    }

    #[test]
    fn test_window_operations() {
        let launcher = make_launcher();
        let spec = WindowSpecBuilder::new("ops.app", "Ops Window")
            .geometry(0, 0, 800, 600)
            .build_unchecked();
        let id = launcher.launch(spec).unwrap();

        // Geometry
        let new_geo = WindowGeometry {
            x: 50,
            y: 50,
            width: 1920,
            height: 1080,
        };
        launcher.set_geometry(id, new_geo).unwrap();
        assert_eq!(launcher.get_window(id).unwrap().geometry.width, 1920);

        // State
        launcher.set_state(id, WindowState::Maximized).unwrap();
        assert_eq!(
            launcher.get_window(id).unwrap().state,
            WindowState::Maximized
        );

        // Visibility
        launcher.set_visible(id, false).unwrap();
        assert!(!launcher.get_window(id).unwrap().visible);

        // Title
        launcher.set_title(id, "Updated Title").unwrap();
        assert_eq!(launcher.get_window(id).unwrap().spec.title, "Updated Title");

        println!("✅ Window operations working");
    }

    #[test]
    fn test_focus_management() {
        let mut launcher = make_launcher();
        launcher.set_mode(WindowMode::Multitary);

        let id1 = launcher
            .launch(WindowSpecBuilder::new("a1", "W1").build_unchecked())
            .unwrap();
        let id2 = launcher
            .launch(WindowSpecBuilder::new("a2", "W2").build_unchecked())
            .unwrap();

        launcher.set_focus(id1).unwrap();
        assert!(launcher.get_window(id1).unwrap().focused);
        assert!(!launcher.get_window(id2).unwrap().focused);
        assert_eq!(launcher.focused_window().unwrap().id, id1);

        launcher.set_focus(id2).unwrap();
        assert!(!launcher.get_window(id1).unwrap().focused);
        assert_eq!(launcher.focused_window().unwrap().id, id2);

        println!("✅ Focus management working");
    }

    #[test]
    fn test_close_window() {
        let launcher = make_launcher();
        let id = launcher.launch_from_config().unwrap();
        assert_eq!(launcher.window_count(), 1);
        launcher.close_window(id).unwrap();
        assert_eq!(launcher.window_count(), 0);
        assert!(launcher.get_window(id).is_none());
        println!("✅ Window close working");
    }

    #[test]
    fn test_close_all() {
        let mut launcher = make_launcher();
        launcher.set_mode(WindowMode::Multitary);
        for i in 0..5 {
            launcher
                .launch(
                    WindowSpecBuilder::new(format!("a{}", i), format!("W{}", i)).build_unchecked(),
                )
                .unwrap();
        }
        assert_eq!(launcher.window_count(), 5);
        launcher.close_all();
        assert_eq!(launcher.window_count(), 0);
        println!("✅ close_all working");
    }

    #[test]
    fn test_opt_override_applied() {
        let launcher = make_launcher();
        launcher.override_opt(|opt| {
            opt.draw.vsync = false;
            opt.draw.target_fps = Some(144);
            opt.xlinx.cache_mode = XlinxCacheMode::Aggressive;
        });

        let opt = launcher.opt_store.read();
        assert!(!opt.draw.vsync);
        assert_eq!(opt.draw.target_fps, Some(144));
        assert_eq!(opt.xlinx.cache_mode, XlinxCacheMode::Aggressive);
        println!("✅ Opt override applied correctly");
    }

    #[test]
    fn test_posix_opt_min_size_constraint() {
        let config = make_config();
        let mut launcher = PosixWindowLauncher::new(config);
        // Set min size via opt
        launcher.override_opt(|opt| {
            opt.draw.size.min_width = 500;
            opt.draw.size.min_height = 400;
        });

        // Launch with smaller geometry
        let spec = WindowSpecBuilder::new("small.app", "Small")
            .geometry(0, 0, 100, 100) // smaller than min
            .build_unchecked();
        let id = launcher.launch(spec).unwrap();
        let w = launcher.get_window(id).unwrap();
        // Should be clamped to min
        assert!(w.geometry.width >= 500);
        assert!(w.geometry.height >= 400);
        println!(
            "✅ PosixOpt min size constraint applied: {}x{}",
            w.geometry.width, w.geometry.height
        );
    }

    #[test]
    fn test_spec_from_manifest_invalid_values() {
        let launcher = make_launcher();
        let manifest = "
app_id=broken.app
title=Broken
width=notanumber
height=600
";
        let id = launcher
            .launch_from_manifest(manifest, "/tmp/broken.spec")
            .unwrap();
        let w = launcher.get_window(id).unwrap();
        // Invalid width should fall back to default (800)
        assert_eq!(w.spec.geometry.width, 800);
        println!("✅ Manifest invalid value fallback working");
    }

    #[test]
    fn test_uclient_engine_trait_object() {
        let launcher: Box<dyn UClientEngine> = Box::new(make_launcher());
        assert!(!launcher.is_active());
        let (total, cells, _) = launcher.memory_usage();
        assert!(total > 0 && cells > 0);
        println!("✅ UClientEngine trait object (PosixWindowLauncher) working");
    }

    #[test]
    fn test_builder() {
        let config = make_config();
        let launcher = PosixWindowLauncherBuilder::new()
            .with_config(config)
            .with_mode(WindowMode::Multitary)
            .opt_override(|opt| opt.draw.antialiasing = false)
            .build()
            .unwrap();

        assert_eq!(launcher.mode(), WindowMode::Multitary);
        assert!(!launcher.opt_store.read().draw.antialiasing);
        println!("✅ PosixWindowLauncherBuilder working");
    }

    #[test]
    fn test_list_windows_sorted() {
        let mut launcher = make_launcher();
        launcher.set_mode(WindowMode::Multitary);
        for i in 0..4 {
            launcher
                .launch(
                    WindowSpecBuilder::new(format!("a{}", i), format!("W{}", i)).build_unchecked(),
                )
                .unwrap();
        }
        let windows = launcher.list_windows();
        assert_eq!(windows.len(), 4);
        for pair in windows.windows(2) {
            assert!(pair[0].id < pair[1].id);
        }
        println!("✅ list_windows sorted correctly");
    }
}