nebulus 0.1.30

Low-latency native OpenIPC FPV ground station built with egui
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
use eframe::egui;
use openipc_core::channel::DEFAULT_LINK_ID;

use crate::{
    app::NebulusApp,
    model::ReceiverState,
    settings::{ReceiverSource, DEFAULT_CHANNEL, DEFAULT_CHANNEL_OFFSET, MAX_LINK_ID},
};

use super::SettingsPage;

pub(crate) fn show(app: &mut NebulusApp, ui: &mut egui::Ui) {
    match app.settings_page {
        SettingsPage::Receiver => receiver_page(app, ui),
        SettingsPage::Media => media_page(app, ui),
        SettingsPage::Profiles => profiles_page(app, ui),
        SettingsPage::Network => network_page(app, ui),
    }
}

fn receiver_page(app: &mut NebulusApp, ui: &mut egui::Ui) {
    if app.receiver_info.is_some() {
        connected_receiver(app, ui);
    }
    let editable = matches!(app.state, ReceiverState::Idle | ReceiverState::Failed);
    ui.add_enabled_ui(editable, |ui| {
        section(ui, "Receiver", |ui| {
            receiver_source_selector(app, ui);
            match app.settings.receiver_source {
                ReceiverSource::Usb => usb_receiver_settings(app, ui),
                ReceiverSource::UdpRtp => udp_receiver_settings(app, ui),
            }
            ui.horizontal(|ui| {
                if ui.button("Run preflight").clicked() {
                    app.run_preflight();
                }
                if app.settings.receiver_source == ReceiverSource::Usb
                    && ui.button("Scan channels").clicked()
                {
                    app.show_channel_scanner = true;
                }
            });
        });

        if app.settings.receiver_source == ReceiverSource::Usb {
            section(ui, "Radio", |ui| {
                radio_settings(app, ui);
            });
        }

        section(ui, "Link", |ui| {
            ui.checkbox(
                &mut app.settings.auto_recover,
                "Automatically recover a dropped receiver",
            );
            if app.settings.receiver_source == ReceiverSource::Usb {
                ui.checkbox(&mut app.settings.adaptive_link, "Adaptive link feedback");
            } else {
                ui.label(
                    egui::RichText::new(
                        "UDP input uses the RTP sequence number for optional reordering; WFB adaptive feedback is not applicable.",
                    )
                    .small()
                    .color(ui.visuals().weak_text_color()),
                );
            }
            if cfg!(target_arch = "wasm32") {
                ui.label(
                    egui::RichText::new(
                        "Browser reconnects require a user gesture; automatic retries run in native builds.",
                    )
                    .small()
                    .color(ui.visuals().weak_text_color()),
                );
            }
            if app.recovery.active {
                ui.horizontal_wrapped(|ui| {
                    let remaining = app
                        .recovery
                        .scheduled_at
                        .map_or(0.0, |at| {
                            at.saturating_duration_since(web_time::Instant::now())
                                .as_secs_f32()
                        });
                    ui.colored_label(
                        ui.visuals().warn_fg_color,
                        format!(
                            "Recovery attempt {} in {:.1}s",
                            app.recovery.attempt, remaining
                        ),
                    );
                    if ui.small_button("Cancel").clicked() {
                        app.cancel_recovery();
                    }
                });
            }
            if app.settings.receiver_source == ReceiverSource::Usb && app.settings.adaptive_link {
                ui.horizontal(|ui| {
                    ui.label("Uplink TX power");
                    ui.add(egui::Slider::new(&mut app.settings.tx_power, 0..=127));
                });
            }
        });

        if app.settings.receiver_source == ReceiverSource::Usb {
            section(ui, "Receiver key", |ui| {
            ui.horizontal(|ui| {
                if ui.button("Open file").clicked() {
                    app.open_key_file(ui.ctx());
                }
                if ui.button("Use default").clicked() {
                    app.reset_key();
                }
            });
            ui.horizontal(|ui| {
                ui.label(&app.key_name);
                ui.label(
                    egui::RichText::new(format!("{} bytes", app.settings.key_bytes.len()))
                        .small()
                        .color(ui.visuals().weak_text_color()),
                );
            });
            if let Some(error) = &app.key_error {
                ui.colored_label(ui.visuals().error_fg_color, error);
            } else {
                ui.label(
                    egui::RichText::new("You can also drop a gs.key file anywhere on the window")
                        .small()
                        .color(ui.visuals().weak_text_color()),
                );
            }
            });
        }
    });
}

