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
//! Bookmarks: set/jump leader state and the bookmark-list overlay — methods on `App`.
use super::*;
impl App {
// --- ブックマーク (M7 補助) ----------------------------------------------
/// Whether we are waiting for an alphabetic key after `m` (while true, main intercepts keys).
pub fn is_marking(&self) -> bool {
self.mark_set_pending
}
/// `m`=enter set mode (the next letter registers; scope = letter case).
pub fn start_mark_set(&mut self) {
self.mark_set_pending = true;
}
/// Cancel the mark wait (Esc or a non-applicable key).
pub fn cancel_mark(&mut self) {
self.mark_set_pending = false;
}
/// The one key after `m`: register the cursor item (or the current root) under that letter.
/// If `ui.confirm_bookmark_overwrite` is on and the letter already points to a **different** path,
/// open a yes/no confirmation dialog instead of overwriting silently.
pub fn mark_input(&mut self, c: char) {
if !std::mem::take(&mut self.mark_set_pending) {
return;
}
if !c.is_ascii_alphabetic() {
self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::InvalidMarkKey).into());
return;
}
let target = self.bookmark_target();
// 上書き確認: 既にそのキーが**別のパス**に割り当て済みで、確認が有効なら、直に上書きせず
// 確認ダイアログを出す(同じパスの再登録・未使用キーは無条件で登録=無駄な確認を出さない)。
if self.cfg.ui.confirm_bookmark_overwrite {
if let Some(existing) = self.bookmarks.get(c) {
if existing != target {
let msg = format!(
"{} {c}\n{}\n → {}",
crate::i18n::tr(self.lang, crate::i18n::Msg::BookmarkOverwriteConfirm),
self.bookmark_display_path(c.is_ascii_lowercase(), &existing),
self.bookmark_display_path(c.is_ascii_lowercase(), &target),
);
self.dialog = Some(Dialog {
op: PendingOp::BookmarkOverwrite { key: c, target },
kind: DialogKind::Confirm {
message: msg,
allow_permanent: false,
},
});
return;
}
}
}
self.perform_mark_set(c, target);
}
/// Actually write the bookmark under `c` and flash the result. Used by `mark_input` directly (no
/// overwrite / confirm off) and by the overwrite confirmation (`dialog_confirm`).
pub(super) fn perform_mark_set(&mut self, c: char, target: std::path::PathBuf) {
match self.bookmarks.set(c, target.clone()) {
Ok(_) => {
let scope = if c.is_ascii_uppercase() {
crate::i18n::tr(self.lang, crate::i18n::Msg::GlobalApp)
} else {
crate::i18n::tr(self.lang, crate::i18n::Msg::Local)
};
self.flash = Some(format!(
"{} {c} = {} [{scope}]",
crate::i18n::tr(self.lang, crate::i18n::Msg::Bookmarked),
self.bookmark_display_path(c.is_ascii_lowercase(), &target),
));
}
// 保存失敗: メモリ上には登録済みだが再起動で消える旨を通知(握り潰さない)。
Err(e) => {
self.flash = Some(format!(
"{}{e}",
crate::i18n::tr(self.lang, crate::i18n::Msg::OperationFailed)
));
}
}
}
/// What `m` registers: the previewed file in Preview mode, otherwise the tree cursor entry
/// (fallback: the current root). Preview mode's tree cursor can lag behind the shown file
/// (bookmark jumps / follow mode open previews without moving it), so the shown file wins.
fn bookmark_target(&self) -> std::path::PathBuf {
if matches!(self.mode, Mode::Preview) {
if let Some(p) = &self.preview_path {
return p.clone();
}
}
self.entries
.get(self.selected)
.map(|e| e.path.clone())
.unwrap_or_else(|| self.root.clone())
}
/// Display form for a bookmark target. Local marks show the contextual (relative-style) path;
/// global marks always show their absolute location (`~`-shortened) — a global target usually
/// lives outside the current tree, where a relative `../../...` rendering is unreadable.
pub fn bookmark_display_path(&self, is_local: bool, path: &std::path::Path) -> String {
if is_local {
self.format_path(path)
} else {
home_relative(path)
}
}
/// A plain letter inside the bookmark list (`'` opens it): jump straight to that bookmark
/// (a-z local / A-Z global; dir=new root / file=preview). Unknown letters just flash and the
/// list stays open. Keys claimed by the list/global keymap (j/k/q, tab keys …) never reach here.
pub fn bookmark_jump_letter(&mut self, c: char) {
match self.bookmarks.get(c) {
Some(p) if p.is_dir() => {
self.close_bookmark_list();
self.jump_to_dir(p);
}
Some(p) if p.is_file() => {
self.close_bookmark_list();
self.enter_preview(&p);
}
Some(p) => {
self.flash = Some(format!(
"{}: {}",
crate::i18n::tr(self.lang, crate::i18n::Msg::BookmarkTargetMissing),
self.bookmark_display_path(c.is_ascii_lowercase(), &p)
))
}
None => {
self.flash = Some(format!(
"{} '{c}'",
crate::i18n::tr(self.lang, crate::i18n::Msg::NoBookmark)
))
}
}
}
/// Make the bookmark target (a directory) the new root and show the Tree. Does not change open_dir (the local key).
pub(super) fn jump_to_dir(&mut self, dir: std::path::PathBuf) {
// root を変えるので旧 root の選択/ビジュアル/絞り込み/検索を破棄する(持ち越すと
// マーカー不可視のまま旧 root のファイルが誤操作対象になる footgun)。
self.clear_for_root_change();
self.root = dir;
self.entries.clear();
self.selected = 0;
self.rebuild_tree_notify();
self.mode = Mode::Tree;
self.preview_path = None;
self.preview_kind = None;
}
/// `:`=make the current location the "anchored root" (**no text input**). Re-anchors the current tree root,
/// navigated to with `h`/`l`, to the display base (open_dir), so relative-path display, the `yr` path copy, and
/// the title all become relative to the current location (resolving what used to show as `../` from launch). Leaves the tree structure and cursor unchanged.
pub fn reanchor_root(&mut self) {
if self.open_dir == self.root {
self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::AlreadyRoot).into());
return;
}
self.open_dir = self.root.clone();
self.flash = Some(format!(
"{}: {}",
crate::i18n::tr(self.lang, crate::i18n::Msg::Root),
home_relative(&self.root)
));
}
/// `A`=reset the anchor (display base = open_dir) back to the **launch dir** (the counterpart of reanchor_root=`a`).
/// Resets the anchor that `a` moved to the current location back to the startup position, restoring relative-path display.
/// Leaves the tree structure / cursor / root unchanged (moves only open_dir, symmetric to reanchor_root).
pub fn reset_anchor(&mut self) {
if self.open_dir == self.launch_dir {
self.flash =
Some(crate::i18n::tr(self.lang, crate::i18n::Msg::AlreadyAtStartDir).into());
return;
}
self.open_dir = self.launch_dir.clone();
self.flash = Some(format!(
"{}: {}",
crate::i18n::tr(self.lang, crate::i18n::Msg::AnchorReset),
home_relative(&self.launch_dir)
));
}
// --- ブックマーク一覧オーバーレイ ----------------------------------------
pub fn is_bookmark_list(&self) -> bool {
self.bookmark_list
}
pub fn open_bookmark_list(&mut self) {
self.bookmark_list = true;
self.bookmark_list_sel = 0;
}
pub fn close_bookmark_list(&mut self) {
self.bookmark_list = false;
}
pub fn bookmark_list_sel(&self) -> usize {
self.bookmark_list_sel
}
/// List items (is_local, key, path). Local first, then global.
pub fn bookmark_list_items(&self) -> Vec<(bool, char, std::path::PathBuf)> {
let (local, global) = self.bookmarks.list();
let mut v = Vec::with_capacity(local.len() + global.len());
for (k, p) in local {
v.push((true, k, p));
}
for (k, p) in global {
v.push((false, k, p));
}
v
}
pub fn bookmark_list_move(&mut self, delta: i32) {
let n = self.bookmark_list_items().len();
if n == 0 {
return;
}
self.bookmark_list_sel =
(self.bookmark_list_sel as i32 + delta).rem_euclid(n as i32) as usize;
}
/// Jump to the selected bookmark (closes the list).
pub fn bookmark_list_jump(&mut self) {
let items = self.bookmark_list_items();
if let Some((is_local, _, p)) = items.get(self.bookmark_list_sel).cloned() {
self.bookmark_list = false;
if p.is_dir() {
self.jump_to_dir(p);
} else if p.is_file() {
self.enter_preview(&p); // ファイルはプレビューで開く(tree は変えない)
} else {
self.flash = Some(format!(
"{}: {}",
crate::i18n::tr(self.lang, crate::i18n::Msg::BookmarkTargetMissing),
self.bookmark_display_path(is_local, &p)
));
}
}
}
/// If the selected list item is a file, **open it directly in the editor** without going through the preview
/// (closes the list and sets pending_edit; the run loop launches run_editor). Directories cannot be edited and flash.
pub fn bookmark_list_edit(&mut self) {
let items = self.bookmark_list_items();
if let Some((is_local, _, p)) = items.get(self.bookmark_list_sel).cloned() {
if p.is_file() {
self.bookmark_list = false;
self.pending_edit = Some((p, None));
} else if p.is_dir() {
self.flash =
Some(crate::i18n::tr(self.lang, crate::i18n::Msg::CannotEditDirectory).into());
} else {
self.flash = Some(format!(
"{}: {}",
crate::i18n::tr(self.lang, crate::i18n::Msg::BookmarkTargetMissing),
self.bookmark_display_path(is_local, &p)
));
}
}
}
/// Delete the selected bookmark (the list stays open; the selection is clamped).
pub fn bookmark_list_delete(&mut self) {
let items = self.bookmark_list_items();
if let Some((_, key, _)) = items.get(self.bookmark_list_sel) {
let key = *key;
if let Err(e) = self.bookmarks.remove(key) {
self.flash = Some(format!(
"{}{e}",
crate::i18n::tr(self.lang, crate::i18n::Msg::OperationFailed)
));
}
let n = self.bookmark_list_items().len();
if self.bookmark_list_sel >= n {
self.bookmark_list_sel = n.saturating_sub(1);
}
}
}
/// Start filtering (`/`). Recursively collects everything under root into a pool and enters input mode.
pub fn start_filter(&mut self) {
self.filter_pool = collect_all(&self.root, self.show_hidden);
self.filter_input = Some(String::new());
self.tree_filter = Some(String::new());
self.selected = 0;
self.reapply_filter();
}
/// Add one character to the filter input (live filtering).
pub fn filter_input_push(&mut self, c: char) {
if let Some(q) = self.filter_input.as_mut() {
q.push(c);
}
self.tree_filter = self.filter_input.clone();
self.reapply_filter();
}
/// Delete one character from the filter input.
pub fn filter_input_backspace(&mut self) {
if let Some(q) = self.filter_input.as_mut() {
q.pop();
}
self.tree_filter = self.filter_input.clone();
self.reapply_filter();
}
/// Commit input (Enter): leave editing but keep the filtered results (navigate normally afterwards).
pub fn filter_commit(&mut self) {
self.filter_input = None;
}
/// Clear the filter (Esc): return to the normal tree.
pub fn filter_clear(&mut self) {
self.clear_filter_state();
self.selected = 0;
self.rebuild_tree_notify();
}
/// Discard the filter state (input/query/pool and the changed-files filter) (does not rebuild the tree).
pub(super) fn clear_filter_state(&mut self) {
self.filter_input = None;
self.tree_filter = None;
self.filter_pool = Vec::new();
self.changed_filter = false;
}
/// Whether input mode (key interception) is active.
pub fn is_filtering(&self) -> bool {
self.filter_input.is_some()
}
/// The query while a filter is applied (including after the input is committed). Used for title / relative-path display.
pub fn filter_query(&self) -> Option<&str> {
self.tree_filter.as_deref()
}
/// Filter the pool by the current query (substring match, case-insensitive) to build entries.
/// When the query is empty (= right after pressing `/`, before typing any character), **show nothing**
/// (avoiding a flat display of everything, which would look like "expand all").
fn reapply_filter(&mut self) {
let q = self.tree_filter.clone().unwrap_or_default().to_lowercase();
self.entries = if q.is_empty() {
Vec::new()
} else {
self.filter_pool
.iter()
.filter(|e| {
e.path
.file_name()
.and_then(|n| n.to_str())
.map(|n| n.to_lowercase().contains(&q))
.unwrap_or(false)
})
.cloned()
.collect()
};
if self.selected >= self.entries.len() {
self.selected = self.entries.len().saturating_sub(1);
}
// 絞り込み結果は別 entries 集合なので visual_anchor(添字)は stale。無効化する。
self.visual_anchor = None;
}
// --- 変更ファイルのみフィルタ (`C`) + 変更間ジャンプ (`n`/`N`) — Agent Watch ① ----------
/// Whether the changed-files-only tree filter is active (drives the flat relative-path rendering).
pub fn changed_filter(&self) -> bool {
self.changed_filter
}
/// The sorted list of files with a git status under the current root (the review work-list).
/// Deleted files have a status but no longer exist, so they are excluded (nothing to preview/select).
fn changed_paths(&self) -> Vec<PathBuf> {
let mut v: Vec<PathBuf> = self
.git_status
.keys()
.filter(|p| p.starts_with(&self.root) && p.is_file())
.cloned()
.collect();
v.sort();
v
}
/// `C`: toggle the changed-files-only view. ON shows the flat list of changed files (like the `/`
/// filter's result list — review them top to bottom); OFF returns to the normal tree. When there is
/// no change, stays on the tree with a flash (never trap the user in an empty list).
pub fn toggle_changed_filter(&mut self) {
if self.changed_filter {
self.changed_filter = false;
self.selected = 0;
self.rebuild_tree_notify();
return;
}
self.ensure_git_status_now(); // `C` は status から答えを出す=走行中なら待つ(偽の「変更なし」を出さない)
if self.changed_paths().is_empty() {
self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoChangedFiles).into());
return;
}
self.clear_filter_state(); // 名前絞り込み(`/`)とは排他
self.changed_filter = true;
self.selected = 0;
self.reapply_changed_filter();
}
/// Rebuild entries as the flat changed-files list. Called on toggle and by `refresh_fs` while active
/// (an agent committing/reverting updates the list live). Auto-exits to the tree when the last change
/// disappears (e.g. everything was committed) instead of leaving an empty list.
pub(super) fn reapply_changed_filter(&mut self) {
let entries: Vec<super::Entry> = self
.changed_paths()
.into_iter()
.map(|path| super::Entry {
path,
is_dir: false,
depth: 0,
expanded: false,
})
.collect();
if entries.is_empty() {
self.changed_filter = false;
self.selected = 0;
self.rebuild_tree_notify();
self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoChangedFiles).into());
return;
}
self.entries = entries;
if self.selected >= self.entries.len() {
self.selected = self.entries.len().saturating_sub(1);
}
self.visual_anchor = None;
}
/// `n`/`N` on the tree: jump the cursor to the next/previous changed file in path order (wraps).
/// In the normal tree the target is revealed (collapsed ancestors expanded); in the changed-only
/// filter it moves within the flat list.
pub fn jump_changed(&mut self, dir: i64) {
// diff ビュー表示中は「次/前の変更ファイルの diff へ切替」= ビューを出ずに変更を回遊する
// (hunk/lazygit 流のレビュー動線)。ツリーでは従来どおりカーソルジャンプ。
if self.is_git_diff_preview() {
self.diff_jump_changed(dir);
return;
}
self.ensure_git_status_now(); // `n`/`N` も status から答えを出す
let paths = self.changed_paths();
if paths.is_empty() {
self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoChangedFiles).into());
return;
}
let len = paths.len() as i64;
let idx = match self.entries.get(self.selected).map(|e| e.path.clone()) {
Some(cur) => match paths.binary_search(&cur) {
Ok(i) => (i as i64 + dir).rem_euclid(len) as usize,
// カーソルが変更ファイル上にない: 挿入位置の次(前)へ(wrap)。
Err(ins) => {
if dir > 0 {
(ins as i64).rem_euclid(len) as usize
} else {
(ins as i64 - 1).rem_euclid(len) as usize
}
}
},
None => 0,
};
let target = paths[idx].clone();
if self.changed_filter {
if let Some(i) = self.entries.iter().position(|e| e.path == target) {
self.selected = i;
}
return;
}
match self.reveal_path_deep(&target) {
Ok(true) => {}
// 対象が隠しディレクトリ配下などで可視化できない(`.` で隠し表示に切替すれば届く)。
Ok(false) => {
self.flash =
Some(crate::i18n::tr(self.lang, crate::i18n::Msg::JumpTargetHidden).into());
}
Err(e) => {
self.flash = Some(format!(
"{}{e}",
crate::i18n::tr(self.lang, crate::i18n::Msg::OperationFailed)
));
}
}
}
/// `n`/`N` inside the GitDiff preview: switch the diff target to the next/previous changed file
/// (wraps) without leaving the view. **Scope depends on how the diff was opened**: a follow-opened
/// diff cycles only the files changed during the current follow session ("what just changed"),
/// while a tree-/hub-opened diff cycles the full uncommitted change set. The tree cursor follows
/// (so `q` lands on the file just reviewed), and where `q` returns to (hub vs tree) is preserved.
fn diff_jump_changed(&mut self, dir: i64) {
let paths = if self.diff_follow_scope {
self.follow_session_paths()
} else {
self.ensure_git_status_now();
self.changed_paths()
};
if paths.is_empty() {
self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoChangedFiles).into());
return;
}
let Some(crate::preview::PreviewKind::GitDiff(cur)) = self.preview_kind.clone() else {
return;
};
let len = paths.len() as i64;
let idx = match paths.iter().position(|p| *p == cur) {
Some(i) => (i as i64 + dir).rem_euclid(len) as usize,
// 表示中ファイルが集合に無い(直前にコミットされた等): 先頭/末尾から。
None => {
if dir > 0 {
0
} else {
(len - 1) as usize
}
}
};
let target = paths[idx].clone();
if target == cur {
return; // 対象が1つだけ
}
// ツリーのカーソルも同期(q で戻ったとき、いま見ていたファイルの上に居る)。
if self.changed_filter {
self.reapply_changed_filter();
if let Some(i) = self.entries.iter().position(|e| e.path == target) {
self.selected = i;
}
} else {
let _ = self.reveal_path_deep(&target);
}
// open_git_diff は came_from_git_view / diff_follow_scope を初期化するため保存/復元する
// (ハブ経由の diff から回遊しても q でハブへ戻れる・フォロースコープの回遊が続く)。
let came = self.came_from_git_view;
let scope = self.diff_follow_scope;
self.open_git_diff(&target);
self.came_from_git_view = came;
self.diff_follow_scope = scope;
}
/// The follow session's reviewable files (recorded while `F` was ON), pruned to still-existing
/// non-media files. First-change order (chronological — the review order of "what just happened").
fn follow_session_paths(&self) -> Vec<PathBuf> {
self.follow_session
.iter()
.filter(|p| p.is_file() && !self.follow_is_media(p))
.cloned()
.collect()
}
/// The current GitDiff target's position within its navigation set (1-based, total) — the follow
/// session for follow-opened diffs, the full change set otherwise. For the title's `(2/5)` indicator.
pub fn diff_change_position(&self) -> Option<(usize, usize)> {
let crate::preview::PreviewKind::GitDiff(p) = self.preview_kind.as_ref()? else {
return None;
};
let paths = if self.diff_follow_scope {
self.follow_session_paths()
} else {
self.changed_paths()
};
let i = paths.iter().position(|q| q == p)?;
Some((i + 1, paths.len()))
}
/// Refetch git status if root changed (called just before rendering). Does nothing if root is unchanged.
/// As a result, expand/collapse does not refetch; updates happen only on directory moves and tab switches.
///
/// The cheap `statuses`+`branch` (tens of ms, within the <60ms budget) is refetched synchronously, but the
/// **heavy `ignored` (~800ms on large repos) is offloaded to a separate thread** (the "don't block the UI" principle). Rendering stays responsive, and
/// only the dimming based on ignore rules appears after the result arrives (`apply_ignored`).
pub fn refresh_git_if_needed(&mut self) {
// 同一 root かつ dirty でなければ何もしない。dirty(再検証要求)は同一 root でも取り直す。
if self.git_status_for.as_deref() == Some(self.root.as_path()) && !self.git_status_dirty {
return;
}
let wd = crate::git::workdir(&self.root);
// statuses/branch は **workdir から** `git status` を回す=同一リポジトリ内ならどのサブディレクトリでも
// 結果は同一。よって **workdir が同じで dirty でなければ再計算せず流用**する(`l`/`h` 潜行のたびに
// 全 worktree を走査する `git status` が同期実行されるのを回避=大 repo での h/l の重さの主因)。
// dirty(ファイル変更/コミット/チェックアウト/無視ルール変更)や別 repo への移動時のみ取り直す。
// ignored の Phase G(workdir 単位キャッシュ)と同型。
let status_reusable = self.git_status_workdir.is_some()
&& self.git_status_workdir == wd
&& !self.git_status_dirty;
if status_reusable {
// 同一 repo かつ再検証要求なし: 既存の status をそのまま流用する(`l`/`h` 潜行の最適化)。
self.git_status_for = Some(self.root.clone());
} else {
// フル `git status`(全 worktree 走査)は**別スレッドへ**逃がす。到着まで直前の status を
// 見せ続けるので、ツリーは即座に描ける(原則「UI をブロックしない」)。
self.kick_status_refresh(wd.clone());
}
self.refresh_ignored_if_needed(wd);
}
/// The `ignored` half of `refresh_git_if_needed`, split out so the synchronous
/// `ensure_git_status_now` can reuse it without also going through the async status dispatch.
fn refresh_ignored_if_needed(&mut self, wd: Option<PathBuf>) {
// 重い ignored(無視セット)は **repo(workdir)が変わった時だけ** 作り直す。同一リポジトリ内の
// サブディレクトリへ潜っても無視ルールは同一なので流用する(`l` 潜行時の再計算を回避)。
let different_repo = self.git_ignored_for != wd;
let need = self.git_ignored_dirty || different_repo;
// 同一 workdir の計算が既に走行中なら待つ(無視ルール変更 dirty の時はそれより新しい結果が要る)。
// `is_some()` が要る: repo でない root では `wd` も `git_ignored_pending` も None なので、
// それ無しでは「計算中」が**常に成立**して早期 return し、下の None 分岐(前の repo の
// 無視セットを捨てる処理)へ永久に到達しなかった。計算が走るのは必ず実在の workdir に対してだけ。
let inflight = self.git_ignored_pending.is_some()
&& self.git_ignored_pending == wd
&& !self.git_ignored_dirty;
if !need || inflight {
return;
}
match wd {
None => {
// repo でない: 即クリア(計算不要)。
self.git_ignored.clear();
self.git_ignored_for = None;
self.git_ignored_pending = None;
self.git_ignored_dirty = false;
}
Some(wd) => {
// 別 repo へ移った時だけ旧セットを消す(暗転の混在を防ぐ)。無視ルール変更(dirty)で
// 同一 repo を作り直す時は、新セット到着まで旧セットを見せ続ける(チラつき回避)。
if different_repo {
self.git_ignored.clear();
self.git_ignored_for = None;
}
self.git_ignored_gen = self.git_ignored_gen.wrapping_add(1);
self.git_ignored_pending = Some(wd.clone());
self.git_ignored_dirty = false;
let gen = self.git_ignored_gen;
self.spawn_or_sync_ignored(self.root.clone(), wd, gen);
}
}
}
/// Attach the Sender of the worker that computes `ignored` in the background (called by main at startup).
pub fn attach_git_loader(&mut self, tx: std::sync::mpsc::Sender<IgnoredResult>) {
self.ignored_tx = Some(tx);
}
/// Attach the Sender of the worker that computes `statuses`+`branch` in the background (called by main at startup).
pub fn attach_status_loader(&mut self, tx: std::sync::mpsc::Sender<crate::app::StatusResult>) {
self.status_tx = Some(tx);
}
/// Request a `git status` refresh for the current root, **without blocking**.
///
/// Within the same repository the previous statuses are deliberately **kept on screen until the new
/// ones arrive**: entries are keyed by absolute path, so nothing shifts under the cursor and the
/// markers don't blink off on every root/tab change. Moving to a **different repo** does clear them,
/// because `git_branch` (the tree title) and `git_has_changes()` (the gutter column) are *not*
/// path-keyed and would otherwise show the previous repository's branch for the length of a scan.
fn kick_status_refresh(&mut self, wd: Option<PathBuf>) {
// 同一 root のスキャンが既に走行中なら **新たに spawn しない**。再検証要求(dirty)は立てたまま
// 残し、結果到着時(`apply_statuses`)に1回だけ引き継いで再実行する = **要求の合体**。
// 同期実行だった頃はスキャン所要時間が次の要求を自然に律速していたが、非同期化でその律速が
// 消えるため、ここで合体させないと fs イベント毎に全 worktree 走査が積み上がる
// (エージェントが書き続ける大 repo ほど悪化する = この修正が狙った状況そのもの)。
if self.git_status_pending.as_deref() == Some(self.root.as_path()) {
return;
}
// 別 repo へ移ったら、パスキーでない派生表示(ブランチ名/ガター列の有無)が前の repo のまま
// 残らないよう捨てる。同一 repo 内(`l`/`h`)ではここを通らないのでチラつかない。
if self.git_status_workdir != wd {
self.git_status.clear();
self.git_branch = None;
self.git_status_workdir = None;
}
self.git_status_gen = self.git_status_gen.wrapping_add(1);
self.git_status_pending = Some(self.root.clone());
// 要求はこの世代の計算が引き受けた。以後の再検証要求は次の世代で拾う。
self.git_status_dirty = false;
// 「この root の status を持っている/取得中」の印。これを進めておかないと、結果が届くまで
// 毎描画で kick し直してしまう(上の inflight ガードと二重防御)。
self.git_status_for = Some(self.root.clone());
let gen = self.git_status_gen;
let root = self.root.clone();
self.spawn_or_sync_statuses(root, wd, gen);
}
/// Compute `statuses`+`branch` on a separate thread and return them via the Sender. With no Sender attached
/// (tests / no channel), fall back to **synchronous** computation and application, so unit tests that don't
/// drive a run loop still observe the result immediately (same contract as `spawn_or_sync_ignored`).
fn spawn_or_sync_statuses(&mut self, root: PathBuf, workdir: Option<PathBuf>, gen: u64) {
// repo でない(no-git ビルド含む)なら結果は自明に空。スレッドを起こさず即座に確定させる。
if workdir.is_none() {
let res = crate::app::StatusResult {
gen,
statuses: Default::default(),
branch: None,
workdir,
};
self.apply_statuses(res);
return;
}
let Some(tx) = self.status_tx.clone() else {
let res = Self::scan_statuses(root, workdir, gen);
self.apply_statuses(res);
return;
};
std::thread::spawn(move || {
// ワーカーが panic すると結果が返らず `git_status_pending` が永久に残り、スピナーが
// 回り続け status も凍結する。他のワーカーと同じ安全網で必ず結果を返す(原則#3)。
if let Some(res) =
crate::preview::markdown::catch_silent(|| Self::scan_statuses(root, workdir, gen))
{
let _ = tx.send(res);
}
});
}
/// The actual scan (pure: no `&self`), shared by the worker thread and the synchronous fallbacks.
fn scan_statuses(
root: PathBuf,
workdir: Option<PathBuf>,
gen: u64,
) -> crate::app::StatusResult {
crate::app::StatusResult {
gen,
statuses: crate::git::statuses(&root),
branch: crate::git::branch(&root),
workdir,
}
}
/// Guarantee `git_status`/`git_branch` describe the working tree **right now**, computing synchronously
/// if a background scan is still in flight.
///
/// The two paths have deliberately different contracts:
/// - `refresh_git_if_needed` = the **render path**. Never blocks; a stale frame is fine because the
/// result lands a moment later and repaints.
/// - this = an **explicit user command** whose answer is derived from the status (`d` open diff,
/// `C` changed-only filter, `n`/`N` jump to change, the branch label right after a checkout).
/// These must not answer "no changes" just because a scan hasn't finished — that reads as a broken
/// feature rather than a slow one.
pub fn ensure_git_status_now(&mut self) {
let wd = crate::git::workdir(&self.root);
// 走行中でなく、同一 repo の最新を既に持っているなら何もしない(`l`/`h` の流用と同じ判定)。
let fresh = self.git_status_pending.is_none()
&& self.git_status_workdir.is_some()
&& self.git_status_workdir == wd
&& !self.git_status_dirty;
if fresh {
self.git_status_for = Some(self.root.clone());
} else {
// ここでは**別スレッドへ投げない**。投げてから同期計算すると、捨てるだけのフル走査を
// 1本余計に走らせることになる(大 repo ほど無駄が大きい)。世代を進めることで、既に
// 走行中だったスキャンの結果は届いても破棄される。
self.git_status_gen = self.git_status_gen.wrapping_add(1);
self.git_status_dirty = false;
self.git_status_pending = None;
let res = Self::scan_statuses(self.root.clone(), wd.clone(), self.git_status_gen);
self.apply_statuses(res);
}
self.refresh_ignored_if_needed(wd);
}
/// Apply a `statuses` result from the other thread. Discards results whose generation is stale (the user
/// moved to another root/tab while it was computing). Returns true if state changed (the caller redraws).
pub fn apply_statuses(&mut self, res: crate::app::StatusResult) -> bool {
if res.gen != self.git_status_gen {
return false; // 陳腐化: 既に別 root/タブへ移っている
}
self.git_status = res.statuses;
self.git_branch = res.branch;
self.git_status_workdir = res.workdir;
// 世代が一致 = この結果は現在の workdir のもの。スキャン開始時点の root は、同一 repo 内で
// `l`/`h` が動いていると現在の root と食い違う。食い違ったまま記録すると、次の fs イベントで
// `refresh_git_status_only` が早期 return して**再検証を丸ごと取りこぼす**ため、現在の root を入れる。
self.git_status_for = Some(self.root.clone());
self.git_status_pending = None;
// 計算中に届いていた再検証要求(合体分)をここで1回だけ実行する。
if self.git_status_dirty {
let wd = crate::git::workdir(&self.root);
self.kick_status_refresh(wd);
}
// 「変更ファイルのみ」フィルタの一覧は statuses から**導出済みの entries** なので、再描画では
// 直らない。新しい status が届いたこの瞬間に作り直す(エージェントの編集への live 追従)。
if self.changed_filter {
self.reapply_changed_filter();
}
true
}
/// Compute the heavy `git::ignored(root)` on a separate thread and return the result via the Sender. If no Sender is attached (tests /
/// no channel), fall back to **synchronous** immediate computation and application (keeping unit tests that don't assume rendering working).
fn spawn_or_sync_ignored(&mut self, root: PathBuf, workdir: PathBuf, gen: u64) {
let Some(tx) = self.ignored_tx.clone() else {
// 同期フォールバック: その場で計算して反映(陳腐化なし)。
let set = crate::git::ignored(&root);
self.apply_ignored(IgnoredResult { gen, workdir, set });
return;
};
std::thread::spawn(move || {
let set = crate::git::ignored(&root);
let _ = tx.send(IgnoredResult { gen, workdir, set });
});
}
/// Apply the `ignored` computation result from the other thread. Discards results with an old generation (moved to a different repo during computation).
/// Returns true if applying changed the state (the caller redraws).
pub fn apply_ignored(&mut self, res: IgnoredResult) -> bool {
if res.gen != self.git_ignored_gen {
return false; // 陳腐化: 既に別 repo / 別世代へ移っている
}
self.git_ignored = res.set;
self.git_ignored_for = Some(res.workdir);
self.git_ignored_pending = None;
true
}
/// Returns the git status of a given path.
pub fn git_status_of(&self, path: &Path) -> Option<crate::git::FileStatus> {
self.git_status.get(path).copied()
}
/// Whether `path` is excluded by gitignore (itself or an **ancestor directory** is in the ignored set).
/// Even when expanding under `node_modules` (= one entry), an ancestor match lets the contents be dimmed too. Does not look above root.
pub fn is_ignored(&self, path: &Path) -> bool {
if self.git_ignored.is_empty() {
return false;
}
let mut p = path;
loop {
if self.git_ignored.contains(p) {
return true;
}
if p == self.root {
return false;
}
match p.parent() {
Some(parent) => p = parent,
None => return false,
}
}
}
/// The current branch name (None if not a repo). Used for the tree's title display.
pub fn git_branch(&self) -> Option<&str> {
self.git_branch.as_deref()
}
/// Whether there is at least one change (= a git repo with uncommitted changes). Used to decide the status-gutter display.
pub fn git_has_changes(&self) -> bool {
!self.git_status.is_empty()
}
/// Reload: refetch the directory listing and git status (`r` key, FSEvents, returning from an external tool).
/// Keeps derived state in sync **in one place** to prevent the display from diverging from reality:
/// - **Prune selection to existing paths only** (prevents one externally-deleted item from making a batch trash operation fail entirely #12).
/// A broken symlink itself is kept as existing (judged via `symlink_metadata` without following → don't wrongly drop it from operation targets).
/// - **Recompute only the active derived views** (don't touch inactive ones, to avoid over-recomputation;
/// same spirit as the root guard in `refresh_git_if_needed`): in the Git view, the change list; in Preview mode,
/// refetch the current preview (reflecting git_view_entries staleness on return from an external git tool #4 / preview staleness on external edit).
pub fn refresh(&mut self) -> Result<()> {
// 明示的な再読込(`r`・fileops・外部ツール復帰)は無視セットも作り直す(全再計算)。
self.refresh_fs(true)
}
/// Reload from FSEvents. When `recompute_ignored=false`, **skip recomputing the heavy ignore set (`ignored`)**
/// and refetch only the cheap `statuses`+`branch`. Ignore rules (`.gitignore` /
/// `.git/info/exclude`) rarely change, so this is called with `true` only when they actually change, also rebuilding
/// `ignored`. This avoids a few-hundred-ms freeze per event on large repositories.
pub fn refresh_fs(&mut self, recompute_ignored: bool) -> Result<()> {
// 変更パス不明 = 安全側(プレビューも再読込)。
self.refresh_fs_changed(recompute_ignored, &[])
}
/// `refresh_fs` の**変更パスを知っている**版。`changed` が空でなければ、現プレビューが
/// その変更の影響を受けるときだけ再読込する(`preview_affected_by` 参照)。
///
/// 目的: エージェントが `src/` を書き換え続けている間に、無関係な `docs/foo.md` の装飾を
/// 毎イベント作り直す(=Markdown 全文の再レンダ / CSV 全体の再パース)のを避ける。
/// ツリー再構築・git status・変更フィルタ・git ビューは従来どおり毎回追従する。
pub fn refresh_fs_changed(
&mut self,
recompute_ignored: bool,
changed: &[std::path::PathBuf],
) -> Result<()> {
self.refresh_fs_inner(recompute_ignored, changed, true)
}
/// The tab-switch variant: refresh the tree / git status / derived views, but **do not reload the
/// preview**. `load_active` has just rebuilt it from disk itself (`setup_windowed` reopens the file,
/// `load_table` re-parses it, `md_cache = None` makes the next draw re-read the source, and
/// `start_media_load` re-reads the media), so going through `reload_preview` here only repeated the
/// same work — a second full CSV parse for a table tab, a second window open for a text tab.
pub(super) fn refresh_fs_after_tab_switch(&mut self) -> Result<()> {
self.refresh_fs_inner(false, &[], false)
}
fn refresh_fs_inner(
&mut self,
recompute_ignored: bool,
changed: &[std::path::PathBuf],
reload_preview: bool,
) -> Result<()> {
if recompute_ignored {
self.git_status_for = None; // 次の描画で statuses+branch を再計算
self.git_status_dirty = true; // 無視ルール変更で status 出力も変わり得る=workdir キャッシュを無効化
self.git_ignored_dirty = true; // 重い ignored も作り直す(無視ルール変更/明示 refresh)。
// 旧セットは反映まで維持(別スレッド計算・チラつき回避)。
} else {
self.refresh_git_status_only(); // statuses+branch のみ(ignored はキャッシュ保持)
}
self.diff_cache = None; // 作業ツリーが変わった可能性 → diff キャッシュを落とす(外部編集の追従)
self.gutter_cache = None; // 同上: git 変更ガターも作業ツリー変更で作り直す
// ツリー再構築は行うが、その一時的な失敗(エージェントが一括でファイルを書き替える最中に
// 展開中サブディレクトリが一瞬読めなくなる等)で、下のプレビュー/ビュー再読込を**スキップさせない**。
// それらは preview_path / git 状態だけで動き、新しいツリーには依存しない。ツリーの Err は末尾で返す。
let tree = self.rebuild_tree();
// 変更ファイルのみフィルタ中は一覧を最新の statuses から作り直す(エージェントの編集に追従)。
if self.changed_filter {
self.refresh_git_if_needed();
// スキャン走行中に作り直してはいけない。別 repo のタブから戻った直後は `git_status` が
// 空(kick が別 repo の残骸を捨てた直後)なので、ここで作り直すとフィルタが「変更ゼロ」と
// 判断されて**黙って解除され、嘘の「no changed files」まで出る**。結果到着時に
// `apply_statuses` が作り直すので、待てばよい。
if self.git_status_pending.is_none() {
self.reapply_changed_filter();
}
}
// 消えたパスを選択集合から除く(retain で実在のみ残す。シンボリックリンクは辿らない)。
self.selection.retain(|p| p.symlink_metadata().is_ok());
// アクティブな派生ビューのみ追従させる。
if self.is_git_view() {
self.git_view_reload();
}
if reload_preview && matches!(self.mode, Mode::Preview) && self.preview_affected_by(changed)
{
self.reload_preview();
}
tree
}
/// Whether the current preview must be re-read because of this FS event.
///
/// `changed` carries the non-`.git` paths from the event (the watcher strips repository
/// internals). **An empty slice therefore means "unknown or `.git`-only"** — a commit, a
/// checkout, or an event we could not attribute — and always reloads, so git diff previews and
/// change gutters never go stale.
///
/// Otherwise only the previewed file itself matters. Inline Markdown images are deliberately not
/// considered: `md_image_cache` is keyed by path and only cleared when switching files, so those
/// are not re-decoded by a reload either — gating here does not make them any staler.
fn preview_affected_by(&self, changed: &[std::path::PathBuf]) -> bool {
if changed.is_empty() {
return true;
}
// git の diff 表示は「ファイル + git 状態」の関数。同じイベントに `.git` の変更が
// 混ざっていても(=ここには現れない)取りこぼさないよう、常に追従させる。
if self.is_git_diff_preview() {
return true;
}
let Some(cur) = self.preview_path.as_deref() else {
return true;
};
changed.iter().any(|p| p == cur)
}
/// Cheap git update: refetch only `statuses` + `branch`, **leaving the heavy `ignored` (ignore set) untouched**
/// (keeping the cache). Does nothing if the initial `ignored` computation hasn't happened yet (`git_status_for` unset)
/// (the next render's `refresh_git_if_needed` computes everything).
fn refresh_git_status_only(&mut self) {
if self.git_status_for.as_deref() != Some(self.root.as_path()) {
return;
}
// 再取得は**別スレッド**へ。ここは `handle_key` の中(fs イベント/タブ切替)から呼ばれるので、
// 同期実行するとキー入力そのものが `git status` の時間だけ固まっていた。
let wd = crate::git::workdir(&self.root);
self.git_status_dirty = true; // 同一 workdir でも取り直す(再検証要求)
self.kick_status_refresh(wd);
}
}