runandlog 0.7.0

CLI / TUI that runs the shell commands in a Markdown file and writes the results back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
//! Desktop app (GUI).
//!
//! The window shows the same document the TUI shows: the file path, then every
//! cell with its command, a Run button, and the result of the last run. Parsing,
//! running and writing back all go through [`Session`], which is the same path
//! the TUI and non-interactive runs take. Nothing about the Markdown format is
//! re-implemented here, so the rules cannot drift apart.
//!
//! Design notes:
//!
//! - **A run happens on a blocking worker, never on a Tauri command thread.**
//!   `runandlog_core::run` blocks until the command finishes; running it inline
//!   would freeze the window for as long as the command takes.
//! - **The session is only locked around the short synchronous parts.** The lock
//!   is never held across an `await`, so a long run does not block the commands
//!   that read the document.
//! - **Only one run is in flight at a time** (`busy`). Cells share one file, and
//!   two concurrent write-backs would each see the other's edit as an external
//!   modification and refuse to write.
//! - **The whole document is re-sent after every write.** Writing back re-parses
//!   the file, so byte offsets and result blocks change; sending a diff would
//!   mean tracking that in two places.

use std::collections::HashMap;
use std::io;
use std::path::Path;
use std::sync::{Mutex, PoisonError, mpsc};

use serde::Serialize;
use tauri::{AppHandle, Emitter, Manager, State};

use runandlog_core::Canceller;

use crate::session::Session;

/// Event carrying the current document. Sent whenever the file is re-read.
const EVENT_DOCUMENT: &str = "runandlog://document";
/// Event marking the start of a run.
const EVENT_STARTED: &str = "runandlog://started";
/// Event carrying a piece of a running command's output.
const EVENT_OUTPUT: &str = "runandlog://output";
/// Event marking the end of a run, successful or not.
const EVENT_FINISHED: &str = "runandlog://finished";
/// Event carrying a command's request for a password. Answered with
/// [`answer_password`].
const EVENT_PASSWORD: &str = "runandlog://password";

/// How much of one piece of output is sent to the window at a time.
///
/// A command can print faster than anything can be read, and the window only shows
/// the tail of what it has been sent. Sending megabytes through the IPC for a view
/// that drops all but the end of it is work with nothing to show for it, so an
/// overlong piece is cut to its end. Nothing is lost by it: the whole output is
/// written back to the Markdown when the command finishes.
const MAX_OUTPUT_CHUNK_BYTES: usize = 64 * 1024;

/// Id of the "Third-Party Licenses" menu item, and label of the window it opens.
const LICENSES: &str = "licenses";

/// A cell as the window shows it.
#[derive(Debug, Clone, Serialize)]
struct CellView {
    /// Zero-based index, used to ask for a run.
    index: usize,
    /// One-based number, as shown.
    number: usize,
    lang: String,
    command: String,
    /// Destination file for the result, when the cell designates one.
    out_file: Option<String>,
    /// Body of the result block from the last run, without the markers.
    result: Option<String>,
}

/// The document as the window shows it.
#[derive(Debug, Clone, Serialize)]
struct DocumentView {
    path: String,
    cells: Vec<CellView>,
}

/// A piece of what a running command has printed.
///
/// Carries the cell it belongs to: a piece that arrives after the window has moved
/// on -- the last of a run whose result is already drawn, say -- must not be shown
/// under whatever cell is running now.
#[derive(Debug, Clone, Serialize)]
struct OutputChunk {
    index: usize,
    text: String,
}

/// How a run ended, for the status line.
#[derive(Debug, Clone, Serialize)]
struct RunReport {
    index: usize,
    /// `exit 0`, `timeout`, and so on.
    status: String,
    success: bool,
    /// Whether the run was stopped from the window. A batch stops here.
    cancelled: bool,
}

/// A command asking for a password, as the window shows it.
#[derive(Debug, Clone, Serialize)]
struct PasswordRequest {
    /// What the answer is sent back under.
    id: u64,
    /// What the command asked, word for word.
    prompt: String,
}

/// Password requests waiting for the window to answer.
///
/// Whether a request may be taken at all lives under the same lock as the requests
/// themselves. Checked apart, a command could end -- and its requests be declined --
/// between the check and the registration, leaving a prompt for a run that is over.
#[derive(Default)]
struct Passwords {
    /// Whether the window has subscribed to the requests. Until it has, nobody would
    /// see one, and the command would wait on an answer that cannot come.
    window_listens: bool,
    /// Whether a command is running right now. Not the same as `busy`, which also
    /// covers the write-back and the gaps between the cells of a batch.
    accepting: bool,
    next: u64,
    pending: HashMap<u64, mpsc::Sender<Option<String>>>,
}