fn media_page(app: &mut NebulusApp, ui: &mut egui::Ui) {
    let editable = matches!(app.state, ReceiverState::Idle | ReceiverState::Failed);
    ui.add_enabled_ui(editable, |ui| {
        section(ui, "Video", |ui| {
            ui.horizontal(|ui| {
                ui.label("Codec preference");
                egui::ComboBox::from_id_salt("codec-preference")
                    .selected_text(app.settings.codec_preference.label())
                    .show_ui(ui, |ui| {
                        for preference in [
                            crate::settings::CodecPreference::Auto,
                            crate::settings::CodecPreference::H264,
                            crate::settings::CodecPreference::H265,
                        ] {
                            ui.selectable_value(
                                &mut app.settings.codec_preference,
                                preference,
                                preference.label(),
                            );
                        }
                    });
            });
            ui.checkbox(&mut app.settings.rtp_reorder, "RTP reorder buffer");
            egui::Grid::new("decoder-settings")
                .num_columns(2)
                .spacing([18.0, 7.0])
                .show(ui, |ui| {
                    ui.label("Decoder queue");
                    ui.label("3 frames, latest-frame output");
                    ui.end_row();
                });
        });
        section(ui, "Recording", |ui| recording_settings(app, ui));
    });
}

fn profiles_page(app: &mut NebulusApp, ui: &mut egui::Ui) {
    let editable = matches!(app.state, ReceiverState::Idle | ReceiverState::Failed);
    ui.add_enabled_ui(editable, |ui| {
        section(ui, "Receiver profiles", |ui| profile_editor(app, ui));
        section(ui, "Preset packs", |ui| super::presets::section(app, ui));
    });
}

fn network_page(app: &mut NebulusApp, ui: &mut egui::Ui) {
    section(ui, "VPN / tunnel", |ui| {
        if app.settings.receiver_source == ReceiverSource::Usb {
            super::vpn(app, ui);
        } else {
            ui.label(
                egui::RichText::new(
                    "VPN/TUN requires the bidirectional WFB radio transport and is unavailable for direct UDP RTP input.",
                )
                .small()
                .color(ui.visuals().weak_text_color()),
            );
        }
    });

    if app.settings.receiver_source == ReceiverSource::Usb {
        let editable = matches!(app.state, ReceiverState::Idle | ReceiverState::Failed);
        ui.add_enabled_ui(editable, |ui| {
            section(ui, "USB transport", |ui| {
                egui::Grid::new("advanced-settings")
                    .num_columns(2)
                    .spacing([18.0, 7.0])
                    .show(ui, |ui| {
                        ui.label("Minimum epoch");
                        ui.add(egui::DragValue::new(&mut app.settings.minimum_epoch));
                        ui.end_row();
                        ui.label("Transfer size");
                        ui.add(
                            egui::DragValue::new(&mut app.settings.transfer_size)
                                .range(4_096..=1_048_576),
                        );
                        ui.end_row();
                    });
            });
        });
    }
}

