wasma-client 1.2.0-beta2

Windows Assignment System Monitoring Architecture - Cross-platform resource-aware window management
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
// WASMA - Windows Assignment System Monitoring Architecture
// Main Entry Point - CLI & GUI Support
// January 14, 2026

use clap::{Parser, Subcommand};
use std::process;
use wasma_client::{
    WasmaCore,
    ResourceMode, WindowState,
};

/// Initialize a default configuration file
fn init_config(output: Option<String>) -> Result<String, String> {
    use std::fs;
    use wasma_client::parser::{WasmaConfig, UriHandlingConfig, UserConfig, ResourceLimits};
    
    let default_config = WasmaConfig {
        uri_handling: UriHandlingConfig {
            window_app_spec: "default.app".to_string(),
            protocols: vec![],
            multi_instances: true,
            singularity_instances: false,
            compilation_server: None,
        },
        user_config: UserConfig {
            user_withed: "user".to_string(),
            groups_withed: vec![],
        },
        resource_limits: ResourceLimits {
            ip_scope: "local".to_string(),
            scope_level: 1,
            renderer: "cpu".to_string(),
            execution_mode: None,
            max_memory_mb: Some(1024),
            max_vram_mb: Some(512),
            cpu_cores: vec![],
        },
    };
    
    let output_path = output.unwrap_or_else(|| "wasmal.conf".to_string());
    let toml_content = toml::to_string_pretty(&default_config)
        .map_err(|e| format!("Failed to serialize config: {}", e))?;
    
    fs::write(&output_path, toml_content)
        .map_err(|e| format!("Failed to write config file: {}", e))?;
    
    Ok(output_path)
}

/// Validate a configuration file
fn validate_config(config_path: Option<String>) -> Result<(), String> {
    use wasma_client::ConfigParser;
    
    let parser = ConfigParser::new(config_path);
    parser.load().map_err(|e| e.to_string())?;
    Ok(())
}

/// Print configuration information
fn print_config_info(config_path: Option<String>) -> Result<(), String> {
    use wasma_client::ConfigParser;
    
    let parser = ConfigParser::new(config_path);
    let config = parser.load().map_err(|e| e.to_string())?;
    
    println!("WASMA Configuration:");
    println!("  URI Handling:");
    println!("    Window App Spec: {}", config.uri_handling.window_app_spec);
    println!("    Protocols: {:?}", config.uri_handling.protocols);
    println!("  User Config:");
    println!("    User: {}", config.user_config.user_withed);
    println!("    Groups: {:?}", config.user_config.groups_withed);
    println!("  Resource Limits:");
    println!("    IP Scope: {}", config.resource_limits.ip_scope);
    println!("    Scope Level: {}", config.resource_limits.scope_level);
    println!("    Renderer: {}", config.resource_limits.renderer);
    if let Some(mem) = config.resource_limits.max_memory_mb {
        println!("    Max Memory: {} MB", mem);
    }
    if let Some(vram) = config.resource_limits.max_vram_mb {
        println!("    Max VRAM: {} MB", vram);
    }
    println!("    CPU Cores: {:?}", config.resource_limits.cpu_cores);
    
    Ok(())
}

#[derive(Parser)]
#[command(name = "wasma")]
#[command(author = "WASMA Project")]
#[command(version = "1.0.0")]
#[command(about = "Windows Assignment System Monitoring Architecture", long_about = None)]
struct Cli {
    /// Path to configuration file
    #[arg(short, long, value_name = "FILE")]
    config: Option<String>,

    /// Resource mode (auto/manual)
    #[arg(short = 'm', long, value_enum, default_value = "auto")]
    resource_mode: ResourceModeArg,

    /// Enable verbose logging
    #[arg(short, long)]
    verbose: bool,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(clap::ValueEnum, Clone, Debug)]
enum ResourceModeArg {
    Auto,
    Manual,
}

impl From<ResourceModeArg> for ResourceMode {
    fn from(arg: ResourceModeArg) -> Self {
        match arg {
            ResourceModeArg::Auto => ResourceMode::Auto,
            ResourceModeArg::Manual => ResourceMode::Manual,
        }
    }
}

#[derive(Subcommand)]
enum Commands {
    /// Launch GUI window manager
    Gui {
        /// Window width
        #[arg(short, long, default_value = "1200")]
        width: u32,
        
        /// Window height
        #[arg(short = 'h', long, default_value = "800")]
        height: u32,
    },

    /// Initialize default configuration file
    Init {
        /// Output path for config file
        #[arg(short, long)]
        output: Option<String>,
    },