/// How a "run all" ended.
///
/// `stopped` is carried separately because a batch can end on a Stop that landed
/// between two cells, where there is no cancelled run to read it from.
#[derive(Debug, Clone, Serialize)]
struct BatchReport {
    reports: Vec<RunReport>,
    stopped: bool,
}

/// The operation in flight, if any, and what has been asked of it.
///
/// All three live under one lock rather than as separate atomics: they describe a
/// single thing, and a Stop has to be decided against the operation it was pressed
/// during. Read apart, "is anything running", "remember the stop" and "cancel the
/// command" can interleave with an operation ending and the next one starting, and
/// the stop then lands on a command the user never asked to stop.
#[derive(Default)]
struct Operation {
    /// Whether a run or a reload is in flight.
    busy: bool,
    /// Whether Stop was pressed during it.
    ///
    /// A canceller exists only while a command is actually running, and a batch
    /// spends real time between cells writing the previous result back. Without this
    /// a Stop landing in that gap would reach nothing and be forgotten, leaving the
    /// batch running after the window said it had stopped.
    stop_requested: bool,
    /// Handle for the command running right now.
    canceller: Option<Canceller>,
}

/// Shared state behind the Tauri commands.
struct GuiState {
    session: Mutex<Session>,
    operation: Mutex<Operation>,
    passwords: Mutex<Passwords>,
}

impl GuiState {
    fn operation(&self) -> std::sync::MutexGuard<'_, Operation> {
        // Nothing under this lock can panic while it is held, so poisoning would
        // only be a leftover from an unrelated crash.
        self.operation
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
    }

    /// Publishes the handle for the command about to run, so Stop can reach it.
    ///
    /// Reports whether a stop was already asked for, which the caller must honour:
    /// the window keeps Stop available for the whole operation, including the moment
    /// before the first command has a handle to cancel.
    fn arm(&self, canceller: Option<Canceller>) -> bool {
        let mut operation = self.operation();
        operation.canceller = canceller;
        operation.stop_requested
    }

    /// Stops the operation in flight. Reports whether there was one.
    ///
    /// The request is remembered for as long as the operation lasts, so that a batch
    /// stops even when the press lands between two cells.
    fn stop(&self) -> bool {
        let mut operation = self.operation();
        if !operation.busy {
            return false;
        }
        operation.stop_requested = true;
        if let Some(canceller) = &operation.canceller {
            canceller.cancel();
        }
        true
    }

    fn passwords(&self) -> std::sync::MutexGuard<'_, Passwords> {
        // As with `operation`: nothing under this lock can panic.
        self.passwords
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
    }

    /// Registers a request for a password, returning its id and where the answer
    /// will arrive. `None` when no command is running to have asked, when the
    /// request's own run is over (`gone`), or when the window cannot show the
    /// question.
    ///
    /// `gone` is asked under the lock: `accepting` may have been cleared for the
    /// request's run and set again for the next one while the request was on its
    /// way, and it is `gone` that tells the two runs apart.
    fn request_password(
        &self,
        gone: &dyn Fn() -> bool,
    ) -> Option<(u64, mpsc::Receiver<Option<String>>)> {
        let mut passwords = self.passwords();
        if !passwords.window_listens || !passwords.accepting || gone() {
            // Outside a run it is a leftover from a command already written back -- a
            // background process it started, say -- with no cell to show it against.
            return None;
        }
        let id = passwords.next;
        passwords.next += 1;
        let (reply, answer) = mpsc::channel();
        passwords.pending.insert(id, reply);
        Some((id, answer))
    }

    /// Puts a registered request to the window with `show`, unless the request
    /// has been abandoned since it was registered. Reports whether it was shown.
    ///
    /// Under the lock, so that abandoning a run's requests and showing one of them
    /// cannot cross: a request registered just before its run ended would
    /// otherwise come up under the next cell. A `show` that fails drops the
    /// request, which the helper reads as a decline.
    fn show_password_request(&self, id: u64, show: impl FnOnce() -> bool) -> bool {
        let mut passwords = self.passwords();
        if !passwords.pending.contains_key(&id) {
            return false;
        }
        if show() {
            return true;
        }
        passwords.pending.remove(&id);
        false
    }

    /// Answers a request. Reports whether it was still waiting.
    fn answer_password(&self, id: u64, answer: Option<String>) -> bool {
        match self.passwords().pending.remove(&id) {
            Some(reply) => reply.send(answer).is_ok(),
            None => false,
        }
    }

    /// Starts taking requests, for the command about to run.
    fn accept_passwords(&self) {
        self.passwords().accepting = true;
    }

    /// Declines every request still waiting and stops taking new ones. Called when a
    /// command ends: whatever asked is gone with it, and the window closes its
    /// prompt on the same event.
    fn abandon_passwords(&self) {
        let mut passwords = self.passwords();
        passwords.accepting = false;
        // Dropping a sender is a decline to the helper waiting on it.
        passwords.pending.clear();
    }

    /// Whether Stop has been pressed during the operation in flight.
    fn stop_requested(&self) -> bool {
        self.operation().stop_requested
    }

    /// Marks an operation as started, or reports that one is already in flight.
    ///
    /// The guard clears the mark on drop, so an early return or a panic in a command
    /// cannot leave the app permanently refusing to run anything.
    fn acquire(&self) -> Result<BusyGuard<'_>, String> {
        let mut operation = self.operation();
        if operation.busy {
            return Err("A command is already running.".to_string());
        }
        // A stop belongs to the operation it was pressed during, so this one starts
        // with a clean slate.
        *operation = Operation {
            busy: true,
            ..Operation::default()
        };
        Ok(BusyGuard { state: self })
    }
}

