holodeck-simctl-tui 0.4.0

Terminal UI for holodeck-simctl, a companion for the iOS Simulator's simctl
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
use std::collections::HashMap;

use uuid::Uuid;

use holodeck_core::models::{Simulator, SimulatorState};

use super::app_state::{
    AppState, CreateWizard, CreateWizardStep, Modal, OpenUrlPrompt, PendingOperation, PrivacyWizard, PrivacyWizardStep,
};
use super::event::{AppEvent, ReducerOutput, SideEffect};
use super::key::{Key, is_printable};
use super::modal_reducer;
use super::palette_command::PaletteCommand;

pub fn reduce(state: &AppState, event: AppEvent) -> ReducerOutput {
    let mut next = state.clone();
    match event {
        AppEvent::Refreshed(sims) => {
            next.simulators = AppState::sort(sims);
            let visible_count = next.visible_simulators().len() as i64;
            if visible_count == 0 {
                next.selected_index = 0;
            } else if next.selected_index >= visible_count {
                next.selected_index = visible_count - 1;
            }
            next.main_scroll_offset = clamp_main_scroll(next.main_scroll_offset, &next);
            if let Some(referenced) = next.modal.as_ref().and_then(Modal::referenced_simulator)
                && !next.simulators.iter().any(|s| s.id == referenced)
            {
                next.modal = None;
            }
            let reconciled = reconcile_pending(&next.pending_operations, &next.simulators);
            if reconciled.len() != next.pending_operations.len() && reconciled.is_empty() {
                // Every tracked operation reached its target; the status
                // banner that announced it ('Booting A…', 'Shutting down
                // A…') would otherwise outlive the operation it described.
                next.status_message = None;
            }
            next.pending_operations = reconciled;
            next.last_error = None;
            ReducerOutput::new(next)
        }

        AppEvent::RefreshFailed(message) => {
            next.last_error = Some(message);
            ReducerOutput::new(next)
        }

        AppEvent::Resized { rows, cols } => {
            next.rows = rows;
            next.cols = cols;
            next.main_scroll_offset = clamp_main_scroll(next.main_scroll_offset, &next);
            ReducerOutput::new(next)
        }

        AppEvent::PollTick => {
            // Keep polling even while recording: `simctl list` is a
            // read-only, independent process from the recording child, and
            // skipping it left simulator/operation state stale for the
            // entire (potentially multi-minute) recording.
            ReducerOutput::with_effects(next, vec![SideEffect::Refresh])
        }

        AppEvent::Key(key) => handle_key(&next, key),

        AppEvent::OperationCompleted(id) => {
            // If reconcile_pending already dropped the entry on an earlier
            // Refreshed, the user has moved on (possibly issued another op)
            // and clobbering status_message here would wipe the newer op's
            // banner. Only respond to events for still-tracked operations.
            if next.pending_operations.remove(&id).is_none() {
                return ReducerOutput::new(next);
            }
            next.status_message = None;
            ReducerOutput::with_effects(next, vec![SideEffect::Refresh])
        }

        AppEvent::OperationFailed(id, message) => {
            if next.pending_operations.remove(&id).is_none() {
                // The op visibly succeeded as far as the user is concerned
                // (state reached target before the simctl process
                // returned). Don't paint a red error banner over a clean
                // outcome.
                return ReducerOutput::new(next);
            }
            next.status_message = None;
            next.last_error = Some(message);
            ReducerOutput::with_effects(next, vec![SideEffect::Refresh])
        }

        AppEvent::RecordingStarted(id, path) => {
            next.recording_device_id = Some(id);
            next.recording_path = Some(path);
            next.status_message = None;
            ReducerOutput::new(next)
        }

        AppEvent::RecordingStopped(path) => {
            next.recording_device_id = None;
            next.recording_path = None;
            next.status_message = path.map(|p| format!("Saved {}", p.display()));
            ReducerOutput::with_effects(next, vec![SideEffect::Refresh])
        }

        AppEvent::RecordingFailed(message) => {
            next.recording_device_id = None;
            next.recording_path = None;
            next.last_error = Some(message);
            ReducerOutput::new(next)
        }

        AppEvent::ScreenshotSaved(path) => {
            let file_name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
            next.status_message = Some(format!("Screenshot saved {file_name}"));
            ReducerOutput::new(next)
        }

        AppEvent::ScreenshotFailed(message) => {
            next.last_error = Some(message);
            ReducerOutput::new(next)
        }

        AppEvent::AppearanceChanged(_, appearance) => {
            next.status_message = Some(format!("Appearance set to {}", appearance.raw_value()));
            ReducerOutput::with_effects(next, vec![SideEffect::Refresh])
        }

        AppEvent::AppearanceFailed(message) => {
            next.last_error = Some(message);
            ReducerOutput::new(next)
        }

        AppEvent::TargetsLoaded { mut device_types, mut runtimes } => {
            if let Some(Modal::CreateWizard(wizard)) = &next.modal {
                let mut updated = wizard.clone();
                device_types.sort_by(|a, b| a.name.cmp(&b.name));
                runtimes.sort_by(|a, b| b.cmp(a));
                updated.device_types = device_types;
                updated.runtimes = runtimes;
                updated.step =
                    if updated.device_types.is_empty() { CreateWizardStep::Loading } else { CreateWizardStep::PickDeviceType };
                next.modal = Some(Modal::CreateWizard(updated));
            }
            ReducerOutput::new(next)
        }

        AppEvent::TargetsFailed(message) => {
            if let Some(Modal::CreateWizard(_)) = &next.modal {
                next.modal = None;
            }
            next.last_error = Some(message);
            ReducerOutput::new(next)
        }

        AppEvent::SimulatorCreated(_, name) => {
            next.modal = None;
            next.status_message = Some(format!("Created {name}"));
            ReducerOutput::with_effects(next, vec![SideEffect::Refresh])
        }

        AppEvent::SimulatorCreateFailed(message) => {
            if let Some(Modal::CreateWizard(wizard)) = &next.modal {
                let mut updated = wizard.clone();
                updated.step = CreateWizardStep::Confirm;
                updated.error = Some(message);
                next.modal = Some(Modal::CreateWizard(updated));
            } else {
                next.last_error = Some(message);
            }
            ReducerOutput::new(next)
        }

        AppEvent::AppsLoaded(apps) => {
            if let Some(Modal::PrivacyWizard(wizard)) = &next.modal {
                let mut updated = wizard.clone();
                updated.all_apps = apps;
                updated.app_index = 0;
                updated.step = PrivacyWizardStep::PickApp;
                updated.error = None;
                next.modal = Some(Modal::PrivacyWizard(updated));
            }
            ReducerOutput::new(next)
        }

        AppEvent::AppsLoadFailed(message) => {
            if let Some(Modal::PrivacyWizard(_)) = &next.modal {
                next.modal = None;
            }
            next.last_error = Some(message);
            ReducerOutput::new(next)
        }

        AppEvent::PrivacyApplied { bundle_id } => {
            next.modal = None;
            next.status_message = Some(format!("Privacy updated for {bundle_id}"));
            ReducerOutput::new(next)
        }

        AppEvent::PrivacyApplyFailed(message) => {
            if let Some(Modal::PrivacyWizard(wizard)) = &next.modal {
                let mut updated = wizard.clone();
                updated.step = PrivacyWizardStep::PickAction;
                updated.error = Some(message);
                next.modal = Some(Modal::PrivacyWizard(updated));
            } else {
                next.last_error = Some(message);
            }
            ReducerOutput::new(next)
        }

        AppEvent::UrlHistoryLoaded(history) => {
            next.url_history = history;
            ReducerOutput::new(next)
        }

        AppEvent::UrlOpened { url, history } => {
            // Update history regardless (the simctl call already
            // succeeded), but only surface the modal close + status message
            // if the user is still on the open-URL modal. Esc during
            // submission drops the modal first.
            next.url_history = history;
            if let Some(Modal::OpenUrl(_)) = &next.modal {
                next.modal = None;
                next.status_message = Some(format!("Opened {url}"));
            }
            ReducerOutput::new(next)
        }

        AppEvent::UrlOpenFailed(message) => {
            if let Some(Modal::OpenUrl(prompt)) = &next.modal {
                let mut updated = prompt.clone();
                updated.is_submitting = false;
                updated.error = Some(message);
                next.modal = Some(Modal::OpenUrl(updated));
            }
            ReducerOutput::new(next)
        }
    }
}

