croft-software 0.2.232

VSCode-style TUI written in Rust
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
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
//! A single-line text input modal for Source Control operations that need
//! a typed value: a clone URL, a new branch name, a remote name/URL, a tag
//! name. Croft's design rule keeps inputs in a visible popup (never the
//! status line), so every such prompt routes through this widget.
//!
//! The widget is pure: it owns the prompt text, the typed value, and the
//! caret. The App holds it inside `Option<InputPrompt>` with a `purpose`
//! tag so a single key/mouse/render path serves every prompt, and decides
//! what to do with the submitted string.
//!
//! A yes/no question ([`InputPrompt::confirm`]) uses the same box with no
//! field, so nothing typed can look like an answer the App then ignores.

use std::path::PathBuf;

use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph, Widget},
};
use unicode_width::UnicodeWidthStr;

/// The four ways VS Code's Databases view adds a database (#578).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodeqlDbSource {
    Folder,
    Archive,
    Url,
    Github,
}

/// Why an input prompt is open, so the App can route the submitted value
/// to the right git operation. Variants carry whatever context the second
/// step needs (e.g. the base ref a new branch forks from).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InputPurpose {
    /// Extract one archive member (#179): the typed value is the
    /// destination folder.
    ArchiveExtract {
        member: String,
    },
    /// Name a new worktree lane (#348): the typed value becomes the branch
    /// `agent/<slug>` and a sibling directory beside the repo.
    NewWorktreeLane,
    /// The command to run across the fleet (#363).
    FleetCommand,
    /// The host to push the syncable config to now (#262).
    SyncConfigHost,
    /// The pull request to review (#365): a number, `#n`, or its URL.
    PullRequestNumber,
    /// Where to add a CodeQL database from (#578).
    CodeqlDatabase {
        source: CodeqlDbSource,
    },
    /// Confirm removing the CodeQL database at `path` (#578). Submitting
    /// (Enter) removes it; Esc keeps it. A Y/N confirm, with no value.
    CodeqlRemoveDatabase {
        path: PathBuf,
    },
    /// Confirm deleting the unused CodeQL databases at `paths` (#578), all
    /// copies in croft's cache. Submitting (Enter) deletes them; Esc keeps
    /// them. A Y/N confirm, with no value.
    CodeqlDeleteUnusedDatabases {
        paths: Vec<PathBuf>,
    },
    /// A new display name for the CodeQL database at `path` (#578).
    CodeqlRenameDatabase {
        path: PathBuf,
    },
    /// Confirm removing the query history entry whose run wrote `output`
    /// (#578). Submitting (Enter) removes it; Esc keeps it. A Y/N confirm,
    /// with no value.
    CodeqlRemoveHistory {
        output: PathBuf,
    },
    /// A label for the query history entry whose run wrote `output` (#578).
    CodeqlRenameHistory {
        output: PathBuf,
    },
    /// The name of a new CodeQL query to write into `dir` (#578), in
    /// `language` when it is known.
    CodeqlCreateQuery {
        dir: PathBuf,
        language: Option<String>,
    },
    /// The controller repository variant analysis runs from (#578):
    /// `owner/repo` or its GitHub URL.
    CodeqlControllerRepository,
    /// A repository to add for variant analysis (#578), into the list
    /// called `list` when there is one.
    CodeqlAddVariantRepo {
        list: Option<String>,
    },
    /// The name of a new variant analysis repository list (#578).
    CodeqlAddVariantList,
    /// A GitHub user or organisation to add for variant analysis (#578).
    CodeqlAddVariantOwner,
    /// The CodeQL packs to download from the registry (#578).
    CodeqlDownloadPacks,
    /// Where to copy the query results at `output` (#578).
    CodeqlExportResults {
        output: PathBuf,
    },
    /// CodeQL: Run Queries in Published Pack (#578): the pack reference.
    CodeqlRunPublishedPack,
    /// A GitHub Code Search query whose repositories go into the variant
    /// analysis list called `list` (#578).
    CodeqlVariantCodeSearch {
        list: String,
    },
    /// Where to export the results of remembered variant analysis `index`
    /// (#578): a folder, or `gist`.
    CodeqlExportVariantResults {
        index: usize,
    },
    /// A new name for the variant analysis list called `name` (#578).
    CodeqlRenameVariantList {
        name: String,
    },
    /// Confirm removing the variant analysis list called `name` (#578).
    /// Submitting (Enter) removes it; Esc keeps it. A Y/N confirm, with no
    /// value.
    CodeqlRemoveVariantList {
        name: String,
    },
    /// Where a SARIF result's file lives on this machine (#577): the value
    /// is a path; `uri` is the location the log named.
    SarifLocate {
        uri: String,
    },
    /// The kind of Model Editor model `choice` of endpoint `endpoint`
    /// (#578): `remote`, `command-injection`, `taint`, โ€ฆ
    CodeqlModelKind {
        endpoint: usize,
        choice: usize,
    },
    /// A missing SARIF file that can be downloaded from `host`, which is
    /// not yet trusted (#577). An empty value trusts `host` and downloads;
    /// a path locates the file instead, as [`InputPurpose::SarifLocate`].
    SarifTrustHost {
        uri: String,
        host: String,
        url: String,
    },
    /// Another SARIF log to merge into the open viewer (#577).
    SarifAddLog,
    /// The SARIF results list's optional columns, comma-separated (#577).
    SarifColumns,
    /// A baseline SARIF log to compare the open viewer against (#577).
    SarifBaseline,
    /// Where to write the SARIF viewer's visible results as CSV (#577).
    SarifExport,
    /// The optional comment for dismissing code scanning alert `number`
    /// with reason `reason` (an index into `DismissReason::ALL`).
    DismissAlertComment {
        number: u64,
        reason: usize,
    },
    /// A new value for the setting `key` (#612).
    SettingValue {
        key: String,
    },
    /// Find in a hex tab (#172): the typed value is hex byte pairs
    /// ("de ad be ef") or, when it does not parse as hex, literal ASCII.
    /// Submitting stores the query on the view and jumps to the first
    /// match at or after the cursor; F3 repeats it.
    HexFind,
    /// Emmet: Wrap with Abbreviation (#1557): the typed abbreviation wraps
    /// the selection.
    EmmetWrap,
    /// Emmet: Update Tag (#1557): the typed name replaces the enclosing
    /// element's.
    EmmetUpdateTag,
    /// Save the current folder set as a VS Code-compatible workspace
    /// file (#163): the typed value is the destination path.
    SaveWorkspaceAs,
    /// Confirm changing the folder list of the workspace file that exists
    /// at `dest` (#1012). Submitting (Enter) rewrites its `folders` and
    /// nothing else; Esc leaves it. A Y/N confirm, with no value.
    UpdateWorkspaceFile {
        dest: PathBuf,
    },
    CloneUrl,
    RenameBranch,
    CreateBranchFrom {
        base: String,
    },
    AddRemoteName,
    AddRemoteUrl {
        name: String,
    },
    CreateTag,
    /// Create Tag Here on a COMMITS row (#1627): the tag goes on `target`,
    /// the clicked commit, rather than on HEAD.
    CreateTagAt {
        target: String,
    },
    /// The optional message for tag `name` (#1582): one makes an annotated
    /// tag, none (Enter on a blank field) a lightweight one.
    CreateTagMessage {
        name: String,
    },
    /// Confirm deleting tag `name` from `remote` (#1582). Submitting (Enter)
    /// deletes it there; Esc keeps it. A Y/N confirm, with no value. `root` is
    /// the repository whose remote was listed: the deletion is dropped if
    /// Source Control has moved to another one by then.
    DeleteRemoteTag {
        root: std::path::PathBuf,
        remote: String,
        name: String,
    },
    /// Add a debugger watch expression (#112): submitting appends it to the
    /// App's watch list and re-evaluates at the current stop.
    AddWatch,
    /// First-run consent for an extension-contributed viewer (#485 review):
    /// the same gate a sidecar passes, since both spawn a program from a
    /// manifest. Carries the viewer's key and the file, so allowing resumes
    /// the open the user asked for.
    ViewerConsent {
        key: String,
        path: std::path::PathBuf,
    },
    /// First-run consent to spawn an MCP sidecar: submitting confirms, then the
    /// command (`command_id`) proceeds to its argument prompt or runs.
    McpConsent {
        command_id: String,
    },
    /// Collect the single string argument for an MCP command before calling its
    /// tool. The submitted value fills the tool's declared argument.
    McpArg {
        command_id: String,
    },
    /// Collect a repeat count for "Macro: Replay N Timesโ€ฆ" (#255). A value
    /// that is not a positive number is refused rather than silently
    /// replaying once.
    MacroReplayCount,
    /// The optional name for a stash (#1581), as VS Code's Git: Stash asks:
    /// one becomes `git stash push -m`, a blank field keeps git's own
    /// `WIP on <branch>: <commit>`.
    StashMessage {
        kind: crate::git::StashKind,
    },
    /// Confirm uninstalling an installed extension. Submitting (Enter) performs
    /// the removal; Esc keeps it. A Y/N confirm, with no value.
    ExtensionUninstall {
        id: String,
    },
    /// Confirm moving Explorer file-tree entries to the OS Trash. Submitting
    /// (Enter) trashes `paths`; Esc keeps them. A Y/N confirm, with no value:
    /// a prefilled `trash` read as type-to-confirm, yet any answer trashed
    /// (#855).
    TreeDelete {
        paths: Vec<PathBuf>,
    },
    /// A dirty buffer collided with an external write. Submitting (Enter)
    /// reloads `paths` from disk, discarding local edits; Esc keeps the edits.
    /// The value is a sentinel.
    ReloadConflict {
        paths: Vec<PathBuf>,
    },
    /// Instruction for the resident navigator (`croft pair`), scoped to the
    /// 0-based inclusive line `range` of `file`; `selection` carries the
    /// selected text when the scope came from a selection. Submitting sends
    /// the ask turn (the navigator may edit on it).
    AskNavigator {
        file: String,
        range: (usize, usize),
        selection: String,
    },
    /// One field of **Debug: Add Configurationโ€ฆ** (#250); the draft it
    /// fills is the App's.
    DebugConfigField {
        field: crate::dap::configs::DraftField,
    },
    /// A `${input:โ€ฆ}` a launch or task asks for (#1424); the question
    /// itself is the App's.
    LaunchInput,
    /// Go to Line, opened by clicking the status bar's `Ln X, Col Y`
    /// readout: the typed value is a one-based line number.
    GoToLine,
}