/// Ends the operation when it goes out of scope.
struct BusyGuard<'a> {
    state: &'a GuiState,
}

impl Drop for BusyGuard<'_> {
    fn drop(&mut self) {
        let mut operation = self.state.operation();
        operation.busy = false;
        operation.canceller = None;
    }
}

/// Builds the view of the document currently held in memory.
fn document_view(session: &Session) -> DocumentView {
    let doc = session.doc();
    let cells = doc
        .cells
        .iter()
        .map(|cell| CellView {
            index: cell.index,
            number: cell.display_number(),
            lang: cell.lang.clone(),
            command: cell.command.clone(),
            out_file: cell.out_file.clone(),
            result: doc.result_text(cell).map(str::to_string),
        })
        .collect();
    DocumentView {
        path: session.path().display().to_string(),
        cells,
    }
}

/// Reads the document without touching the disk.
#[tauri::command]
fn document(state: State<'_, GuiState>) -> Result<DocumentView, String> {
    let session = state.session.lock().map_err(lock_error)?;
    Ok(document_view(&session))
}

/// Re-reads the file, picking up edits made in an external editor.
#[tauri::command]
fn reload(state: State<'_, GuiState>) -> Result<DocumentView, String> {
    reload_session(&state)
}

/// The body of [`reload`], separated from the Tauri wrapper so it can be tested
/// without an app handle.
///
/// **Reloading takes the busy flag too, so it cannot happen during a run.**
/// `Session::apply_outcome` refuses to write when the file changed while the
/// command was running, and it detects that by comparing the file against the
/// document it held *before* the run. A reload replaces that document with
/// whatever is on disk now, which makes the comparison pass again -- the check
/// would be defeated by the very thing it guards against, and the result of the
/// old command could land on a cell that is no longer the one it came from.
fn reload_session(state: &GuiState) -> Result<DocumentView, String> {
    let _busy = state
        .acquire()
        .map_err(|_| "A command is running, so the file cannot be reloaded yet.".to_string())?;
    let mut session = state.session.lock().map_err(lock_error)?;
    session.reload().map_err(|error| error.to_string())?;
    Ok(document_view(&session))
}

/// Runs one cell and writes the result back.
#[tauri::command]
async fn run_cell(
    app: AppHandle,
    state: State<'_, GuiState>,
    index: usize,
) -> Result<RunReport, String> {
    let _busy = state.acquire()?;
    execute(&app, &state, index).await
}

/// Runs every cell in order.
///
/// A failed command does not stop the batch -- its exit code is the result and
/// gets written back like any other. A failed *write-back* does stop it: the file
/// changed underneath us, so the commands held in memory may no longer be the
/// ones in the file.
#[tauri::command]
async fn run_all(app: AppHandle, state: State<'_, GuiState>) -> Result<BatchReport, String> {
    let _busy = state.acquire()?;
    let count = {
        let session = state.session.lock().map_err(lock_error)?;
        session.len()
    };

    let mut reports = Vec::new();
    let mut stopped = false;
    for index in 0..count {
        // Asked before the cell starts as well as after it ends. Writing the previous
        // result back takes real time, and a Stop landing in that gap has no command
        // to cancel -- starting this cell only to kill it at once would replace the
        // result it already had with an empty one.
        if state.stop_requested() {
            stopped = true;
            break;
        }
        match execute(&app, &state, index).await {
            Ok(report) => {
                stopped = report.cancelled;
                reports.push(report);
                if stopped {
                    // Stop was pressed. Its result has been written back; carrying on
                    // to the next cell is not what was asked for.
                    break;
                }
            }
            Err(error) => return Err(error),
        }
    }
    // Asked once more rather than left to the loop: a Stop landing while the last
    // cell's result is written back never reaches a check above, and the window
    // would report the batch as having run to the end after saying it was stopping.
    Ok(BatchReport {
        reports,
        stopped: stopped || state.stop_requested(),
    })
}