fn handle_key(state: &AppState, key: Key) -> ReducerOutput {
    if state.is_filter_focused {
        return handle_filter_key(state, key);
    }
    if state.modal.is_some() {
        return modal_reducer::handle(state, key);
    }
    let mut next = state.clone();
    let count = next.visible_simulators().len() as i64;
    match key {
        Key::Up | Key::Char('k') => {
            if count > 0 {
                next.selected_index = (next.selected_index - 1).max(0);
            }
            next.main_scroll_offset = AppState::scroll(next.main_scroll_offset, next.selected_index, next.main_list_viewport());
            ReducerOutput::new(next)
        }
        Key::Down | Key::Char('j') => {
            if count > 0 {
                next.selected_index = (next.selected_index + 1).min(count - 1);
            }
            next.main_scroll_offset = AppState::scroll(next.main_scroll_offset, next.selected_index, next.main_list_viewport());
            ReducerOutput::new(next)
        }
        Key::Char('/') => {
            next.is_filter_focused = true;
            next.filter_query.clear();
            next.selected_index = 0;
            next.main_scroll_offset = 0;
            ReducerOutput::new(next)
        }
        Key::Char(':') => {
            next.modal = Some(Modal::CommandPalette(super::app_state::CommandPalette {
                simulator_id: next.selected_simulator().map(|s| s.id),
                query: String::new(),
            }));
            ReducerOutput::new(next)
        }
        Key::Char('i') => run_command(PaletteCommand::Inspect, next),
        Key::Char('o') => run_command(PaletteCommand::Open, next),
        Key::Char('q') | Key::Escape => {
            if next.is_recording() {
                return ReducerOutput::with_effects(next, vec![SideEffect::StopRecording]);
            }
            next.is_quitting = true;
            ReducerOutput::new(next)
        }
        Key::Char('R') => {
            next.status_message = Some("Refreshing…".to_string());
            ReducerOutput::with_effects(next, vec![SideEffect::Refresh])
        }
        Key::Char('r') => {
            if next.recording_device_id.is_some() {
                next.status_message = Some("Stopping recording…".to_string());
                return ReducerOutput::with_effects(next, vec![SideEffect::StopRecording]);
            }
            run_command(PaletteCommand::Record, next)
        }
        Key::Char('p') => run_command(PaletteCommand::Screenshot, next),
        Key::Char('a') => run_command(PaletteCommand::Appearance, next),
        Key::Char('e') => run_command(PaletteCommand::Erase, next),
        Key::Char('d') => run_command(PaletteCommand::Delete, next),
        Key::Char('n') => run_command(PaletteCommand::New, next),
        Key::Char('f') => run_command(PaletteCommand::Focus, next),
        Key::Char('P') => run_command(PaletteCommand::Privacy, next),
        Key::Char('?') => {
            next.modal = Some(Modal::Help);
            ReducerOutput::new(next)
        }
        Key::Enter | Key::Char(' ') => toggle_selected(next),
        _ => ReducerOutput::new(next),
    }
}