fn radio_settings(app: &mut NebulusApp, ui: &mut egui::Ui) {
    egui::Grid::new("radio-settings")
        .num_columns(3)
        .spacing([18.0, 8.0])
        .show(ui, |ui| {
            ui.label("Channel");
            ui.add(
                egui::Slider::new(&mut app.settings.channel, 1..=177)
                    .show_value(true)
                    .text(""),
            );
            if ui.small_button("Default").clicked() {
                app.settings.channel = DEFAULT_CHANNEL;
            }
            ui.end_row();
            ui.label("Width");
            egui::ComboBox::from_id_salt("channel-width")
                .selected_text(format!("{} MHz", app.settings.channel_width_mhz))
                .show_ui(ui, |ui| {
                    for width in [5, 10, 20, 40, 80] {
                        ui.selectable_value(
                            &mut app.settings.channel_width_mhz,
                            width,
                            format!("{width} MHz"),
                        );
                    }
                });
            ui.label("");
            ui.end_row();
            ui.label("Offset");
            ui.add(
                egui::Slider::new(&mut app.settings.channel_offset, 0..=4)
                    .show_value(true)
                    .text(""),
            );
            if ui.small_button("Default").clicked() {
                app.settings.channel_offset = DEFAULT_CHANNEL_OFFSET;
            }
            ui.end_row();
            ui.label("Link ID");
            ui.add(
                egui::Slider::new(&mut app.settings.link_id, 0..=MAX_LINK_ID)
                    .show_value(true)
                    .custom_formatter(|value, _| format!("0x{:06X}", value as u32))
                    .custom_parser(parse_link_id),
            );
            if ui.small_button("Default").clicked() {
                app.settings.link_id = DEFAULT_LINK_ID;
            }
            ui.end_row();
        });
}

fn receiver_source_selector(app: &mut NebulusApp, ui: &mut egui::Ui) {
    #[cfg(not(target_arch = "wasm32"))]
    ui.horizontal(|ui| {
        ui.label("Source");
        ui.selectable_value(
            &mut app.settings.receiver_source,
            ReceiverSource::Usb,
            ReceiverSource::Usb.label(),
        );
        ui.selectable_value(
            &mut app.settings.receiver_source,
            ReceiverSource::UdpRtp,
            ReceiverSource::UdpRtp.label(),
        );
    });

    #[cfg(target_arch = "wasm32")]
    {
        app.settings.receiver_source = ReceiverSource::Usb;
        ui.horizontal(|ui| {
            ui.label("Source");
            ui.strong("WebUSB");
        });
    }
}

fn usb_receiver_settings(app: &mut NebulusApp, ui: &mut egui::Ui) {
    ui.label(
        egui::RichText::new("Primary receiver and uplink")
            .small()
            .color(ui.visuals().weak_text_color()),
    );
    ui.horizontal(|ui| {
        egui::ComboBox::from_id_salt("usb-device")
            .selected_text(selected_device_label(app))
            .width(230.0)
            .show_ui(ui, |ui| {
                for device in &app.devices {
                    let changed = ui
                        .selectable_value(
                            &mut app.settings.device_id,
                            Some(device.id.clone()),
                            format!("{}{}", device.label, device.location),
                        )
                        .changed();
                    if changed {
                        app.settings
                            .diversity_device_ids
                            .retain(|id| Some(id) != app.settings.device_id.as_ref());
                    }
                }
            });
        if ui.button("Refresh").clicked() {
            app.refresh_devices();
        }
        #[cfg(target_arch = "wasm32")]
        if ui.button("Add adapter").clicked() {
            app.authorize_webusb_adapter();
        }
    });
    if app.devices.is_empty() {
        ui.label(
            egui::RichText::new("No supported USB adapter found")
                .small()
                .color(ui.visuals().weak_text_color()),
        );
    }
    if app.devices.len() > 1 {
        ui.add_space(6.0);
        ui.label(
            egui::RichText::new("Diversity receivers")
                .small()
                .color(ui.visuals().weak_text_color()),
        );
        for device in &app.devices {
            if app.settings.device_id.as_deref() == Some(device.id.as_str()) {
                continue;
            }
            let mut selected = app
                .settings
                .diversity_device_ids
                .iter()
                .any(|id| id == &device.id);
            if ui
                .checkbox(
                    &mut selected,
                    format!("{}{}", device.label, device.location),
                )
                .changed()
            {
                if selected {
                    app.settings.diversity_device_ids.push(device.id.clone());
                } else {
                    app.settings
                        .diversity_device_ids
                        .retain(|id| id != &device.id);
                }
                app.settings.normalize();
            }
        }
        ui.label(
            egui::RichText::new(format!(
                "{} adapters selected; first valid WFB packet wins",
                app.settings.selected_device_ids().len()
            ))
            .small()
            .color(ui.visuals().weak_text_color()),
        );
    }
}