/// Stops the command in flight, keeping the output it has produced so far.
///
/// Reports whether there was anything to stop, so the window can tell "stopped"
/// from "nothing was running" without guessing.
#[tauri::command]
fn cancel(state: State<'_, GuiState>) -> bool {
    state.stop()
}

/// Tells the backend that the window is listening for password requests.
///
/// Called once the subscriptions are in place. Before that -- and for good, if
/// subscribing failed -- requests are declined at once rather than sent to nobody.
#[tauri::command]
fn listen_for_passwords(state: State<'_, GuiState>) {
    state.passwords().window_listens = true;
}

/// Answers a command's request for a password. `None` declines it.
///
/// Reports whether the request was still waiting: one whose command has ended is
/// gone, and the answer goes nowhere.
#[tauri::command]
fn answer_password(state: State<'_, GuiState>, id: u64, answer: Option<String>) -> bool {
    state.answer_password(id, answer)
}

/// The body shared by [`run_cell`] and [`run_all`].
///
/// Split out so that the busy flag is taken once for a whole batch: taking it per
/// cell would let a second batch interleave with this one.
async fn execute(
    app: &AppHandle,
    state: &State<'_, GuiState>,
    index: usize,
) -> Result<RunReport, String> {
    let (command, run) = {
        let session = state.session.lock().map_err(lock_error)?;
        if index >= session.len() {
            return Err(format!("There is no cell {}.", index + 1));
        }
        (session.command_of(index), session.start_run())
    };

    // One handle per run: a stopped cell must not leave the next one unable to start.
    let canceller = Canceller::new();
    if state.arm(Some(canceller.clone())) {
        // Stop was pressed before this command had a handle. Honour it here rather
        // than let the press vanish.
        canceller.cancel();
    }

    let _ = app.emit(EVENT_STARTED, index);
    state.accept_passwords();
    // The lock is deliberately not held here: the run can take minutes, and the
    // window keeps reading the document while it does.
    let reporter = app.clone();
    let outcome = tauri::async_runtime::spawn_blocking(move || {
        let outcome = runandlog_core::run_streaming(&command, &run.options, &canceller, |chunk| {
            // Sent as the command prints rather than kept until it ends: a run that
            // takes minutes should show what it is doing while it does it.
            let _ = reporter.emit(
                EVENT_OUTPUT,
                OutputChunk {
                    index,
                    text: crate::live::tail(chunk, MAX_OUTPUT_CHUNK_BYTES).to_string(),
                },
            );
        });
        // The command is over; the write-back that follows is not part of the run.
        drop(run);
        outcome
    })
    .await
    .map_err(|error| format!("The worker thread died unexpectedly: {error}"))
    .inspect_err(|_| {
        state.arm(None);
        state.abandon_passwords();
    })?
    .map_err(|error| format!("The run failed: {error}"))
    .inspect_err(|_| {
        state.arm(None);
        state.abandon_passwords();
    })?;
    // Disarmed as soon as the command is over: from here on there is nothing to
    // stop, and a Stop that arrived late must not reach the *next* run.
    state.arm(None);
    state.abandon_passwords();

    let view = {
        let mut session = state.session.lock().map_err(lock_error)?;
        session
            .apply_outcome(index, &outcome)
            .map_err(|error| format!("Writing the result failed: {error}"))?;
        document_view(&session)
    };
    let _ = app.emit(EVENT_DOCUMENT, &view);
    let report = RunReport {
        index,
        status: outcome.status_text(),
        success: outcome.is_success(),
        cancelled: outcome.cancelled,
    };
    let _ = app.emit(EVENT_FINISHED, &report);
    Ok(report)
}

/// The licences shown in the Third-Party Licenses window: Run and Log's own, then
/// those of the libraries compiled into it. The same text `--license` prints.
#[tauri::command]
fn third_party_notices() -> String {
    crate::notices::license_text()
}