pub struct InputPrompt {
    pub purpose: InputPurpose,
    pub title: String,
    pub placeholder: String,
    pub value: String,
    pub cursor: usize,
    pub last_rect: Rect,
    /// Whether Enter on an empty field submits (an optional field left
    /// blank) rather than waiting for a value.
    pub allow_blank: bool,
    /// The line under the field; `None` is the generic "Enter to confirm ยท
    /// Esc to cancel".
    pub hint: Option<String>,
    /// Draw the value as dots (a `"password": true` input, #1424).
    pub masked: bool,
    /// The whole value is selected (#1601): a prefilled value opens this
    /// way, as VS Code's input boxes do, so typing or pasting replaces it
    /// and Backspace clears it, where before every key appended to it.
    pub selected: bool,
    /// A yes/no question with no field (#855): Enter or Y answers yes, Esc
    /// or N no, and typing goes nowhere. A sentinel value in an editable
    /// field read as type-to-confirm, yet `no` + Enter still went ahead.
    pub confirm: bool,
    /// Where the terminal's caret goes in the field, set by a `surfaces`
    /// theme's render (which draws no caret of its own); `None` on a boxed
    /// theme, whose caret is a painted block, and for a confirm.
    pub last_caret: Option<(u16, u16)>,
}

impl InputPrompt {
    pub fn new(
        purpose: InputPurpose,
        title: impl Into<String>,
        placeholder: impl Into<String>,
    ) -> Self {
        Self {
            purpose,
            title: title.into(),
            placeholder: placeholder.into(),
            value: String::new(),
            cursor: 0,
            last_rect: Rect::default(),
            allow_blank: false,
            hint: None,
            masked: false,
            selected: false,
            confirm: false,
            last_caret: None,
        }
    }