fn udp_receiver_settings(_app: &mut NebulusApp, ui: &mut egui::Ui) {
    #[cfg(not(target_arch = "wasm32"))]
    {
        egui::Grid::new("udp-rtp-listener")
            .num_columns(3)
            .spacing([12.0, 7.0])
            .show(ui, |ui| {
                ui.label("Bind address");
                ui.add(
                    egui::TextEdit::singleline(&mut _app.settings.udp_bind_address)
                        .desired_width(150.0)
                        .char_limit(64),
                );
                if ui.small_button("Default").clicked() {
                    _app.settings.udp_bind_address = "0.0.0.0".to_owned();
                }
                ui.end_row();

                ui.label("Port");
                ui.add(egui::DragValue::new(&mut _app.settings.udp_bind_port).range(1..=65_535));
                if ui.small_button("Default").clicked() {
                    _app.settings.udp_bind_port = crate::settings::DEFAULT_UDP_RTP_PORT;
                }
                ui.end_row();
            });
        ui.label(
            egui::RichText::new(
                "Listens for one RTP packet per UDP datagram. H.264/H.265, mixed Opus audio, recording, and payload routes use the normal receive pipeline.",
            )
            .small()
            .color(ui.visuals().weak_text_color()),
        );
    }

    #[cfg(target_arch = "wasm32")]
    ui.label(
        egui::RichText::new("Direct UDP sockets are unavailable in browsers")
            .small()
            .color(ui.visuals().warn_fg_color),
    );
}

fn recording_settings(_app: &mut NebulusApp, ui: &mut egui::Ui) {
    #[cfg(all(not(target_arch = "wasm32"), not(target_os = "android")))]
    {
        ui.label("Recording folder");
        ui.add(
            egui::Label::new(egui::RichText::new(_app.recording_directory_display()).monospace())
                .wrap(),
        );
        ui.horizontal(|ui| {
            if ui.button("Choose folder").clicked() {
                _app.choose_recording_directory();
            }
            if ui.button("Use default").clicked() {
                _app.reset_recording_directory();
            }
        });
        ui.label(
            egui::RichText::new(
                "Record creates a unique MP4 here immediately; it never opens a save dialog.",
            )
            .small()
            .color(ui.visuals().weak_text_color()),
        );
    }

    #[cfg(target_os = "android")]
    ui.label(
        egui::RichText::new(
            "Recordings are written to Nebulus app storage without opening a document picker.",
        )
        .small()
        .color(ui.visuals().weak_text_color()),
    );

    #[cfg(target_arch = "wasm32")]
    ui.label(
        egui::RichText::new(
            "The browser buffers the MP4 and starts a download when recording stops. The browser controls the download folder.",
        )
        .small()
        .color(ui.visuals().weak_text_color()),
    );
}

