cardinal-gui 0.3.4

Simple GUI for a Uxn + Varvara system
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
use cardinal_gui::uxn::audio_setup;
use cardinal_gui::uxn::InjectEvent;

/// Injects a string as Orca events, simulating character entry with right/left/down arrows
fn build_orca_inject_queue_from_chars(
    chars: &str,
) -> std::collections::VecDeque<InjectEvent> {
    use std::collections::VecDeque;
    use varvara::Key;
    let mut queue = VecDeque::new();
    const CTRL_H: Key = Key::Ctrl;
    const RIGHT: Key = Key::Right;
    const LEFT: Key = Key::Left;
    const DOWN: Key = Key::Down;
    // Send Ctrl + . four times instead of Ctrl+H
    const CTRL: Key = Key::Ctrl;
    const COMMA: Key = Key::Char(b',');

    // Inject Ctrl+Comma as a chord 7 times, then release both
    for _ in 0..7 {
        queue.push_back(InjectEvent::Chord(vec![CTRL, COMMA]));
        queue.push_back(InjectEvent::KeyRelease(COMMA));
        queue.push_back(InjectEvent::KeyRelease(CTRL));
    }
    // Inject each character, move right after each
    let mut arrow_count = 0;
    for ch in chars.chars() {
        let byte = ch as u8;
        queue.push_back(InjectEvent::Char(byte));
        queue.push_back(InjectEvent::KeyPress(RIGHT));
        queue.push_back(InjectEvent::KeyRelease(RIGHT));
        arrow_count += 1;
    }

    // After all chars, send LEFT_ARROW 'arrow_count' times to return to column 0
    for _ in 0..arrow_count {
        queue.push_back(InjectEvent::KeyPress(RIGHT));
        queue.push_back(InjectEvent::KeyRelease(RIGHT));
    }
    // Send DOWN_ARROW to move to next line
    queue.push_back(InjectEvent::KeyPress(DOWN));
    queue.push_back(InjectEvent::KeyRelease(DOWN));
    queue.push_back(InjectEvent::KeyPress(DOWN));
    queue.push_back(InjectEvent::KeyRelease(DOWN));

    queue
}
/// Build an InjectEvent queue for orca file injection with rectangle and efficient movement
fn build_orca_inject_queue(
    file_path: &str,
) -> std::collections::VecDeque<InjectEvent> {
    use std::collections::VecDeque;
    use std::fs::File;
    use std::io::{BufRead, BufReader};
    use varvara::Key;
    let mut queue = VecDeque::new();
    const CTRL_H: Key = Key::Ctrl;
    const RIGHT: Key = Key::Right;
    const LEFT: Key = Key::Left;
    const UP: Key = Key::Up;
    const DOWN: Key = Key::Down;
    // Read file into lines
    let mut lines: Vec<Vec<char>> = Vec::new();
    let mut max_len = 0;
    if let Ok(file) = File::open(file_path) {
        let reader = BufReader::new(file);
        for line in reader.lines().flatten() {
            let chars: Vec<char> = line.chars().collect();
            max_len = max_len.max(chars.len());
            lines.push(chars);
        }
    }
    let rows = lines.len();
    let cols = max_len;
    // Build rectangle with '/' border
    let mut grid = vec![vec![' '; cols + 2]; rows + 2];
    // Fill top and bottom borders
    for c in 0..cols + 2 {
        grid[0][c] = '/';
        grid[rows + 1][c] = '/';
    }
    // Fill left and right borders with '/' (actual border logic handled in event queue below)
    // Fill file contents
    for (i, line) in lines.iter().enumerate() {
        for (j, &ch) in line.iter().enumerate() {
            grid[i + 1][j + 1] = ch;
        }
    }
    // Start at (1,1)
    let mut cur_row = 1;
    let mut cur_col = 1;
    queue.push_back(InjectEvent::KeyPress(CTRL_H));
    queue.push_back(InjectEvent::KeyRelease(CTRL_H));
    // Visit all non '.' cells efficiently
    let mut visited = vec![vec![false; cols + 2]; rows + 2];
    for r in 0..rows + 2 {
        for c in 0..cols + 2 {
            if grid[r][c] != '.' && !visited[r][c] {
                // Move to (r,c)
                let dr = r as isize - cur_row as isize;
                let dc = c as isize - cur_col as isize;
                for _ in 0..dr.abs() {
                    queue.push_back(if dr > 0 {
                        InjectEvent::KeyPress(DOWN)
                    } else {
                        InjectEvent::KeyPress(UP)
                    });
                    queue.push_back(if dr > 0 {
                        InjectEvent::KeyRelease(DOWN)
                    } else {
                        InjectEvent::KeyRelease(UP)
                    });
                }
                for _ in 0..dc.abs() {
                    queue.push_back(if dc > 0 {
                        InjectEvent::KeyPress(RIGHT)
                    } else {
                        InjectEvent::KeyPress(LEFT)
                    });
                    queue.push_back(if dc > 0 {
                        InjectEvent::KeyRelease(RIGHT)
                    } else {
                        InjectEvent::KeyRelease(LEFT)
                    });
                }
                cur_row = r;
                cur_col = c;
                // Print char
                if r == 0 || r == rows + 1 {
                    // Top or bottom border: just '/'
                    if grid[r][c] == '/' {
                        queue.push_back(InjectEvent::Char('/' as u8));
                    } else {
                        queue.push_back(InjectEvent::Char(grid[r][c] as u8));
                    }
                } else if c == 0 {
                    // Left border: '/' then row and col as two hex digits each
                    queue.push_back(InjectEvent::Char('/' as u8));
                    queue.push_back(InjectEvent::KeyPress(RIGHT));
                    let hex = format!("{:01X}{:01X}", r, c);
                    for b in hex.bytes() {
                        queue.push_back(InjectEvent::Char(b));

                        queue.push_back(InjectEvent::KeyRelease(RIGHT));
                    }
                } else if c == cols + 1 {
                    // Right border: '/' then row and col as two hex digits each
                    queue.push_back(InjectEvent::Char('/' as u8));
                    queue.push_back(InjectEvent::KeyPress(RIGHT));
                    let hex = format!("{:01X}{:01X}", r, c);
                    for b in hex.bytes() {
                        queue.push_back(InjectEvent::Char(b));
                        queue.push_back(InjectEvent::KeyRelease(RIGHT));
                    }
                    // After right border, return to start of next row
                    for _ in 0..(cols + 1) {
                        queue.push_back(InjectEvent::KeyPress(LEFT));
                        queue.push_back(InjectEvent::KeyRelease(LEFT));
                    }
                    queue.push_back(InjectEvent::KeyPress(DOWN));
                } else {
                    // File contents
                    queue.push_back(InjectEvent::Char(grid[r][c] as u8));
                }
                visited[r][c] = true;
            }
        }
    }
    queue
}
// cardinal-demo.rs - Uxn GUI runner for crate, with ROM selection and download