/// The app's menu: Tauri's default one, with "Third-Party Licenses" right below
/// "About".
///
/// About sits first in the app menu on macOS and first in the Help menu
/// elsewhere, which is where Tauri's default menu puts it; the item goes in at
/// the position after it. Nothing else of the default menu is changed, so the
/// Edit menu's copy and paste keep working in the window.
fn app_menu(app: &AppHandle) -> tauri::Result<tauri::menu::Menu<tauri::Wry>> {
    let menu = tauri::menu::Menu::default(app)?;
    let about_menu = if cfg!(target_os = "macos") {
        menu.items()?.into_iter().next()
    } else {
        menu.get(tauri::menu::HELP_SUBMENU_ID)
    };
    if let Some(submenu) = about_menu.as_ref().and_then(|item| item.as_submenu()) {
        let licenses = tauri::menu::MenuItem::with_id(
            app,
            LICENSES,
            "Third-Party Licenses",
            true,
            None::<&str>,
        )?;
        submenu.insert(&licenses, 1)?;
    }
    Ok(menu)
}

/// Opens the Third-Party Licenses window, or brings it forward when it is open.
///
/// The window gets no capability: it calls nothing but [`third_party_notices`],
/// a command of the app's own, which needs none.
fn show_licenses(app: &AppHandle) -> tauri::Result<()> {
    if let Some(window) = app.get_webview_window(LICENSES) {
        return window.set_focus();
    }
    tauri::WebviewWindowBuilder::new(
        app,
        LICENSES,
        tauri::WebviewUrl::App("licenses.html".into()),
    )
    .title("Third-Party Licenses")
    .inner_size(720.0, 640.0)
    .build()?;
    Ok(())
}

/// A poisoned lock means another thread panicked while holding the session.
fn lock_error<T>(_: std::sync::PoisonError<T>) -> String {
    "The session is no longer usable because a background task panicked.".to_string()
}

/// Opens the desktop app.
///
/// Mirrors [`crate::tui::run`]: it takes an already loaded session and returns
/// when the window closes.
pub fn run(session: Session) -> io::Result<()> {
    if let Some(reason) = no_display_reason() {
        return Err(io::Error::other(reason));
    }

    // The title is built before the session is handed over, so that the setup hook
    // does not have to take the lock just to read the file name.
    let title = window_title(session.path());

    let app = tauri::Builder::default()
        .manage(GuiState {
            session: Mutex::new(session),
            operation: Mutex::new(Operation::default()),
            passwords: Mutex::new(Passwords::default()),
        })
        .manage(AskpassSlot::default())
        .menu(app_menu)
        .on_menu_event(|app, event| {
            if event.id() == LICENSES
                && let Err(error) = show_licenses(app)
            {
                eprintln!("runandlog: could not open the licenses window: {error}");
            }
        })
        .setup(move |app| {
            // Say which file is open. tauri.conf.json cannot express this because
            // the path is only known at run time.
            if let Some(window) = app.get_webview_window("main") {
                let _ = window.set_title(&title);
            }
            start_askpass(app.handle());
            Ok(())
        })
        .invoke_handler(tauri::generate_handler![
            document,
            reload,
            run_cell,
            run_all,
            cancel,
            listen_for_passwords,
            answer_password,
            third_party_notices
        ])
        .build(tauri::generate_context!())
        .map_err(io::Error::other)?;
    app.run(|app, event| {
        if let tauri::RunEvent::Exit = event {
            // The app may leave by exiting the process, which runs no destructors;
            // taken here, the helper's directory does not outlive the window.
            let slot = app.state::<AskpassSlot>();
            drop(slot.0.lock().unwrap_or_else(PoisonError::into_inner).take());
        }
    });
    Ok(())
}

/// Holds the askpass helper for as long as the window is open.
#[derive(Default)]
struct AskpassSlot(
    #[cfg(unix)] Mutex<Option<crate::askpass::Askpass>>,
    #[cfg(not(unix))] Mutex<Option<()>>,
);