    /// A yes/no question (#855): `title` asks it and `hint` says which keys
    /// answer it. Submitting carries an empty value.
    pub fn confirm(
        purpose: InputPurpose,
        title: impl Into<String>,
        hint: impl Into<String>,
    ) -> Self {
        Self {
            hint: Some(hint.into()),
            confirm: true,
            ..Self::new(purpose, title, "")
        }
    }

    /// Say under the field what Enter and Esc do, when it is more than
    /// confirm and cancel.
    pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
        self.hint = Some(hint.into());
        self
    }

    /// Draw the typed value as dots.
    pub fn masked(mut self) -> Self {
        self.masked = true;
        self
    }

    /// Let Enter submit an empty field, for a value that is optional.
    pub fn allowing_blank(mut self) -> Self {
        self.allow_blank = true;
        self
    }

    /// Seed the field with an initial value (e.g. the current branch name
    /// for a rename), caret at the end.
    pub fn with_value(mut self, value: impl Into<String>) -> Self {
        self.value = value.into();
        self.cursor = self.value.chars().count();
        self.selected = !self.value.is_empty();
        self
    }

    /// Select the whole value (Ctrl+A), caret at its end.
    pub fn select_all(&mut self) {
        self.cursor = self.char_count();
        self.selected = !self.value.is_empty();
    }

    /// Drop a selected value, for the key about to replace or delete it.
    /// True when there was one.
    fn take_selection(&mut self) -> bool {
        if !std::mem::take(&mut self.selected) {
            return false;
        }
        self.value.clear();
        self.cursor = 0;
        true
    }

    /// Delete from the start of the value to the caret (Ctrl+U).
    pub fn clear_to_start(&mut self) {
        if self.take_selection() {
            return;
        }
        let at = self.byte_offset(self.cursor);
        self.value.replace_range(..at, "");
        self.cursor = 0;
    }

    /// Delete from the caret to the end of the value (Ctrl+K).
    pub fn clear_to_end(&mut self) {
        if self.take_selection() {
            return;
        }
        let at = self.byte_offset(self.cursor);
        self.value.truncate(at);
    }

    /// Delete the word before the caret (Ctrl+W, Alt/Ctrl+Backspace): the
    /// separators after it, then back to the previous space or path
    /// separator, so `/a/b/c.txt` goes to `/a/b/`.
    pub fn delete_word_back(&mut self) {
        if self.take_selection() {
            return;
        }
        let chars: Vec<char> = self.value.chars().collect();
        let is_sep = |c: char| c.is_whitespace() || c == '/' || c == '\\';
        let mut start = self.cursor.min(chars.len());
        while start > 0 && is_sep(chars[start - 1]) {
            start -= 1;
        }
        while start > 0 && !is_sep(chars[start - 1]) {
            start -= 1;
        }
        let (from, to) = (self.byte_offset(start), self.byte_offset(self.cursor));
        self.value.replace_range(from..to, "");
        self.cursor = start;
    }

    fn char_count(&self) -> usize {
        self.value.chars().count()
    }

    fn byte_offset(&self, char_idx: usize) -> usize {
        self.value
            .char_indices()
            .nth(char_idx)
            .map(|(b, _)| b)
            .unwrap_or(self.value.len())
    }

    /// Type `c` at the caret; a confirm has no field, so it takes none.
    pub fn push_char(&mut self, c: char) {
        if self.confirm || c == '\n' || c == '\r' {
            return;
        }
        self.take_selection();
        let at = self.byte_offset(self.cursor);
        self.value.insert(at, c);
        self.cursor += 1;
    }

    pub fn pop_char(&mut self) {
        if self.take_selection() || self.cursor == 0 {
            return;
        }
        let at = self.byte_offset(self.cursor - 1);
        self.value.remove(at);
        self.cursor -= 1;
    }

    pub fn delete_char(&mut self) {
        if self.take_selection() || self.cursor >= self.char_count() {
            return;
        }
        let at = self.byte_offset(self.cursor);
        self.value.remove(at);
    }

    /// Left on a selected value goes to its start, as in a text field.
    pub fn move_cursor_left(&mut self) {
        self.cursor = match std::mem::take(&mut self.selected) {
            true => 0,
            false => self.cursor.saturating_sub(1),
        };
    }

    /// Right on a selected value goes to its end.
    pub fn move_cursor_right(&mut self) {
        self.cursor = match std::mem::take(&mut self.selected) {
            true => self.char_count(),
            false => (self.cursor + 1).min(self.char_count()),
        };
    }

    pub fn move_cursor_home(&mut self) {
        self.selected = false;
        self.cursor = 0;
    }

    pub fn move_cursor_end(&mut self) {
        self.selected = false;
        self.cursor = self.char_count();
    }

    /// The trimmed submitted value, or `None` when blank (Enter on an empty
    /// field is a no-op the caller treats as "keep waiting"). A confirm's
    /// answer is always the empty value.
    pub fn submit_value(&self) -> Option<String> {
        let v = self.value.trim();
        (self.allow_blank || self.confirm || !v.is_empty()).then(|| v.to_string())
    }
}