fn handle_filter_key(state: &AppState, key: Key) -> ReducerOutput {
    let mut next = state.clone();
    match key {
        Key::Escape => {
            next.is_filter_focused = false;
            next.filter_query.clear();
            next.selected_index = 0;
            next.main_scroll_offset = 0;
        }
        Key::Enter => next.is_filter_focused = false,
        Key::Backspace => {
            if !next.filter_query.is_empty() {
                next.filter_query.pop();
            }
            next.selected_index = 0;
            next.main_scroll_offset = 0;
        }
        Key::Char(c) if is_printable(c) => {
            next.filter_query.push(c);
            next.selected_index = 0;
            next.main_scroll_offset = 0;
        }
        _ => {}
    }
    ReducerOutput::new(next)
}

/// Executes a palette command (or the equivalent keyboard shortcut).
/// Preconditions match `PaletteCommand::is_applicable`; when the precondition
/// fails this surfaces a transient status message instead of an effect.
pub fn run_command(command: PaletteCommand, state: AppState) -> ReducerOutput {
    let mut next = state;
    match command {
        PaletteCommand::New => {
            next.modal = Some(Modal::CreateWizard(CreateWizard::new()));
            ReducerOutput::with_effects(next, vec![SideEffect::LoadTargets])
        }

        PaletteCommand::Inspect => {
            let Some(sim) = next.selected_simulator() else {
                return ReducerOutput::new(next);
            };
            let id = sim.id;
            next.modal = Some(Modal::Inspector(id));
            ReducerOutput::new(next)
        }

        PaletteCommand::Focus => {
            let Some(sim) = next.selected_simulator().cloned() else {
                return ReducerOutput::new(next);
            };
            next.status_message = Some(format!("Focusing {}", sim.name));
            ReducerOutput::with_effects(next, vec![SideEffect::FocusSimulator(sim.id)])
        }

        PaletteCommand::Delete => {
            let Some(sim) = next.selected_simulator() else {
                return ReducerOutput::new(next);
            };
            let id = sim.id;
            next.modal = Some(Modal::ConfirmDelete(id));
            ReducerOutput::new(next)
        }

        PaletteCommand::Erase => {
            let Some(sim) = next.selected_simulator().cloned() else {
                return ReducerOutput::new(next);
            };
            if sim.state != SimulatorState::Shutdown {
                next.status_message = Some(format!("Cannot erase: {} is {}", sim.name, sim.state.raw_value()));
                return ReducerOutput::new(next);
            }
            next.modal = Some(Modal::ConfirmErase(sim.id));
            ReducerOutput::new(next)
        }

        PaletteCommand::Appearance => {
            let Some(sim) = next.selected_simulator().cloned() else {
                return ReducerOutput::new(next);
            };
            if sim.state != SimulatorState::Booted {
                next.status_message = Some(format!("Cannot set appearance: {} is {}", sim.name, sim.state.raw_value()));
                return ReducerOutput::new(next);
            }
            next.modal = Some(Modal::Appearance);
            ReducerOutput::new(next)
        }

        PaletteCommand::Screenshot => {
            let Some(sim) = next.selected_simulator().cloned() else {
                return ReducerOutput::new(next);
            };
            if sim.state != SimulatorState::Booted {
                next.status_message = Some(format!("Cannot capture: {} is {}", sim.name, sim.state.raw_value()));
                return ReducerOutput::new(next);
            }
            next.status_message = Some("Capturing screenshot…".to_string());
            ReducerOutput::with_effects(next, vec![SideEffect::CaptureScreenshot(sim.id)])
        }

        PaletteCommand::Record => {
            let Some(sim) = next.selected_simulator().cloned() else {
                return ReducerOutput::new(next);
            };
            if sim.state != SimulatorState::Booted {
                next.status_message = Some(format!("Cannot record: {} is {}", sim.name, sim.state.raw_value()));
                return ReducerOutput::new(next);
            }
            next.status_message = Some("Starting recording…".to_string());
            ReducerOutput::with_effects(next, vec![SideEffect::StartRecording(sim.id)])
        }

        PaletteCommand::Open => {
            let Some(sim) = next.selected_simulator().cloned() else {
                return ReducerOutput::new(next);
            };
            if sim.state != SimulatorState::Booted {
                next.status_message = Some(format!("Cannot open URL: {} is {}", sim.name, sim.state.raw_value()));
                return ReducerOutput::new(next);
            }
            next.modal = Some(Modal::OpenUrl(OpenUrlPrompt::new(sim.id)));
            ReducerOutput::new(next)
        }

        PaletteCommand::Privacy => {
            let Some(sim) = next.selected_simulator().cloned() else {
                return ReducerOutput::new(next);
            };
            if sim.state != SimulatorState::Booted {
                next.status_message = Some(format!("Cannot inspect apps: {} is {}", sim.name, sim.state.raw_value()));
                return ReducerOutput::new(next);
            }
            next.modal = Some(Modal::PrivacyWizard(PrivacyWizard::new(sim.id)));
            ReducerOutput::with_effects(next, vec![SideEffect::LoadInstalledApps(sim.id)])
        }

        PaletteCommand::Boot => {
            let Some(sim) = next.selected_simulator().cloned() else {
                return ReducerOutput::new(next);
            };
            if next.pending_operations.contains_key(&sim.id) {
                next.status_message = Some(format!("{} has a pending operation", sim.name));
                return ReducerOutput::new(next);
            }
            if sim.state != SimulatorState::Shutdown {
                next.status_message = Some(format!("Cannot boot: {} is {}", sim.name, sim.state.raw_value()));
                return ReducerOutput::new(next);
            }
            next.pending_operations.insert(sim.id, PendingOperation::Boot);
            next.status_message = Some(format!("Booting {}", sim.name));
            ReducerOutput::with_effects(next, vec![SideEffect::Boot(sim.id)])
        }

        PaletteCommand::Shutdown => {
            let Some(sim) = next.selected_simulator().cloned() else {
                return ReducerOutput::new(next);
            };
            if next.pending_operations.contains_key(&sim.id) {
                next.status_message = Some(format!("{} has a pending operation", sim.name));
                return ReducerOutput::new(next);
            }
            if sim.state != SimulatorState::Booted {
                next.status_message = Some(format!("Cannot shut down: {} is {}", sim.name, sim.state.raw_value()));
                return ReducerOutput::new(next);
            }
            next.pending_operations.insert(sim.id, PendingOperation::Shutdown);
            next.status_message = Some(format!("Shutting down {}", sim.name));
            ReducerOutput::with_effects(next, vec![SideEffect::Shutdown(sim.id)])
        }
    }
}