use cardinal_gui::uxn::{UxnApp, UxnModule};
use eframe::egui;
#[cfg(not(target_arch = "wasm32"))]
use eframe::NativeOptions;
use notify::{Config, Event, RecommendedWatcher, RecursiveMode, Watcher};
#[cfg(not(target_arch = "wasm32"))]
use reqwest::blocking::Client;
use reqwest::Url;
use std::io::Write;
use std::path::PathBuf;
use std::sync::mpsc;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
use std::time::Duration;

#[cfg(not(target_arch = "wasm32"))]
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args: Vec<String> = std::env::args().collect();
    let mut rom_path: Option<PathBuf> = None;
    let mut scale: f32 = 2.0;
    let mut window_size = (640, 480);
    let mut title = "crate Uxn".to_string();
    let mut window_mode = "free".to_string(); // static, free, proportional

    // Parse CLI args (simple version, extend as needed)
    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            "--rom" => {
                if i + 1 < args.len() {
                    rom_path = Some(PathBuf::from(&args[i + 1]));
                    i += 1;
                }
            }
            "--scale" => {
                if i + 1 < args.len() {
                    scale = args[i + 1].parse().unwrap_or(scale);
                    i += 1;
                }
            }
            "--width" => {
                if i + 1 < args.len() {
                    window_size.0 =
                        args[i + 1].parse().unwrap_or(window_size.0);
                    i += 1;
                }
            }
            "--height" => {
                if i + 1 < args.len() {
                    window_size.1 =
                        args[i + 1].parse().unwrap_or(window_size.1);
                    i += 1;
                }
            }
            "--title" => {
                if i + 1 < args.len() {
                    title = args[i + 1].clone();
                    i += 1;
                }
            }
            "--window-mode" => {
                if i + 1 < args.len() {
                    window_mode = args[i + 1].to_lowercase();
                    i += 1;
                }
            }
            _ => {}
        }
        i += 1;
    }

    // --- Static ROM URLs ---
    let static_rom_urls = vec![
        (
            "orca-toy/orca.rom",
            "https://rabbits.srht.site/orca-toy/orca.rom",
        ),
        // (
        //     "orca-toy/bin/orca.rom",
        //     "file:///C:/w/music/orca-toy/bin/orca.rom",
        // ),
        // (
        //     "write_to_file.rom",
        //     "file:///C:/w/music/orca-toy/bin/write_to_file.rom",
        // ),
        ("potato.rom", "https://rabbits.srht.site/potato/potato.rom"),
        //("uxn.rom", "https://rabbits.srht.site/uxn/uxn.rom"),
        ("oekaki.rom", "https://rabbits.srht.site/oekaki/oekaki.rom"),
        ("flick.rom", "https://rabbits.srht.site/flick/flick.rom"),
        //("adelie.rom", "https://rabbits.srht.site/adelie/adelie.rom"),
        //("nasu.rom", "https://hundredrabbits.itch.io/nasu"),
        // ("noodle.rom", "https://hundredrabbits.itch.io/noodle"),
        // ("left.rom", "http://hundredrabbits.itch.io/Left")
        // Add more static ROMs here: ("label", "url")
    ];

    // Download static ROMs and collect their names and paths
    let mut static_rom_names = Vec::new();
    let mut static_rom_paths = Vec::new();
    for (label, url) in &static_rom_urls {
        let path = download_static_rom(label, url)?;
        static_rom_names.push(label.to_string());
        static_rom_paths.push(path);
    }

    // If no ROM is selected, fetch ROM list and prompt user
    let mut auto_rom_select = false;
    let mut selected_rom_label: Option<String> = None;
    if rom_path.is_none() {
        let mut roms = static_rom_names.clone();
        let github_roms = fetch_rom_list()?;
        roms.extend(github_roms.iter().cloned());
        let selected = prompt_rom_selection(&roms)?;
        if selected == "__AUTO__" {
            // User hit return: enable auto ROM cycling
            auto_rom_select = true;
        } else {
            let idx = roms.iter().position(|r| r == &selected).unwrap_or(0);
            selected_rom_label = Some(roms[idx].clone());
            if idx < static_rom_paths.len() {
                rom_path = Some(static_rom_paths[idx].clone());
                title = format!("cardinal-demo - {}", roms[idx]);
            } else {
                let github_idx = idx - static_rom_paths.len();
                let rom_file = download_rom(&github_roms[github_idx])?;
                title = format!("cardinal-demo - {}", github_roms[github_idx]);
                rom_path = Some(rom_file);
            }
        }
    } else if let Some(path) = &rom_path {
        if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
            selected_rom_label = Some(name.to_string());
            title = format!("cardinal-demo - {}", name);
        }
    }

    // Build all_roms and all_labels if needed (for auto ROM cycling)
    let mut all_roms: Vec<Vec<u8>> = Vec::new();
    let mut all_labels: Vec<String> = Vec::new();
    if auto_rom_select {
        // Add static ROMs first
        for (i, path) in static_rom_paths.iter().enumerate() {
            let bytes = std::fs::read(path)?;
            all_roms.push(bytes);
            all_labels.push(static_rom_names[i].clone());
        }
        // Then add GitHub ROMs
        let github_roms = fetch_rom_list()?;
        for name in &github_roms {
            let rom_file = download_rom(name)?;
            let bytes = std::fs::read(&rom_file)?;
            all_roms.push(bytes);
            all_labels.push(name.clone());
        }
    }

    // --- Helper to download static ROMs by URL ---
    fn download_static_rom(
        _label: &str,
        url: &str,
    ) -> Result<std::path::PathBuf, String> {
        if url.starts_with("file://") {
            // Use the local file path directly
            let mut path_str = &url[7..];
            // On Windows, strip leading slash if path is like /C:/...
            #[cfg(windows)]
            {
                if path_str.len() > 2
                    && path_str.as_bytes()[0] == b'/'
                    && path_str.as_bytes()[2] == b':'
                {
                    path_str = &path_str[1..];
                }
            }
            let path = std::path::PathBuf::from(path_str);
            if path.exists() {
                Ok(path)
            } else {
                Err(format!("Local file not found: {}", path.display()))
            }
        } else {
            let client = reqwest::blocking::Client::builder()
                .user_agent("cardinal-demo")
                .build()
                .map_err(|e| e.to_string())?;
            let resp = client.get(url).send().map_err(|e| e.to_string())?;
            let bytes = resp.bytes().map_err(|e| e.to_string())?;
            let mut file =
                tempfile::NamedTempFile::new().map_err(|e| e.to_string())?;
            file.write_all(&bytes).map_err(|e| e.to_string())?;
            let path =
                file.into_temp_path().keep().map_err(|e| e.to_string())?;
            Ok(path)
        }
    }

    // Create UxnModule
    let rom_path_arc = Arc::new(Mutex::new(rom_path.clone()));
    let mut uxn_mod = UxnModule::new(rom_path.as_ref().map(|p| p.as_path()))?;
    // --- ROM File Watcher ---
    let (reload_tx, reload_rx) = std::sync::mpsc::channel();
    if let Some(ref rom_path) = rom_path {
        let rom_path_buf = rom_path.clone();
        thread::spawn(move || {
            let mut watcher = RecommendedWatcher::new(
                move |res: Result<Event, notify::Error>| {
                    if let Ok(event) = res {
                        if event.kind.is_modify() {
                            reload_tx.send(()).ok();
                            println!("[ROM WATCHER] Detected change in ROM file: {:?}", event.paths);
                        }
                    }
                },
                Config::default(),
            ).expect("Failed to create watcher");
            watcher
                .watch(&rom_path_buf, RecursiveMode::NonRecursive)
                .expect("Failed to watch ROM file");
            // Keep the watcher alive
            loop {
                std::thread::sleep(Duration::from_secs(60));
            }
        });
    }
    // // Add reload_rom method to UxnModule if not present
    // trait ReloadableUxnModule {
    //     fn reload_rom(&mut self, path: &std::path::Path) -> Result<(), String>;
    // }

    // impl ReloadableUxnModule for UxnModule {
    //     fn reload_rom(&mut self, path: &std::path::Path) -> Result<(), String> {
    //         // Replace the ROM in the VM
    //         // If load_rom expects a path, use it directly
    //         self.load_rom(path).map_err(|e| e.to_string())?;
    //         // Beep twice on reload
    //         beep();
    //         beep();
    //         Ok(())
    //     }
    // }

    // Set up event channel for UxnApp
    let (_event_tx, event_rx) = mpsc::channel();

    let vm = Arc::clone(&uxn_mod.uxn);
    let mut vm = vm.lock().unwrap();
    let mut dev = uxn_mod.varvara.take().expect("Varvara device missing");
    let _audio = audio_setup(dev.audio_streams());

    // Use selected_rom_label for matching, not temp file name
    println!("[DEBUG] selected_rom_label: {:?}", selected_rom_label);
    if let Some(label) = &selected_rom_label {
        if label.contains("orca.rom") {
            // println!("[DEBUG] ROM matched orca.rom by label: {}", label);
            // let dir_path = r"C:\w\music\Orca-c\examples\basics";
            // let entries = fs::read_dir(dir_path)
            //     .map_err(|e| format!("Failed to read directory: {}", e))
            //     .and_then(|read_dir| {
            //     let files: Vec<_> = read_dir
            //         .filter_map(|entry| {
            //         entry.ok().and_then(|e| {
            //             let path = e.path();
            //             if path.extension().and_then(|ext| ext.to_str()) == Some("orca") {
            //             Some(path)
            //             } else {
            //             None
            //             }
            //         })
            //         })
            //         .collect();
            //     if files.is_empty() {
            //         Err("No .orca files found".to_string())
            //     } else {
            //         Ok(files)
            //     }
            //     });

            // match entries {
            //     Ok(files) => {
            //     let mut rng = rand::thread_rng();
            //     if let Some(random_file) = files.choose(&mut rng) {
            //         println!("[DEBUG] Detected orca.rom, sending {:?} to console...", random_file);
            //         match send_orca_file_to_console(&mut dev, &mut vm, random_file.to_str().unwrap()) {
            //         Ok(_) => println!("[DEBUG] {:?} sent to console successfully.", random_file),
            //         Err(e) => eprintln!("Failed to send file: {}", e),
            //         }
            //     }
            //     }
            //     Err(e) => {
            //     eprintln!("[DEBUG] Could not select random .orca file: {}", e);
            //     }
            // }
        } else {
            println!("[DEBUG] ROM label did not match orca.rom: {}", label);
        }
    } else {
        println!("[DEBUG] selected_rom_label is None");
    }
    #[cfg(windows)]
    fn beep() {
        unsafe {
            winapi::um::winuser::MessageBeep(0xFFFFFFFF);
        }
    }

    #[cfg(not(windows))]
    fn beep() {
        print!("\x07");
    }
    // Register listeners for console output
    dev.console.register_stdout_listener(|byte| {
        eprint!("{:02X} ", byte);
        eprintln!();
        beep();
    });
    dev.console.register_stderr_listener(|byte| {
        println!("Console stderr: {}", byte);
    });

    dev.audio(&mut vm);
    let size = dev.output(&vm).size;
    drop(vm); // Release lock

    let mut viewport = egui::ViewportBuilder::default()
        .with_inner_size([
            (window_size.0 as f32 * scale) as f32,
            (window_size.1 as f32 * scale) as f32,
        ])
        .with_title(&title);

    match window_mode.as_str() {
        "static" => {
            viewport = viewport.with_resizable(false);
        }
        _ => {
            viewport = viewport.with_resizable(true);
        }
    }

    let options = NativeOptions {
        viewport,
        ..Default::default()
    };

    // If auto_rom_select, pass all_roms and set auto_rom_select flag, else pass empty vec and false
    let app_all_roms = if auto_rom_select {
        all_roms.clone()
    } else {
        Vec::new()
    };
    let app_auto_rom_select = auto_rom_select;

    eframe::run_native(
        &title,
        options,
        Box::new(move |cc| {
            let ctx = &cc.egui_ctx;
            let vm = Arc::clone(&uxn_mod.uxn);
            let mut vm = vm.lock().unwrap();
            static mut RAM: [u8; 65536] = [0; 65536];
            let ram: &'static mut [u8; 65536] = unsafe { &mut RAM };
            let new_uxn = uxn::Uxn::new(ram, uxn::Backend::Interpreter);
            let mut app = UxnApp::new_with_mode(
                std::mem::replace(&mut *vm, new_uxn),
                dev,
                size,
                scale,
                event_rx,
                ctx,
                window_mode.clone(),
                app_all_roms,
                if app_auto_rom_select {
                    all_labels.clone()
                } else {
                    Vec::new()
                },
                app_auto_rom_select,
                reload_rx,
                rom_path_arc,
            );
            if app_auto_rom_select {
                let ctx = cc.egui_ctx.clone();
                app.set_on_rom_change(move |rom_name| {
                    ctx.send_viewport_cmd(egui::ViewportCommand::Title(
                        format!("cardinal-demo - {}", rom_name),
                    ));
                });
            }

            // --- Orca file injection after UI is ready ---
            // let mut pending_orca_inject = false;
            // let orca_dir = r"C:\w\music\Orca-c\examples\basics";
            // let orca_path = format!("{}/k.orca", orca_dir);
            // if let Some(label) = &selected_rom_label {
            //     if label.contains("orca.rom") {
            //         pending_orca_inject = true;
            //     }
            // }
            // if pending_orca_inject {
            //     let orca_path = orca_path.clone();
            //     app.set_on_first_update(Box::new(move |app_ref: &mut UxnApp| {
            //         let queue = build_orca_inject_queue(&orca_path);
            //         app_ref.queue_input(queue);
            //     }));
            // }

            // --- Inject HornersOrca file if selected ROM is orca.rom ---
            if let Some(label) = &selected_rom_label {
                if label.contains("orca.rom") {
                    let horners_orca_chars = "horners.orca";
                    let queue =
                        build_orca_inject_queue_from_chars(horners_orca_chars);
                    app.queue_input(queue);
                }
            }

            Ok(Box::new(app) as Box<dyn eframe::App>)
        }),
    )?;
    Ok(())
}