/// Where a field `width` cells wide starts showing `value` so the caret
/// at char `cursor` is in view (#1601): the chars skipped, and whether a
/// leading `โ€ฆ` takes the first cell to say so. Measured in terminal cells,
/// so wide (CJK) chars count as two.
pub(crate) fn field_scroll(value: &str, cursor: usize, width: usize) -> (usize, bool) {
    use unicode_width::UnicodeWidthChar;
    let cells: Vec<usize> = value.chars().map(|c| c.width().unwrap_or(0)).collect();
    let cursor = cursor.min(cells.len());
    // The caret's own cell: the char under it, or one blank past the end.
    let caret = cells.get(cursor).copied().unwrap_or(1).max(1);
    let before: usize = cells[..cursor].iter().sum();
    if width < 2 || before + caret <= width {
        return (0, false);
    }
    // `โ€ฆ`, then as many chars before the caret as fit, then the caret.
    let room = width.saturating_sub(1 + caret);
    let (mut skip, mut used) = (cursor, 0);
    while skip > 0 && used + cells[skip - 1] <= room {
        skip -= 1;
        used += cells[skip];
    }
    (skip, true)
}

pub fn render_input_prompt(
    prompt: &mut InputPrompt,
    screen: Rect,
    buf: &mut Buffer,
    theme: crate::theme::Theme,
) {
    if let Some(t) = crate::theme::tones(theme) {
        render_prompt_card(prompt, screen, buf, theme, t);
        return;
    }
    prompt.last_caret = None;
    let width = (screen.width.saturating_mul(6) / 10)
        .clamp(30, 90)
        .min(screen.width);
    // A confirm is the title and one line of keys: it has no field.
    let height: u16 = if prompt.confirm { 3 } else { 5 };
    let rect = Rect {
        x: screen.x + (screen.width.saturating_sub(width)) / 2,
        y: screen.y + (screen.height.saturating_sub(height)) / 3,
        width,
        height: height.min(screen.height),
    };
    prompt.last_rect = rect;
    Widget::render(Clear, rect, buf);
    let title = Span::styled(
        format!(" {} ", prompt.title),
        Style::default()
            .fg(theme.ui(Color::Rgb(0xff, 0xff, 0xff)))
            .add_modifier(Modifier::BOLD),
    );
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(theme.ui(Color::Rgb(0x4e, 0x9a, 0xff))))
        .title(title.clone())
        .style(Style::default().bg(theme.ui(Color::Rgb(0x16, 0x18, 0x1f))));
    let inner = Rect {
        x: rect.x + 2,
        y: rect.y + 1,
        width: rect.width.saturating_sub(4),
        height: rect.height.saturating_sub(2),
    };
    Widget::render(block, rect, buf);
    if theme.framed_overlays() {
        crate::widgets::surface::paint_overlay_frame(buf, rect, theme);
        // Clipped to the box like the block's own title: at full width it
        // ran past the border and the screen edge (#910).
        buf.set_span(rect.x + 1, rect.y, &title, rect.width.saturating_sub(2));
    }
    if inner.width == 0 || inner.height == 0 {
        return;
    }
    if prompt.confirm {
        buf.set_stringn(
            inner.x,
            inner.y,
            prompt.hint.as_deref().unwrap_or_default(),
            inner.width as usize,
            Style::default().fg(theme.ui(Color::Rgb(0xec, 0xef, 0xf4))),
        );
        return;
    }

    // Value row with a blinking caret, or the placeholder when empty.
    let value_y = inner.y;
    if prompt.value.is_empty() {
        buf.set_stringn(
            inner.x,
            value_y,
            &prompt.placeholder,
            inner.width as usize,
            Style::default()
                .fg(theme.ui(Color::Rgb(0x6c, 0x7d, 0x9c)))
                .add_modifier(Modifier::ITALIC),
        );
    } else {
        let shown = if prompt.masked {
            "โ€ข".repeat(prompt.value.chars().count())
        } else {
            prompt.value.clone()
        };
        let cursor = prompt.cursor.min(shown.chars().count());
        // The field scrolls to keep the caret in view (#1601): a value wider
        // than the box, any real path, hid its end and the caret, which
        // starts there. A `โ€ฆ` marks the hidden start.
        let (skip, lead) = field_scroll(&shown, cursor, inner.width as usize);
        let before: String = shown.chars().skip(skip).take(cursor - skip).collect();
        let at: String = shown.chars().skip(cursor).take(1).collect();
        let after: String = shown.chars().skip(cursor + 1).collect();
        let caret = if at.is_empty() { " ".to_string() } else { at };
        let mut value_style = Style::default().fg(theme.ui(Color::Rgb(0xec, 0xef, 0xf4)));
        if prompt.selected {
            value_style = value_style.bg(theme.ui(Color::Rgb(0x26, 0x4f, 0x78)));
        }
        let caret_style = Style::default()
            .fg(theme.ui(Color::Rgb(0x16, 0x18, 0x1f)))
            .bg(theme.ui(Color::Rgb(0xec, 0xef, 0xf4)))
            .add_modifier(Modifier::SLOW_BLINK);
        let dim = Style::default().fg(theme.ui(Color::Rgb(0x6c, 0x7d, 0x9c)));
        let line = Line::from(vec![
            Span::styled(if lead { "\u{2026}" } else { "" }, dim),
            Span::styled(before, value_style),
            Span::styled(caret, caret_style),
            Span::styled(after, value_style),
        ]);
        Widget::render(
            Paragraph::new(line),
            Rect {
                x: inner.x,
                y: value_y,
                width: inner.width,
                height: 1,
            },
            buf,
        );
    }

    if inner.height >= 3 {
        buf.set_stringn(
            inner.x,
            inner.y + 2,
            prompt
                .hint
                .as_deref()
                .unwrap_or("Enter to confirm ยท Esc to cancel"),
            inner.width as usize,
            Style::default().fg(theme.ui(Color::Rgb(0x7a, 0x82, 0x90))),
        );
    }
}