/// Lets commands ask for a password through the window.
///
/// A failure to start leaves commands where they were before there was a helper --
/// asking for a password fails at once -- which is no reason to refuse to open.
#[cfg(unix)]
fn start_askpass(app: &AppHandle) {
    let handle = app.clone();
    let prompter = Box::new(move |prompt: &str, gone: &dyn Fn() -> bool| {
        let state = handle.state::<GuiState>();
        let (id, answer) = state.request_password(gone)?;
        let request = PasswordRequest {
            id,
            prompt: prompt.to_string(),
        };
        // Not shown when the run ended in between; the wait below then finds the
        // sender dropped and declines at once.
        state.show_password_request(id, || handle.emit(EVENT_PASSWORD, request).is_ok());
        // A dropped sender -- the run ended with the prompt up -- is a decline.
        crate::askpass::wait_for_answer(&answer, gone)
    });
    let Ok(askpass) = crate::askpass::Askpass::start(prompter) else {
        return;
    };
    let state = app.state::<GuiState>();
    state
        .session
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .set_run_hook(askpass.hook());
    *app.state::<AskpassSlot>()
        .0
        .lock()
        .unwrap_or_else(PoisonError::into_inner) = Some(askpass);
}

#[cfg(not(unix))]
fn start_askpass(_app: &AppHandle) {}

/// Why the window cannot be opened, when there is no display to open it on.
///
/// GTK aborts the process with a panic when it cannot reach a display, which is
/// what happens over a plain SSH session or in a container. Running a command
/// line tool should not look like a crash, so the common case is caught here and
/// reported as an ordinary error, pointing at the TUI that does work there.
///
/// Only Linux needs this: macOS and Windows have no equivalent environment
/// variable, and their windowing systems are always available to a logged-in
/// user.
#[cfg(target_os = "linux")]
fn no_display_reason() -> Option<&'static str> {
    display_reason(
        std::env::var_os("DISPLAY").as_deref(),
        std::env::var_os("WAYLAND_DISPLAY").as_deref(),
    )
}

/// The decision behind [`no_display_reason`], with the environment passed in.
///
/// Kept separate so the tests do not have to set environment variables: they are
/// process-wide, and the test harness runs tests on threads, so mutating them is
/// both unsound and able to disturb unrelated tests.
#[cfg(target_os = "linux")]
fn display_reason(
    display: Option<&std::ffi::OsStr>,
    wayland: Option<&std::ffi::OsStr>,
) -> Option<&'static str> {
    // An empty value is what a stripped SSH environment leaves behind, and it is
    // no more usable than an unset one.
    let usable = |value: Option<&std::ffi::OsStr>| value.is_some_and(|value| !value.is_empty());
    if usable(display) || usable(wayland) {
        return None;
    }
    Some(
        "no display is available (DISPLAY and WAYLAND_DISPLAY are both unset), so the GUI cannot open; drop --gui to use the TUI",
    )
}

#[cfg(not(target_os = "linux"))]
fn no_display_reason() -> Option<&'static str> {
    None
}