    /// Validate configuration file
    Validate,

    /// Show configuration information
    Info,

    /// Create a new window (CLI mode)
    Create {
        /// Window title
        #[arg(short, long)]
        title: String,

        /// Application ID
        #[arg(short, long)]
        app_id: String,

        /// Window width
        #[arg(short, long, default_value = "800")]
        width: u32,

        /// Window height
        #[arg(short = 'h', long, default_value = "600")]
        height: u32,

        /// Manifest file path
        #[arg(short, long)]
        manifest: Option<String>,
    },

    /// List all windows
    List {
        /// Show detailed information
        #[arg(short, long)]
        detailed: bool,
    },

    /// Close a window
    Close {
        /// Window ID to close
        window_id: u64,
    },

    /// Focus a window
    Focus {
        /// Window ID to focus
        window_id: u64,
    },

    /// Get window resource usage
    Resources {
        /// Window ID
        window_id: u64,
    },

    /// Set window state
    State {
        /// Window ID
        window_id: u64,

        /// New state (normal/minimized/maximized/fullscreen/hidden)
        #[arg(value_enum)]
        state: StateArg,
    },

    /// Run resource management cycle
    Cycle {
        /// Number of cycles to run (0 = continuous)
        #[arg(short, long, default_value = "1")]
        count: u32,
    },

    /// Start UClient engine (direct renderer mode)
    UClient {
        /// Force raw stream mode (scope_level=0)
        #[arg(short, long)]
        raw: bool,
    },
}

#[derive(clap::ValueEnum, Clone, Debug)]
enum StateArg {
    Normal,
    Minimized,
    Maximized,
    Fullscreen,
    Hidden,
}

impl From<StateArg> for WindowState {
    fn from(arg: StateArg) -> Self {
        match arg {
            StateArg::Normal => WindowState::Normal,
            StateArg::Minimized => WindowState::Minimized,
            StateArg::Maximized => WindowState::Maximized,
            StateArg::Fullscreen => WindowState::Fullscreen,
            StateArg::Hidden => WindowState::Hidden,
        }
    }
}

fn main() {
    let cli = Cli::parse();

    if cli.verbose {
        env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("debug"))
            .init();
        println!("🔍 Verbose mode enabled");
    } else {
        env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
            .init();
    }

    match &cli.command {
        Some(Commands::Init { output }) => {
            handle_init(output.clone());
        }
        Some(Commands::Validate) => {
            handle_validate(cli.config);
        }
        Some(Commands::Info) => {
            handle_info(cli.config);
        }
        Some(Commands::Gui { width, height }) => {
            handle_gui(cli.config, cli.resource_mode.into(), *width, *height);
        }
        Some(Commands::Create { title, app_id, width, height, manifest }) => {
            handle_create(cli.config, cli.resource_mode.into(), title, app_id, *width, *height, manifest.clone());
        }
        Some(Commands::List { detailed }) => {
            handle_list(cli.config, cli.resource_mode.into(), *detailed);
        }
        Some(Commands::Close { window_id }) => {
            handle_close(cli.config, cli.resource_mode.into(), *window_id);
        }
        Some(Commands::Focus { window_id }) => {
            handle_focus(cli.config, cli.resource_mode.into(), *window_id);
        }
        Some(Commands::Resources { window_id }) => {
            handle_resources(cli.config, cli.resource_mode.into(), *window_id);
        }
        Some(Commands::State { window_id, state }) => {
            handle_state(cli.config, cli.resource_mode.into(), *window_id, state.clone().into());
        }
        Some(Commands::Cycle { count }) => {
            handle_cycle(cli.config, cli.resource_mode.into(), *count);
        }
        Some(Commands::UClient { raw }) => {
            handle_uclient(cli.config, *raw);
        }
        None => {
            // Default: Launch GUI
            handle_gui(cli.config, cli.resource_mode.into(), 1200, 800);
        }
    }
}

fn handle_init(output: Option<String>) {
    println!("🔧 Initializing WASMA configuration...");
    match init_config(output) {
        Ok(path) => {
            println!("✅ Configuration file created: {}", path);
            println!("   Edit this file to customize your WASMA setup.");
        }
        Err(e) => {
            eprintln!("❌ Failed to initialize config: {}", e);
            process::exit(1);
        }
    }
}

fn handle_validate(config_path: Option<String>) {
    println!("🔍 Validating configuration...");
    match validate_config(config_path) {
        Ok(_) => {
            println!("✅ Configuration is valid!");
        }
        Err(e) => {
            eprintln!("❌ Configuration validation failed: {}", e);
            process::exit(1);
        }
    }
}