/// The prompt as a `surfaces` theme draws it, in the quick inputs' idiom:
/// a card with no title on its edge; the question as its one strong label;
/// the value in a field lifted off the card, with the terminal's own caret;
/// and the keys in a footer on the chrome tone. A confirm has the question
/// and the footer only.
fn render_prompt_card(
    prompt: &mut InputPrompt,
    screen: Rect,
    buf: &mut Buffer,
    theme: crate::theme::Theme,
    t: crate::theme::Tones,
) {
    let width = (screen.width.saturating_mul(6) / 10)
        .clamp(30, 90)
        .min(screen.width);
    // Edge, question, field, footer, edge; a confirm has no field.
    let height: u16 = if prompt.confirm { 4 } else { 5 };
    let rect = Rect {
        x: screen.x + (screen.width.saturating_sub(width)) / 2,
        y: screen.y + (screen.height.saturating_sub(height)) / 3,
        width,
        height: height.min(screen.height),
    };
    prompt.last_rect = rect;
    prompt.last_caret = None;
    if rect.width < 6 || rect.height < 3 || rect.intersection(buf.area) != rect {
        return;
    }
    Widget::render(Clear, rect, buf);
    buf.set_style(rect, Style::default().bg(t.raised()).fg(t.text()));
    let footer = (rect.height == height).then(|| rect.bottom() - 2);
    if let Some(fy) = footer {
        let tray = Rect {
            y: fy,
            height: 2,
            ..rect
        };
        buf.set_style(tray, Style::default().bg(t.chrome()));
    }
    crate::widgets::surface::paint_overlay_frame(buf, rect, theme);
    let (x0, end) = (rect.x + 2, rect.right() - 2);
    let room = usize::from(end - x0);
    let title_style = Style::default().fg(t.strong());
    let (cut, _) = buf.set_stringn(x0, rect.y + 1, &prompt.title, room, title_style);
    if prompt.title.width() > room {
        buf.set_string(cut.min(end - 1), rect.y + 1, "\u{2026}", title_style);
    }
    if let Some(fy) = footer {
        let key = Style::default().fg(t.text());
        let word = Style::default().fg(t.muted());
        let hint = match prompt.hint.as_deref() {
            Some(h) => Line::from(Span::styled(h, word)),
            None => Line::from(vec![
                Span::styled("\u{21b5}", key),
                Span::styled(" confirm   ", word),
                Span::styled("esc", key),
                Span::styled(" cancel", word),
            ]),
        };
        buf.set_line(x0, fy, &hint, end - x0);
    }
    if prompt.confirm || rect.height < 4 {
        return;
    }
    // The field: a step lifted off the card, the text one cell in.
    let field_y = rect.y + 2;
    let well = crate::gradient::lerp_rgb(t.raised, t.lift, 0.06);
    let field = Rect {
        x: x0,
        y: field_y,
        width: end - x0,
        height: 1,
    };
    buf.set_style(field, Style::default().bg(crate::gradient::rgb_color(well)));
    let (tx, tw) = (x0 + 1, usize::from(field.width.saturating_sub(2)));
    if tw == 0 {
        return;
    }
    if prompt.value.is_empty() {
        buf.set_stringn(
            tx,
            field_y,
            &prompt.placeholder,
            tw,
            Style::default()
                .fg(t.muted())
                .add_modifier(Modifier::ITALIC),
        );
        prompt.last_caret = Some((tx, field_y));
        return;
    }
    let shown = if prompt.masked {
        "\u{2022}".repeat(prompt.value.chars().count())
    } else {
        prompt.value.clone()
    };
    let cursor = prompt.cursor.min(shown.chars().count());
    let (skip, lead) = field_scroll(&shown, cursor, tw);
    let mut x = tx;
    if lead {
        buf.set_string(x, field_y, "\u{2026}", Style::default().fg(t.faint()));
        x += 1;
    }
    let mut value_style = Style::default().fg(t.text());
    if prompt.selected {
        value_style = value_style.bg(t.band_on(well));
    }
    let visible: String = shown.chars().skip(skip).collect();
    let before: String = shown.chars().skip(skip).take(cursor - skip).collect();
    let limit = usize::from((tx + u16::try_from(tw).unwrap_or(0)).saturating_sub(x));
    buf.set_stringn(x, field_y, &visible, limit, value_style);
    let caret = x + u16::try_from(before.width()).unwrap_or(u16::MAX);
    prompt.last_caret = Some((caret.min(end - 1), field_y));
}

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

    #[test]
    fn a_long_title_stays_inside_the_box_under_the_gradient_theme() {
        // #910: the gradient repaint drew the title at full width, past the
        // border and the screen edge, taking "unsaved edits" with it.
        let mut p = InputPrompt::new(
            InputPurpose::CreateTag,
            format!(
                "{} changed on disk and you have unsaved edits.",
                "x/".repeat(60)
            ),
            "",
        );
        let screen = Rect::new(0, 0, 80, 20);
        let mut buf = Buffer::empty(screen);
        render_input_prompt(&mut p, screen, &mut buf, crate::theme::Theme::BLACK);
        let r = p.last_rect;
        for x in r.x + r.width..screen.width {
            assert_eq!(buf[(x, r.y)].symbol(), " ", "column {x} of the title row");
        }
    }

    fn prefilled(value: &str) -> InputPrompt {
        InputPrompt::new(InputPurpose::CreateTag, "Tag", "name").with_value(value)
    }

    /// #1601: a prefilled value opens selected, so typing replaces it.
    #[test]
    fn typing_over_a_prefilled_value_replaces_it() {
        let mut p = prefilled("abc");
        assert!(p.selected);
        p.push_char('x');
        p.push_char('y');
        assert_eq!((p.value.as_str(), p.cursor), ("xy", 2));
    }

    /// #1601: Backspace or Delete on a selected value clears all of it.
    #[test]
    fn backspace_or_delete_clears_a_selected_value() {
        let mut p = prefilled("abc");
        p.pop_char();
        assert_eq!(p.value, "");
        let mut p = prefilled("abc");
        p.delete_char();
        assert_eq!(p.value, "");
    }

    /// #1601: Ctrl+U clears to the start and Ctrl+K to the end.
    #[test]
    fn clearing_to_the_start_or_the_end_of_the_value() {
        let mut p = prefilled("abcdef");
        p.move_cursor_left();
        for _ in 0..3 {
            p.move_cursor_right();
        }
        p.clear_to_start();
        assert_eq!((p.value.as_str(), p.cursor), ("def", 0));
        p.move_cursor_right();
        p.clear_to_end();
        assert_eq!((p.value.as_str(), p.cursor), ("d", 1));
        let mut p = prefilled("abc");
        p.clear_to_start();
        assert_eq!(p.value, "", "a selected value goes whole");
    }

    /// #1601: a word delete stops at a path separator.
    #[test]
    fn a_word_delete_goes_back_to_the_path_separator() {
        let mut p = prefilled("/a/b/c.txt");
        p.move_cursor_end();
        p.delete_word_back();
        assert_eq!(p.value, "/a/b/");
        p.delete_word_back();
        assert_eq!(p.value, "/a/");
        let mut p = prefilled("git tag v1");
        p.move_cursor_end();
        p.delete_word_back();
        assert_eq!(p.value, "git tag ");
    }

    /// #1601: Ctrl+A selects the value again after it was deselected.
    #[test]
    fn select_all_selects_the_value_again() {
        let mut p = prefilled("abc");
        p.move_cursor_end();
        assert!(!p.selected);
        p.select_all();
        p.push_char('z');
        assert_eq!(p.value, "z");
    }

    /// Negative (#1601): an arrow key deselects and keeps the value, so
    /// typing then edits it in place.
    #[test]
    fn an_arrow_key_keeps_a_prefilled_value_to_edit() {
        let mut p = prefilled("abc");
        p.move_cursor_left();
        p.push_char('x');
        assert_eq!(p.value, "xabc");
        let mut p = prefilled("abc");
        p.move_cursor_end();
        p.push_char('d');
        assert_eq!(p.value, "abcd");
    }

    /// Negative (#1601): an empty prompt is not selected; typing builds it.
    #[test]
    fn an_empty_prompt_types_as_before() {
        let mut p = InputPrompt::new(InputPurpose::CreateTag, "Tag", "name").with_value("");
        assert!(!p.selected);
        p.push_char('a');
        p.push_char('b');
        p.pop_char();
        assert_eq!(p.value, "a");
    }

    fn value_row(p: &mut InputPrompt, width: u16) -> String {
        let screen = Rect::new(0, 0, width, 12);
        let mut buf = Buffer::empty(screen);
        render_input_prompt(p, screen, &mut buf, crate::theme::Theme::BLACK);
        let r = p.last_rect;
        (r.x + 2..r.x + r.width - 2)
            .map(|x| buf[(x, r.y + 1)].symbol().to_string())
            .collect()
    }

    /// #1601: a value wider than the field scrolls to keep the caret, at
    /// its end, in view, with a `โ€ฆ` for the hidden start.
    #[test]
    fn a_long_value_scrolls_to_keep_the_caret_in_view() {
        let long = format!("/work/{}/end.code-workspace", "dir/".repeat(40));
        let mut p = prefilled(&long);
        let row = value_row(&mut p, 50);
        assert!(row.starts_with('\u{2026}'), "{row}");
        assert!(row.trim_end().ends_with("end.code-workspace"), "{row}");
        p.move_cursor_home();
        let row = value_row(&mut p, 50);
        assert!(row.starts_with("/work/dir/"), "{row}");
    }

    /// #1601: scrolling is measured in cells, so a value of wide chars
    /// that is fewer chars than the field but more cells still scrolls and
    /// keeps the end caret inside the field.
    #[test]
    fn a_wide_char_value_scrolls_by_display_width() {
        let mut p = prefilled(&"\u{4e2d}".repeat(20));
        let screen = Rect::new(0, 0, 50, 12);
        let mut buf = Buffer::empty(screen);
        render_input_prompt(&mut p, screen, &mut buf, crate::theme::Theme::BLACK);
        let r = p.last_rect;
        let (left, right) = (r.x + 2, r.x + r.width - 2);
        assert!(
            20 < right - left && right - left < 40,
            "field is {}",
            right - left
        );
        let caret = (left..right)
            .find(|&x| buf[(x, r.y + 1)].modifier.contains(Modifier::SLOW_BLINK))
            .expect("caret drawn inside the field");
        assert!(caret < right);
        assert_eq!(buf[(left, r.y + 1)].symbol(), "\u{2026}");
        p.move_cursor_home();
        assert!(value_row(&mut p, 50).starts_with('\u{4e2d}'));
    }

    /// Negative (#1601): a value that fits is drawn from its first char.
    #[test]
    fn a_short_value_is_drawn_whole() {
        let mut p = prefilled("v1.2.3");
        let row = value_row(&mut p, 50);
        assert!(row.starts_with("v1.2.3"), "{row}");
    }

    #[test]
    fn submit_value_trims_and_rejects_blank() {
        let mut p = InputPrompt::new(InputPurpose::CreateTag, "Tag", "name");
        assert_eq!(p.submit_value(), None);
        for c in "  v1  ".chars() {
            p.push_char(c);
        }
        assert_eq!(p.submit_value().as_deref(), Some("v1"));
    }

    #[test]
    fn with_value_seeds_text_and_caret_at_end() {
        let p =
            InputPrompt::new(InputPurpose::RenameBranch, "Rename", "new name").with_value("main");
        assert_eq!(p.value, "main");
        assert_eq!(p.cursor, 4);
    }

    #[test]
    fn cursor_edits_mid_string() {
        let mut p = InputPrompt::new(InputPurpose::CloneUrl, "Clone", "url");
        for c in "abc".chars() {
            p.push_char(c);
        }
        p.move_cursor_left();
        p.push_char('X');
        assert_eq!((p.value.as_str(), p.cursor), ("abXc", 3));
        p.pop_char();
        assert_eq!((p.value.as_str(), p.cursor), ("abc", 2));
        p.delete_char();
        assert_eq!(p.value.as_str(), "ab");
    }

    fn trash_confirm() -> InputPrompt {
        InputPrompt::confirm(
            InputPurpose::TreeDelete { paths: Vec::new() },
            "Move 'scratch.py' to Trash?",
            "Enter or Y to trash ยท Esc or N to keep",
        )
    }

    /// #855: a confirm takes nothing typed or pasted, so `no` cannot sit in
    /// a field that Enter then ignores; Enter answers with no value.
    #[test]
    fn a_confirm_has_no_field_to_type_into() {
        let mut p = trash_confirm();
        for c in "no".chars() {
            p.push_char(c);
        }
        assert_eq!(p.value, "");
        assert_eq!(p.submit_value().as_deref(), Some(""));
    }

    fn loch_prompt(p: &mut InputPrompt) -> Buffer {
        let screen = Rect::new(0, 0, 80, 20);
        let mut buf = Buffer::empty(screen);
        render_input_prompt(p, screen, &mut buf, crate::theme::Theme::from_id("loch"));
        buf
    }

    fn line(buf: &Buffer, r: Rect, y: u16) -> String {
        (r.x..r.right())
            .map(|x| buf[(x, y)].symbol().to_string())
            .collect()
    }

    /// Croft Loch: the question is a label inside the card, not a title on
    /// its edge; the value sits in a lifted field with the terminal's caret
    /// at its end (no painted block); the keys are in a footer on chrome.
    #[test]
    fn croft_loch_prompt_is_a_card_with_a_field_and_a_footer() {
        let t = crate::theme::tones(crate::theme::Theme::from_id("loch")).unwrap();
        let mut p = prefilled("v1.2");
        let buf = loch_prompt(&mut p);
        let r = p.last_rect;
        assert!(!line(&buf, r, r.y).contains("Tag"), "no title on the edge");
        assert!(line(&buf, r, r.y + 1).contains("Tag"));
        assert_eq!(buf[(r.x + 2, r.y + 1)].fg, t.strong());
        let field = line(&buf, r, r.y + 2);
        assert!(field.contains(" v1.2"), "{field:?}");
        assert_ne!(buf[(r.x + 2, r.y + 2)].bg, t.raised(), "a lifted field");
        assert_eq!(p.last_caret, Some((r.x + 7, r.y + 2)));
        let blinking = (r.y..r.bottom())
            .any(|y| (r.x..r.right()).any(|x| buf[(x, y)].modifier.contains(Modifier::SLOW_BLINK)));
        assert!(!blinking, "no painted caret");
        let footer = line(&buf, r, r.y + 3);
        assert!(
            footer.contains("\u{21b5} confirm   esc cancel"),
            "{footer:?}"
        );
        assert_eq!(buf[(r.x + 2, r.y + 3)].bg, t.chrome());
        let mut empty = InputPrompt::new(InputPurpose::CreateTag, "Tag", "name");
        let buf = loch_prompt(&mut empty);
        let r = empty.last_rect;
        assert!(line(&buf, r, r.y + 2).contains(" name"));
        assert!(buf[(r.x + 3, r.y + 2)].modifier.contains(Modifier::ITALIC));
        assert_eq!(empty.last_caret, Some((r.x + 3, r.y + 2)));
    }

    /// Croft Loch: a confirm is the question and its keys, with no field
    /// and no caret.
    #[test]
    fn croft_loch_confirm_asks_and_lists_its_keys() {
        let mut p = trash_confirm();
        let buf = loch_prompt(&mut p);
        let r = p.last_rect;
        assert_eq!(r.height, 4);
        assert!(line(&buf, r, r.y + 1).contains("Move 'scratch.py' to Trash?"));
        assert!(line(&buf, r, r.y + 2).contains("Enter or Y to trash"));
        assert_eq!(p.last_caret, None);
    }

    /// #855: the box shows which keys answer it, where the prefilled value
    /// hid that hint, and draws no caret.
    #[test]
    fn a_confirm_draws_its_keys_and_no_caret() {
        let mut p = trash_confirm();
        let screen = Rect::new(0, 0, 80, 12);
        let mut buf = Buffer::empty(screen);
        render_input_prompt(&mut p, screen, &mut buf, crate::theme::Theme::BLACK);
        let r = p.last_rect;
        assert_eq!(r.height, 3, "the title and one line of keys");
        let row: String = (r.x + 2..r.x + r.width - 2)
            .map(|x| buf[(x, r.y + 1)].symbol().to_string())
            .collect();
        assert!(
            row.starts_with("Enter or Y to trash ยท Esc or N to keep"),
            "{row}"
        );
        let caret = (r.y..r.y + r.height).any(|y| {
            (r.x..r.x + r.width).any(|x| buf[(x, y)].modifier.contains(Modifier::SLOW_BLINK))
        });
        assert!(!caret, "a confirm has no caret");
    }
}