/// Fetch the list of ROMs from the GitHub directory listing
#[cfg(not(target_arch = "wasm32"))]
fn fetch_rom_list() -> Result<Vec<String>, String> {
    let url = "https://api.github.com/repos/davehorner/cardinal/contents/roms";
    let client = Client::builder()
        .user_agent("cardinal-demo")
        .build()
        .map_err(|e| e.to_string())?;
    let resp = client
        .get(url)
        .send()
        .map_err(|e| e.to_string())?
        .json::<serde_json::Value>()
        .map_err(|e| e.to_string())?;
    let mut roms = Vec::new();
    if let Some(arr) = resp.as_array() {
        for entry in arr {
            if let Some(name) = entry.get("name").and_then(|n| n.as_str()) {
                if name.ends_with(".rom") {
                    roms.push(name.to_string());
                }
            }
        }
    }
    Ok(roms)
}

/// Prompt the user to select a ROM (simple CLI prompt)
fn prompt_rom_selection(roms: &[String]) -> Result<String, String> {
    println!("Available ROMs: (hit return for auto ROM cycling)");
    for (i, rom) in roms.iter().enumerate() {
        println!("  [{}] {}", i + 1, rom);
    }
    println!(
        "  [Return] Enable AUTO ROM CYCLING mode (cycle all ROMs every 10s)"
    );
    print!("Select a ROM by number, or hit return for auto cycling: ");
    let _ = std::io::stdout().flush();
    let mut input = String::new();
    let _ = std::io::stdin().read_line(&mut input);
    let trimmed = input.trim();
    if trimmed.is_empty() {
        println!(
            "[AUTO ROM CYCLING] You selected auto mode. All ROMs will cycle every 10 seconds."
        );
        return Ok("__AUTO__".to_string());
    }
    let idx: usize = trimmed.parse().unwrap_or(1);
    let idx = idx.saturating_sub(1).min(roms.len().saturating_sub(1));
    Ok(roms[idx].clone())
}