fn handle_info(config_path: Option<String>) {
    if let Err(e) = print_config_info(config_path) {
        eprintln!("❌ Failed to read config: {}", e);
        process::exit(1);
    }
}

fn handle_gui(config_path: Option<String>, resource_mode: ResourceMode, _width: u32, _height: u32) {
    println!("🖥️  Launching WASMA GUI Window Manager...");
    
    let core = match build_core(config_path, Some(resource_mode)) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("❌ Failed to initialize WASMA Core: {}", e);
            process::exit(1);
        }
    };

    println!("🚀 Starting GUI with resource mode: {:?}", resource_mode);
    
    if let Err(e) = core.launch_gui() {
        eprintln!("❌ GUI failed: {}", e);
        process::exit(1);
    }
}

fn handle_create(
    config_path: Option<String>,
    resource_mode: ResourceMode,
    title: &str,
    app_id: &str,
    width: u32,
    height: u32,
    manifest: Option<String>,
) {
    let core = match build_core(config_path, Some(resource_mode)) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("❌ Failed to initialize WASMA Core: {}", e);
            process::exit(1);
        }
    };

    println!("🪟 Creating window: {}", title);
    
    let result = if manifest.is_some() {
        core.create_window(
            title.to_string(),
            app_id.to_string(),
            width,
            height,
        )
    } else {
        core.create_window(
            title.to_string(),
            app_id.to_string(),
            width,
            height,
        )
    };

    match result {
        Ok(window_id) => {
            println!("✅ Window created successfully!");
            println!("   Window ID: {}", window_id);
            println!("   Title: {}", title);
            println!("   Size: {}x{}", width, height);
            println!("   Mode: {:?}", resource_mode);
        }
        Err(e) => {
            eprintln!("❌ Failed to create window: {}", e);
            process::exit(1);
        }
    }
}

fn handle_list(config_path: Option<String>, resource_mode: ResourceMode, detailed: bool) {
    let core = match build_core(config_path, Some(resource_mode)) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("❌ Failed to initialize WASMA Core: {}", e);
            process::exit(1);
        }
    };

    let windows = core.list_windows();

    if windows.is_empty() {
        println!("ℹ️  No active windows.");
        return;
    }

    println!("╔════════════════════════════════════════════════════════════╗");
    println!("║                    Active Windows                          ║");
    println!("╚════════════════════════════════════════════════════════════╝\n");

    for window in &windows {
        let state_icon = match window.state {
            WindowState::Normal => "🟢",
            WindowState::Minimized => "🟡",
            WindowState::Maximized => "🔵",
            WindowState::Fullscreen => "",
            WindowState::Hidden => "",
        };

        let focus = if window.focused { "👁️ " } else { "" };

        println!("{}{} Window #{}: {}", focus, state_icon, window.id, window.title);
        println!("   App ID: {}", window.app_id);
        println!("   Geometry: {}x{} at ({}, {})", 
            window.geometry.width, 
            window.geometry.height,
            window.geometry.x,
            window.geometry.y
        );
        println!("   Visible: {} | Focused: {}", window.visible, window.focused);

        if detailed {
            println!("   Renderer: {}", window.resource_limits.renderer);
            println!("   Execution Mode: {:?}", window.resource_limits.execution_mode);
            
            if let Ok(usage) = core.get_window_resources(window.id) {
                println!("   RAM: {} MiB | VRAM: {} MiB", 
                    usage.ram_allocated_mb, 
                    usage.vram_allocated_mb
                );
                println!("   CPU Cores: {:?}", usage.cpu_cores);
                if let Some(ref gpu) = usage.gpu_device {
                    println!("   GPU: {}", gpu);
                }
                println!("   Task Active: {} | GPU Active: {}", 
                    usage.task_active, 
                    usage.gpu_active
                );
                if usage.remaining_lease_secs > 0 {
                    println!("   Lease Remaining: {}s", usage.remaining_lease_secs);
                }
            }
        }

        println!();
    }

    println!("Total windows: {}", windows.len());
}

fn handle_close(config_path: Option<String>, resource_mode: ResourceMode, window_id: u64) {
    let core = match build_core(config_path, Some(resource_mode)) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("❌ Failed to initialize WASMA Core: {}", e);
            process::exit(1);
        }
    };

    println!("🗑️  Closing window {}...", window_id);
    
    match core.close_window(window_id) {
        Ok(_) => {
            println!("✅ Window {} closed successfully", window_id);
        }
        Err(e) => {
            eprintln!("❌ Failed to close window: {}", e);
            process::exit(1);
        }
    }
}