fn profile_editor(app: &mut NebulusApp, ui: &mut egui::Ui) {
    let active_id = app
        .settings
        .active_profile_id
        .or_else(|| app.settings.profiles.first().map(|profile| profile.id));
    let selected_name = active_id
        .and_then(|id| {
            app.settings
                .profiles
                .iter()
                .find(|profile| profile.id == id)
        })
        .map(|profile| profile.name.clone())
        .unwrap_or_else(|| "No profile".to_owned());
    let mut selected = active_id;
    ui.horizontal(|ui| {
        egui::ComboBox::from_id_salt("receiver-profile")
            .selected_text(selected_name)
            .width(180.0)
            .show_ui(ui, |ui| {
                for profile in &app.settings.profiles {
                    ui.selectable_value(&mut selected, Some(profile.id), &profile.name);
                }
            });
        if selected != active_id {
            if let Some(id) = selected {
                app.apply_profile(id);
            }
        }
        if ui.button("New").clicked() {
            app.create_profile();
        }
    });
    if let Some(id) = app.settings.active_profile_id {
        if let Some(profile) = app
            .settings
            .profiles
            .iter_mut()
            .find(|profile| profile.id == id)
        {
            ui.horizontal(|ui| {
                ui.label("Name");
                ui.add(
                    egui::TextEdit::singleline(&mut profile.name)
                        .desired_width(180.0)
                        .char_limit(48),
                );
            });
        }
    }
    let active_osd = app.settings.active_osd_profile_id;
    let selected_osd_name = active_osd
        .and_then(|id| {
            app.settings
                .osd_profiles
                .iter()
                .find(|profile| profile.id == id)
        })
        .map_or("No OSD", |profile| profile.name.as_str());
    let mut selected_osd = active_osd;
    ui.horizontal(|ui| {
        ui.label("OSD");
        egui::ComboBox::from_id_salt("receiver-profile-osd")
            .selected_text(selected_osd_name)
            .width(180.0)
            .show_ui(ui, |ui| {
                for profile in &app.settings.osd_profiles {
                    ui.selectable_value(&mut selected_osd, Some(profile.id), &profile.name);
                }
            });
    });
    if selected_osd != active_osd {
        if let Some(osd_id) = selected_osd {
            app.apply_osd_profile(osd_id);
            if let Some(profile_id) = app.settings.active_profile_id {
                if let Some(profile) = app
                    .settings
                    .profiles
                    .iter_mut()
                    .find(|profile| profile.id == profile_id)
                {
                    profile.osd_profile_id = Some(osd_id);
                }
            }
        }
    }
    ui.horizontal(|ui| {
        if ui.button("Save current").clicked() {
            app.save_active_profile();
        }
        if ui
            .add_enabled(app.settings.profiles.len() > 1, egui::Button::new("Delete"))
            .clicked()
        {
            app.delete_active_profile();
        }
    });
    ui.label(
        egui::RichText::new(
            "Profiles include receiver hardware, radio, keys, routes, telemetry, audio, VPN, decoder settings, and a reference to a reusable OSD profile.",
        )
        .small()
        .color(ui.visuals().weak_text_color()),
    );
}