/// Download the selected ROM to a temp file and return its path
#[cfg(target_arch = "wasm32")]
fn download_rom(_rom_name: &str) -> Result<PathBuf, String> {
    Err("ROM download not supported on wasm32 targets.".to_string())
}
#[cfg(not(target_arch = "wasm32"))]
fn download_rom(rom_name: &str) -> Result<PathBuf, String> {
    let url = format!(
        "https://raw.githubusercontent.com/davehorner/cardinal/main/roms/{}",
        rom_name
    );

    let client = Client::builder()
        .user_agent("cardinal-demo")
        .build()
        .map_err(|e| e.to_string())?;
    let resp = client
        .get(Url::parse(&url).map_err(|e| e.to_string())?)
        .send()
        .map_err(|e| e.to_string())?;
    let bytes = resp.bytes().map_err(|e| e.to_string())?;
    let mut file = tempfile::NamedTempFile::new().map_err(|e| e.to_string())?;
    file.write_all(&bytes).map_err(|e| e.to_string())?;
    let path = file.into_temp_path().keep().map_err(|e| e.to_string())?;
    Ok(path)
}

/// Send an orca file to the VM console, simulating character entry with right/left/down arrows
fn send_orca_file_to_console(
    dev: &mut varvara::Varvara,
    vm: &mut uxn::Uxn,
    file_path: &str,
) -> Result<(), String> {
    use std::fs::File;
    use std::io::{BufRead, BufReader};
    // Key codes (may need adjustment for your VM)
    // const CTRL_H: u8 = 0x08; // Ctrl+H (backspace, often used for home)
    const RIGHT_ARROW: u8 = 0x1B; // Example: ESC for right arrow (replace with actual code)
    const LEFT_ARROW: u8 = 0x1A; // Example: SUB for left arrow (replace with actual code)
    const DOWN_ARROW: u8 = 0x0A; // LF for down arrow (replace with actual code)

    // Send Ctrl+H to start
    // dev.console(vm, CTRL_H);
    // println!("[DEBUG] Sent Ctrl+H to console");

    let file = File::open(file_path).map_err(|e| e.to_string())?;
    let reader = BufReader::new(file);

    for (_line_idx, line_res) in reader.lines().enumerate() {
        let line = line_res.map_err(|e| e.to_string())?;
        let mut arrow_count = 0;
        for (_col_idx, ch) in line.chars().enumerate() {
            let byte = ch as u8;
            dev.console(vm, byte);
            // println!("[DEBUG] Line {}, Col {}: Sent char '{}' (0x{:02X})", line_idx, col_idx, ch, byte);
            dev.console(vm, RIGHT_ARROW);
            // println!("[DEBUG] Sent RIGHT_ARROW after char");
            arrow_count += 1;
        }
        // After line, send LEFT_ARROW 'arrow_count' times to return to column 0
        for i in 0..arrow_count {
            dev.console(vm, LEFT_ARROW);
            // println!("[DEBUG] Sent LEFT_ARROW to return to column 0 ({} of {})", i+1, arrow_count);
        }
        // Send DOWN_ARROW to move to next line
        dev.console(vm, DOWN_ARROW);
        // println!("[DEBUG] Sent DOWN_ARROW to move to next line");
    }
    Ok(())
}
// ...removed UxnEguiApp, now using UxnApp from uxn.rs...

#[cfg(target_arch = "wasm32")]
fn main() {
    eprintln!("cardinal-demo does not support wasm32 targets.");
}