fn handle_focus(config_path: Option<String>, resource_mode: ResourceMode, window_id: u64) {
    let core = match build_core(config_path, Some(resource_mode)) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("❌ Failed to initialize WASMA Core: {}", e);
            process::exit(1);
        }
    };

    println!("👁️  Focusing window {}...", window_id);
    
    match core.focus_window(window_id) {
        Ok(_) => {
            println!("✅ Window {} is now focused", window_id);
        }
        Err(e) => {
            eprintln!("❌ Failed to focus window: {}", e);
            process::exit(1);
        }
    }
}

fn handle_resources(config_path: Option<String>, resource_mode: ResourceMode, window_id: u64) {
    let core = match build_core(config_path, Some(resource_mode)) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("❌ Failed to initialize WASMA Core: {}", e);
            process::exit(1);
        }
    };

    match core.get_window_resources(window_id) {
        Ok(usage) => {
            println!("╔════════════════════════════════════════════════════════════╗");
            println!("║           Window #{} Resource Usage                       ║", window_id);
            println!("╚════════════════════════════════════════════════════════════╝\n");
            
            println!("📊 Assignment ID: {}", usage.assignment_id);
            println!("💾 RAM Allocated: {} MiB", usage.ram_allocated_mb);
            println!("🎮 VRAM Allocated: {} MiB", usage.vram_allocated_mb);
            println!("🔧 CPU Cores: {:?}", usage.cpu_cores);
            
            if let Some(ref gpu) = usage.gpu_device {
                println!("🎨 GPU Device: {}", gpu);
            } else {
                println!("🎨 GPU Device: None");
            }
            
            println!("⚙️  Execution Mode: {:?}", usage.execution_mode);
            println!("🟢 Task Active: {}", usage.task_active);
            println!("🎯 GPU Active: {}", usage.gpu_active);
            
            if usage.remaining_lease_secs > 0 {
                println!("⏱️  Lease Remaining: {}s", usage.remaining_lease_secs);
            }
        }
        Err(e) => {
            eprintln!("❌ Failed to get resources: {}", e);
            process::exit(1);
        }
    }
}

fn handle_state(
    config_path: Option<String>,
    resource_mode: ResourceMode,
    window_id: u64,
    state: WindowState,
) {
    let core = match build_core(config_path, Some(resource_mode)) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("❌ Failed to initialize WASMA Core: {}", e);
            process::exit(1);
        }
    };

    println!("🔄 Setting window {} state to {:?}...", window_id, state);
    
    match core.set_window_state(window_id, state) {
        Ok(_) => {
            println!("✅ Window state changed successfully");
        }
        Err(e) => {
            eprintln!("❌ Failed to change state: {}", e);
            process::exit(1);
        }
    }
}

fn handle_cycle(config_path: Option<String>, resource_mode: ResourceMode, count: u32) {
    let core = match build_core(config_path, Some(resource_mode)) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("❌ Failed to initialize WASMA Core: {}", e);
            process::exit(1);
        }
    };

    if count == 0 {
        println!("🔄 Running resource management cycle continuously...");
        println!("   Press Ctrl+C to stop");
        loop {
            core.update();
            std::thread::sleep(std::time::Duration::from_secs(1));
        }
    } else {
        println!("🔄 Running {} resource management cycle(s)...", count);
        for i in 1..=count {
            println!("   Cycle {}/{}", i, count);
            core.update();
            if i < count {
                std::thread::sleep(std::time::Duration::from_millis(500));
            }
        }
        println!("✅ Resource cycles completed");
    }
}

fn handle_uclient(config_path: Option<String>, raw: bool) {
    use wasma_client::{ConfigParser, uclient::UClient};

    println!("🔌 Starting UClient engine...");
    
    let parser = ConfigParser::new(config_path);
    let mut config = match parser.load() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("❌ Failed to load config: {}", e);
            process::exit(1);
        }
    };

    if raw {
        println!("⚡ Force enabling RAW mode (scope_level=0)");
        config.resource_limits.scope_level = 0;
    }

    let mut client = UClient::new(config);
    
    println!("🚀 UClient engine started");
    
    if let Err(e) = client.start_engine() {
        eprintln!("❌ UClient engine error: {}", e);
        process::exit(1);
    }
}

fn build_core(
    config_path: Option<String>,
    _resource_mode: Option<ResourceMode>,
) -> Result<WasmaCore, String> {
    // Note: resource_mode parameter is currently unused in WasmaCore::new
    // It uses the config to determine resource mode
    WasmaCore::new(config_path).map_err(|e| e.to_string())
}