fn connected_receiver(app: &NebulusApp, ui: &mut egui::Ui) {
    section(ui, "Connected receivers", |ui| {
        for receiver in &app.receiver_infos {
            let source_label = if receiver.transport == crate::runtime::ReceiverTransport::Usb {
                "Radio"
            } else {
                "Input"
            };
            ui.strong(format!(
                "{source_label} {} · {}",
                receiver.source_id + 1,
                receiver.label
            ));
            egui::Grid::new(("connected-receiver-info", receiver.source_id))
                .num_columns(2)
                .striped(true)
                .spacing([18.0, 7.0])
                .show(ui, |ui| {
                    receiver_row(ui, "Adapter", &receiver.label);
                    match receiver.transport {
                        crate::runtime::ReceiverTransport::Usb => {
                            receiver_row(ui, "Device", &receiver.id);
                            receiver_row(
                                ui,
                                "USB ID",
                                &match (receiver.vendor_id, receiver.product_id) {
                                    (Some(vendor), Some(product)) => {
                                        format!("{vendor:04x}:{product:04x}")
                                    }
                                    _ => "Not applicable".to_owned(),
                                },
                            );
                            receiver_row(ui, "Chipset", &receiver.chip);
                            receiver_row(ui, "RF paths", &receiver.rf_paths);
                            receiver_row(
                                ui,
                                "Cut revision",
                                &receiver.cut_version.map_or_else(
                                    || "Not reported".to_owned(),
                                    |cut| cut.to_string(),
                                ),
                            );
                            receiver_row(ui, "USB link", &receiver.usb_speed);
                            receiver_row(
                                ui,
                                "Bulk endpoints",
                                &match (receiver.bulk_in_endpoint, receiver.bulk_out_endpoint) {
                                    (Some(input), Some(output)) => {
                                        format!("IN 0x{input:02x} / OUT 0x{output:02x}")
                                    }
                                    _ => "Not applicable".to_owned(),
                                },
                            );
                        }
                        crate::runtime::ReceiverTransport::UdpRtp => {
                            receiver_row(ui, "Listen address", &receiver.id);
                            receiver_row(ui, "Transport", "UDP / RTP");
                            receiver_row(ui, "Processing", "Direct RTP depacketization");
                        }
                        crate::runtime::ReceiverTransport::Synthetic => {
                            receiver_row(ui, "Source", &receiver.id);
                            receiver_row(ui, "Transport", "Synthetic RTP");
                            receiver_row(ui, "Processing", &receiver.chip);
                        }
                    }
                    receiver_row(ui, "Initialization", &receiver.initialization);
                    if receiver.transport == crate::runtime::ReceiverTransport::Usb {
                        receiver_row(
                            ui,
                            "Firmware downloaded",
                            match receiver.firmware_downloaded {
                                Some(true) => "Yes",
                                Some(false) => "No",
                                None => "Not applicable",
                            },
                        );
                    }
                    receiver_row(
                        ui,
                        "Role",
                        if receiver.transport != crate::runtime::ReceiverTransport::Usb {
                            "Video/audio receive"
                        } else if receiver.source_id == 0 {
                            "Primary RX and uplink"
                        } else {
                            "Diversity RX"
                        },
                    );
                });
            ui.add_space(8.0);
        }
        if app.settings.receiver_source == ReceiverSource::Usb {
            egui::Grid::new("connected-radio-config")
                .num_columns(2)
                .striped(true)
                .spacing([18.0, 7.0])
                .show(ui, |ui| {
                    receiver_row(
                        ui,
                        "RF configuration",
                        &format!(
                            "channel {} / {} MHz / offset {}",
                            app.settings.channel,
                            app.settings.channel_width_mhz,
                            app.settings.channel_offset
                        ),
                    );
                    receiver_row(
                        ui,
                        "Video channel",
                        &format!(
                            "Link 0x{:06x} / port 0x{:02x}",
                            app.settings.link_id,
                            openipc_core::RadioPort::Video.as_u8()
                        ),
                    );
                });
        }
    });
}

fn receiver_row(ui: &mut egui::Ui, label: &str, value: &str) {
    ui.label(egui::RichText::new(label).color(ui.visuals().weak_text_color()));
    ui.monospace(value);
    ui.end_row();
}

fn parse_link_id(value: &str) -> Option<f64> {
    let value = value.trim();
    let parsed = value
        .strip_prefix("0x")
        .or_else(|| value.strip_prefix("0X"))
        .map_or_else(
            || value.parse::<u32>().ok(),
            |hex| u32::from_str_radix(hex, 16).ok(),
        )?;
    (parsed <= MAX_LINK_ID).then_some(f64::from(parsed))
}

fn selected_device_label(app: &NebulusApp) -> String {
    app.settings
        .device_id
        .as_deref()
        .and_then(|id| app.devices.iter().find(|device| device.id == id))
        .map(|device| format!("{}{}", device.label, device.location))
        .or_else(|| app.settings.device_id.clone())
        .unwrap_or_else(|| "Select an adapter".to_owned())
}

fn section(ui: &mut egui::Ui, title: &str, add: impl FnOnce(&mut egui::Ui)) {
    egui::CollapsingHeader::new(title)
        .default_open(true)
        .show(ui, |ui| {
            ui.add_space(4.0);
            add(ui);
            ui.add_space(8.0);
        });
}

#[cfg(test)]
mod tests {
    use super::parse_link_id;

    #[test]
    fn link_id_parser_accepts_decimal_and_hex() {
        assert_eq!(parse_link_id("7669206"), Some(7_669_206.0));
        assert_eq!(parse_link_id("0x7505D6"), Some(7_669_206.0));
    }

    #[test]
    fn link_id_parser_rejects_values_above_24_bits() {
        assert_eq!(parse_link_id("0x1000000"), None);
    }
}