fn toggle_selected(state: AppState) -> ReducerOutput {
    let mut next = state;
    let Some(sim) = next.selected_simulator().cloned() else {
        return ReducerOutput::new(next);
    };
    if next.pending_operations.contains_key(&sim.id) {
        return ReducerOutput::new(next);
    }
    match sim.state {
        SimulatorState::Booted => {
            next.pending_operations.insert(sim.id, PendingOperation::Shutdown);
            next.status_message = Some(format!("Shutting down {}", sim.name));
            ReducerOutput::with_effects(next, vec![SideEffect::Shutdown(sim.id)])
        }
        SimulatorState::Shutdown => {
            next.pending_operations.insert(sim.id, PendingOperation::Boot);
            next.status_message = Some(format!("Booting {}", sim.name));
            ReducerOutput::with_effects(next, vec![SideEffect::Boot(sim.id)])
        }
        other => {
            next.status_message = Some(format!("{} is {}", sim.name, other.raw_value()));
            ReducerOutput::new(next)
        }
    }
}

/// Drops pending operations that have already reached their target state.
/// Erase/delete entries are kept until the spawned task posts
/// `OperationCompleted` because `simctl erase` does not change the sim's
/// observable state.
fn reconcile_pending(pending: &HashMap<Uuid, PendingOperation>, simulators: &[Simulator]) -> HashMap<Uuid, PendingOperation> {
    let by_id: HashMap<Uuid, &Simulator> = simulators.iter().map(|s| (s.id, s)).collect();
    pending
        .iter()
        .filter(|(id, operation)| match operation {
            PendingOperation::Delete | PendingOperation::Erase => by_id.contains_key(*id),
            PendingOperation::Boot => by_id.get(*id).is_some_and(|s| s.state != SimulatorState::Booted),
            PendingOperation::Shutdown => by_id.get(*id).is_some_and(|s| s.state != SimulatorState::Shutdown),
        })
        .map(|(id, op)| (*id, *op))
        .collect()
}

fn clamp_main_scroll(offset: i64, state: &AppState) -> i64 {
    let count = state.visible_simulators().len() as i64;
    if count == 0 {
        return 0;
    }
    let max_offset = (count - state.main_list_viewport()).max(0);
    offset.clamp(0, max_offset)
}