/// Window title: the file name, falling back to the whole path when there is no
/// file name to show (a path ending in `..`, for instance).
fn window_title(path: &Path) -> String {
    let name = path
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_else(|| path.display().to_string());
    format!("Run and Log - {name}")
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use runandlog_core::ExecOptions;

    use super::*;

    /// Hands out a distinct number per directory.
    ///
    /// Tests run on threads of one process, so the pid alone does not separate
    /// them: two tests picking the same directory would delete it from under each
    /// other on the way in.
    static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);

    /// A temporary directory for tests, including its own cleanup.
    struct TempDir(PathBuf);

    impl TempDir {
        fn new() -> TempDir {
            let path = std::env::temp_dir().join(format!(
                "runandlog-gui-test-{}-{}",
                std::process::id(),
                NEXT_DIR.fetch_add(1, Ordering::SeqCst)
            ));
            let _ = std::fs::remove_dir_all(&path);
            std::fs::create_dir_all(&path).unwrap();
            TempDir(path)
        }

        fn write(&self, name: &str, contents: &str) -> PathBuf {
            let path = self.0.join(name);
            std::fs::write(&path, contents).unwrap();
            path
        }
    }

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    fn session(path: &Path) -> Session {
        let mut options = ExecOptions::new(path.parent().unwrap());
        options.shell = PathBuf::from("/bin/sh");
        Session::load(path, options, 50).unwrap()
    }

    /// The caller keeps the directory alive: dropping it deletes the file the
    /// session was loaded from.
    fn state(dir: &TempDir) -> GuiState {
        GuiState {
            // The session is irrelevant to the busy flag, so any file will do.
            session: Mutex::new(session(&dir.write("doc.md", "# no cells\n"))),
            operation: Mutex::new(Operation::default()),
            passwords: Mutex::new(Passwords::default()),
        }
    }

    #[test]
    fn a_password_is_only_asked_for_while_a_command_runs() {
        let dir = TempDir::new();
        let state = state(&dir);
        state.passwords().window_listens = true;
        // Nothing is running: there is no cell to show the prompt against.
        assert!(state.request_password(&|| false).is_none());

        state.accept_passwords();
        // A request whose own run is over is refused even while requests are
        // being taken: the run it belongs to is not the one they are taken for.
        assert!(state.request_password(&|| true).is_none());
        let (id, answer) = state.request_password(&|| false).unwrap();
        assert!(state.show_password_request(id, || true));
        assert!(state.answer_password(id, Some("s3cret".to_string())));
        assert_eq!(answer.recv().unwrap(), Some("s3cret".to_string()));
        // Answered once; a second answer has nowhere to go.
        assert!(!state.answer_password(id, None));
    }

    #[test]
    fn a_prompt_left_up_when_the_command_ends_is_declined() {
        let dir = TempDir::new();
        let state = state(&dir);
        state.passwords().window_listens = true;
        state.accept_passwords();
        let (id, answer) = state.request_password(&|| false).unwrap();
        state.abandon_passwords();
        // Registered just before the run ended: not shown, since nobody is running
        // to have asked, and the window must not put it under the next cell.
        assert!(!state.show_password_request(id, || unreachable!("shown after abandon")));
        // The helper sees the dropped sender and tells its command "no password".
        assert!(answer.recv().is_err());
        // And an answer typed after that goes nowhere.
        assert!(!state.answer_password(id, Some("late".to_string())));
        // Nor can anything ask again until the next command starts.
        assert!(state.request_password(&|| false).is_none());
    }

    #[test]
    fn a_request_the_window_cannot_be_shown_is_declined() {
        // A window that cannot be reached is a decline, not a wait.
        let dir = TempDir::new();
        let state = state(&dir);
        state.passwords().window_listens = true;
        state.accept_passwords();
        let (id, answer) = state.request_password(&|| false).unwrap();
        assert!(!state.show_password_request(id, || false));
        assert!(answer.recv().is_err());
        assert!(!state.answer_password(id, Some("late".to_string())));
    }

    #[test]
    fn nothing_is_asked_through_a_window_that_is_not_listening() {
        // Subscribing can fail, and the window then runs without events. A request
        // sent to it would be seen by nobody and hold the command until Stop.
        let dir = TempDir::new();
        let state = state(&dir);
        state.accept_passwords();
        assert!(state.request_password(&|| false).is_none());
    }

    #[test]
    fn the_title_shows_the_file_name() {
        assert_eq!(
            window_title(Path::new("/tmp/notes/exam.md")),
            "Run and Log - exam.md"
        );
    }

    #[test]
    fn the_title_falls_back_to_the_whole_path() {
        // A path with no file name still has to produce a title rather than panic.
        assert_eq!(window_title(Path::new("/tmp/..")), "Run and Log - /tmp/..");
    }

    #[test]
    fn a_second_run_is_refused_while_one_is_in_flight() {
        let dir = TempDir::new();
        let state = state(&dir);
        let _first = state.acquire().unwrap();
        // Two runs would write back to the same file and each would see the other's
        // edit as an external modification.
        assert!(state.acquire().is_err());
    }

    #[test]
    fn the_busy_flag_is_released_when_the_guard_is_dropped() {
        let dir = TempDir::new();
        let state = state(&dir);
        drop(state.acquire().unwrap());
        // Without the Drop impl an early return would leave the app refusing to run
        // anything for the rest of the session.
        assert!(state.acquire().is_ok());
    }

    #[test]
    fn stopping_while_idle_says_there_was_nothing_to_stop() {
        let dir = TempDir::new();
        let state = state(&dir);
        // The window uses this to tell "stopped" from "there was nothing to stop"
        // rather than reporting a stop that never happened.
        assert!(!state.stop());
        assert!(!state.stop_requested());
    }

    #[test]
    fn stopping_reaches_the_run_in_flight() {
        let dir = TempDir::new();
        let state = state(&dir);
        let _busy = state.acquire().unwrap();
        let canceller = Canceller::new();
        state.arm(Some(canceller.clone()));

        assert!(state.stop());
        assert!(canceller.is_cancelled());
    }

    #[test]
    fn a_stop_between_two_cells_still_stops_the_batch() {
        let dir = TempDir::new();
        let state = state(&dir);
        let _busy = state.acquire().unwrap();
        // Where `run_all` is between cells: the previous run is disarmed and the
        // next one has not started. There is no handle to cancel, so the press has
        // to be remembered instead of dropped.
        state.arm(None);

        assert!(state.stop());
        assert!(state.stop_requested());
    }

    #[test]
    fn a_stop_that_beats_the_command_to_the_start_is_honoured() {
        let dir = TempDir::new();
        let state = state(&dir);
        let _busy = state.acquire().unwrap();
        // The window enables Stop as soon as the operation begins, which is before
        // the first command exists.
        state.stop();

        let canceller = Canceller::new();
        // `execute` cancels when arming reports a pending stop.
        assert!(state.arm(Some(canceller.clone())));
    }

    #[test]
    fn a_stop_does_not_carry_over_to_the_next_run() {
        let dir = TempDir::new();
        let state = state(&dir);
        let busy = state.acquire().unwrap();
        let stopped = Canceller::new();
        state.arm(Some(stopped.clone()));
        state.stop();
        // Disarmed when the run ends, exactly as `execute` does it.
        state.arm(None);
        drop(busy);

        let _busy = state.acquire().unwrap();
        let next = Canceller::new();
        // Without a fresh handle per run, and without clearing the request when the
        // next operation starts, the next command would refuse to start.
        assert!(!state.arm(Some(next.clone())));
        assert!(!next.is_cancelled());
        assert!(stopped.is_cancelled());
    }

    #[test]
    fn reloading_is_refused_while_a_command_is_running() {
        let dir = TempDir::new();
        let state = state(&dir);
        let _running = state.acquire().unwrap();

        // Session::apply_outcome spots an external edit by comparing the file with
        // the document it held before the run. Reloading mid-run replaces that
        // document with the edited file, so the comparison passes and the result of
        // the old command can be written to whatever cell now sits at that index.
        assert!(reload_session(&state).is_err());
    }

    #[test]
    fn reloading_works_again_once_the_run_is_over() {
        let dir = TempDir::new();
        let state = state(&dir);
        drop(state.acquire().unwrap());

        // The guard above must not leave reloading blocked for the rest of the
        // session.
        assert!(reload_session(&state).is_ok());
    }

    #[test]
    fn reloading_picks_up_an_external_edit() {
        let dir = TempDir::new();
        let state = state(&dir);
        assert!(reload_session(&state).unwrap().cells.is_empty());

        dir.write("doc.md", "```shell\ndate\n```\n");
        let view = reload_session(&state).unwrap();

        assert_eq!(view.cells.len(), 1);
        assert_eq!(view.cells[0].command, "date\n");
    }

    #[test]
    fn the_view_carries_what_the_window_draws() {
        let dir = TempDir::new();
        let path = dir.write(
            "doc.md",
            "# notes\n\n```shell\ndate\n```\n\n```shell out=log.txt\nls\n```\n",
        );
        let view = document_view(&session(&path));

        assert_eq!(view.cells.len(), 2);
        assert_eq!(view.cells[0].index, 0);
        // The window labels cells the way the CLI and the TUI do, from 1.
        assert_eq!(view.cells[0].number, 1);
        assert_eq!(view.cells[0].command, "date\n");
        assert_eq!(view.cells[0].out_file, None);
        assert_eq!(view.cells[0].result, None);
        assert_eq!(view.cells[1].number, 2);
        assert_eq!(view.cells[1].out_file.as_deref(), Some("log.txt"));
    }

    #[test]
    fn the_view_carries_the_previous_result() {
        let dir = TempDir::new();
        let path = dir.write(
            "doc.md",
            "```shell\ndate\n```\n\n<!-- runandlog:begin -->\nRan result: earlier\n<!-- runandlog:end -->\n",
        );
        let view = document_view(&session(&path));

        // The window shows the last result on open, without re-running anything.
        assert_eq!(view.cells[0].result.as_deref(), Some("Ran result: earlier"));
    }
}

#[cfg(all(test, target_os = "linux"))]
mod display_tests {
    use std::ffi::OsStr;

    use super::*;

    #[test]
    fn a_missing_display_is_reported_instead_of_crashing_gtk() {
        // Without this check GTK aborts the process, which reads as a crash rather
        // than as "this machine has no screen".
        assert!(display_reason(None, None).is_some());
    }

    #[test]
    fn either_display_variable_is_enough() {
        assert!(display_reason(Some(OsStr::new(":0")), None).is_none());
        assert!(display_reason(None, Some(OsStr::new("wayland-0"))).is_none());
    }

    #[test]
    fn an_empty_value_does_not_count_as_a_display() {
        // A stripped SSH environment leaves the variable set but empty, and GTK
        // cannot connect to that any more than to an unset one.
        assert!(display_reason(Some(OsStr::new("")), Some(OsStr::new(""))).is_some());
    }
}