forked from gokcehan/lf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nav.go
2060 lines (1742 loc) · 42.9 KB
/
nav.go
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
package main
import (
"bufio"
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/djherbis/times"
)
type linkState byte
const (
notLink linkState = iota
working
broken
)
type file struct {
os.FileInfo
linkState linkState
linkTarget string
path string
dirCount int
dirSize int64
accessTime time.Time
changeTime time.Time
ext string
err error
}
func (file *file) TotalSize() int64 {
if file.IsDir() {
if file.dirSize >= 0 {
return file.dirSize
}
return 0
}
return file.Size()
}
type fakeStat struct {
name string
}
func (fs *fakeStat) Name() string { return fs.name }
func (fs *fakeStat) Size() int64 { return 0 }
func (fs *fakeStat) Mode() os.FileMode { return os.FileMode(0000) }
func (fs *fakeStat) ModTime() time.Time { return time.Unix(0, 0) }
func (fs *fakeStat) IsDir() bool { return false }
func (fs *fakeStat) Sys() any { return nil }
func readdir(path string) ([]*file, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
names, err := f.Readdirnames(-1)
f.Close()
files := make([]*file, 0, len(names))
for _, fname := range names {
fpath := filepath.Join(path, fname)
lstat, err := os.Lstat(fpath)
if os.IsNotExist(err) {
continue
}
if err != nil {
log.Printf("getting file information: %s", err)
files = append(files, &file{
FileInfo: &fakeStat{name: fname},
linkState: notLink,
linkTarget: "",
path: fpath,
dirCount: -1,
dirSize: -1,
accessTime: time.Unix(0, 0),
changeTime: time.Unix(0, 0),
ext: filepath.Ext(fpath),
err: err,
})
continue
}
var linkState linkState
var linkTarget string
if lstat.Mode()&os.ModeSymlink != 0 {
stat, err := os.Stat(fpath)
if err == nil {
linkState = working
lstat = stat
} else {
linkState = broken
}
linkTarget, err = os.Readlink(fpath)
if err != nil {
log.Printf("reading link target: %s", err)
}
}
ts := times.Get(lstat)
at := ts.AccessTime()
var ct time.Time
// from times docs: ChangeTime() panics unless HasChangeTime() is true
if ts.HasChangeTime() {
ct = ts.ChangeTime()
} else {
// fall back to ModTime if ChangeTime cannot be determined
ct = lstat.ModTime()
}
// returns an empty string if extension could not be determined
// i.e. directories, filenames without extensions
ext := filepath.Ext(fpath)
dirCount := -1
if lstat.IsDir() && gOpts.dircounts {
d, err := os.Open(fpath)
if err != nil {
dirCount = -2
} else {
names, err := d.Readdirnames(1000)
d.Close()
if names == nil && err != io.EOF {
dirCount = -2
} else {
dirCount = len(names)
}
}
}
files = append(files, &file{
FileInfo: lstat,
linkState: linkState,
linkTarget: linkTarget,
path: fpath,
dirCount: dirCount,
dirSize: -1,
accessTime: at,
changeTime: ct,
ext: ext,
err: nil,
})
}
return files, err
}
type dir struct {
loading bool // directory is loading from disk
loadTime time.Time // current loading or last load time
ind int // index of current entry in files
pos int // position of current entry in ui
path string // full path of directory
files []*file // displayed files in directory including or excluding hidden ones
allFiles []*file // all files in directory including hidden ones (same array as files)
sortType sortType // sort method and options from last sort
dironly bool // dironly value from last sort
hiddenfiles []string // hiddenfiles value from last sort
filter []string // last filter for this directory
ignorecase bool // ignorecase value from last sort
ignoredia bool // ignoredia value from last sort
noPerm bool // whether lf has no permission to open the directory
lines []string // lines of text to display if directory previews are enabled
}
func newDir(path string) *dir {
time := time.Now()
files, err := readdir(path)
if err != nil {
log.Printf("reading directory: %s", err)
}
return &dir{
loading: gOpts.dirpreviews, // Directory is loaded after previewer function exits.
loadTime: time,
path: path,
files: files,
allFiles: files,
noPerm: os.IsPermission(err),
}
}
func normalize(s1, s2 string, ignorecase, ignoredia bool) (string, string) {
if ignorecase {
s1 = strings.ToLower(s1)
s2 = strings.ToLower(s2)
}
if ignoredia {
s1 = removeDiacritics(s1)
s2 = removeDiacritics(s2)
}
return s1, s2
}
func (dir *dir) sort() {
dir.sortType = getSortType(dir.path)
dir.dironly = getDirOnly(dir.path)
dir.hiddenfiles = gOpts.hiddenfiles
dir.ignorecase = gOpts.ignorecase
dir.ignoredia = gOpts.ignoredia
dir.files = dir.allFiles
// reverse order cannot be applied after stable sorting, otherwise the order
// of equivalent elements will be reversed
reverse := dir.sortType.option&reverseSort != 0
switch dir.sortType.method {
case naturalSort:
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
if !reverse {
return naturalLess(s1, s2)
} else {
return naturalLess(s2, s1)
}
})
case nameSort:
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
if !reverse {
return s1 < s2
} else {
return s2 < s1
}
})
case sizeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
if !reverse {
return dir.files[i].TotalSize() < dir.files[j].TotalSize()
} else {
return dir.files[j].TotalSize() < dir.files[i].TotalSize()
}
})
case timeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
if !reverse {
return dir.files[i].ModTime().Before(dir.files[j].ModTime())
} else {
return dir.files[j].ModTime().Before(dir.files[i].ModTime())
}
})
case atimeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
if !reverse {
return dir.files[i].accessTime.Before(dir.files[j].accessTime)
} else {
return dir.files[j].accessTime.Before(dir.files[i].accessTime)
}
})
case ctimeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
if !reverse {
return dir.files[i].changeTime.Before(dir.files[j].changeTime)
} else {
return dir.files[j].changeTime.Before(dir.files[i].changeTime)
}
})
case extSort:
sort.SliceStable(dir.files, func(i, j int) bool {
ext1, ext2 := normalize(dir.files[i].ext, dir.files[j].ext, dir.ignorecase, dir.ignoredia)
// if the extension could not be determined (directories, files without)
// use a zero byte so that these files can be ranked higher
if ext1 == "" {
ext1 = "\x00"
}
if ext2 == "" {
ext2 = "\x00"
}
name1, name2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
// in order to also have natural sorting with the filenames
// combine the name with the ext but have the ext at the front
if !reverse {
return ext1 < ext2 || ext1 == ext2 && name1 < name2
} else {
return ext2 < ext1 || ext2 == ext1 && name2 < name1
}
})
}
if dir.sortType.option&dirfirstSort != 0 {
sort.SliceStable(dir.files, func(i, j int) bool {
if dir.files[i].IsDir() == dir.files[j].IsDir() {
return i < j
}
return dir.files[i].IsDir()
})
}
// when dironly option is enabled, we move files to the beginning of our file
// list and then set the beginning of displayed files to the first directory
// in the list
if dir.dironly {
sort.SliceStable(dir.files, func(i, j int) bool {
if !dir.files[i].IsDir() && !dir.files[j].IsDir() {
return i < j
}
return !dir.files[i].IsDir()
})
dir.files = func() []*file {
for i, f := range dir.files {
if f.IsDir() {
return dir.files[i:]
}
}
return dir.files[len(dir.files):]
}()
}
// when hidden option is disabled, we move hidden files to the
// beginning of our file list and then set the beginning of displayed
// files to the first non-hidden file in the list
if dir.sortType.option&hiddenSort == 0 {
sort.SliceStable(dir.files, func(i, j int) bool {
if isHidden(dir.files[i], dir.path, dir.hiddenfiles) && isHidden(dir.files[j], dir.path, dir.hiddenfiles) {
return i < j
}
return isHidden(dir.files[i], dir.path, dir.hiddenfiles)
})
for i, f := range dir.files {
if !isHidden(f, dir.path, dir.hiddenfiles) {
dir.files = dir.files[i:]
break
}
}
if len(dir.files) > 0 && isHidden(dir.files[len(dir.files)-1], dir.path, dir.hiddenfiles) {
dir.files = dir.files[len(dir.files):]
}
}
if len(dir.filter) != 0 {
sort.SliceStable(dir.files, func(i, j int) bool {
if isFiltered(dir.files[i], dir.filter) && isFiltered(dir.files[j], dir.filter) {
return i < j
}
return isFiltered(dir.files[i], dir.filter)
})
for i, f := range dir.files {
if !isFiltered(f, dir.filter) {
dir.files = dir.files[i:]
break
}
}
if len(dir.files) > 0 && isFiltered(dir.files[len(dir.files)-1], dir.filter) {
dir.files = dir.files[len(dir.files):]
}
}
dir.ind = max(dir.ind, 0)
dir.ind = min(dir.ind, len(dir.files)-1)
}
func (dir *dir) name() string {
if len(dir.files) == 0 {
return ""
}
return dir.files[dir.ind].Name()
}
func (dir *dir) sel(name string, height int) {
if len(dir.files) == 0 {
dir.ind, dir.pos = 0, 0
return
}
dir.ind = max(dir.ind, 0)
dir.ind = min(dir.ind, len(dir.files)-1)
if dir.files[dir.ind].Name() != name {
for i, f := range dir.files {
if f.Name() == name {
dir.ind = i
break
}
}
}
dir.boundPos(height)
}
func (dir *dir) boundPos(height int) {
if len(dir.files) <= height {
dir.pos = dir.ind
return
}
edge := min(height/2, gOpts.scrolloff)
dir.pos = max(dir.pos, edge)
// use a smaller value for half when the height is even and scrolloff is
// maxed in order to stay at the same row while scrolling up and down
if height%2 == 0 {
edge = min(height/2-1, gOpts.scrolloff)
}
dir.pos = min(dir.pos, height-1-edge)
dir.pos = min(dir.pos, dir.ind)
dir.pos = max(dir.pos, height-(len(dir.files)-dir.ind))
}
type nav struct {
init bool
dirs []*dir
copyBytes int64
copyTotal int64
copyUpdate int
moveCount int
moveTotal int
moveUpdate int
deleteCount int
deleteTotal int
deleteUpdate int
copyBytesChan chan int64
copyTotalChan chan int64
moveCountChan chan int
moveTotalChan chan int
deleteCountChan chan int
deleteTotalChan chan int
previewChan chan string
dirPreviewChan chan *dir
dirChan chan *dir
regChan chan *reg
dirCache map[string]*dir
regCache map[string]*reg
saves map[string]bool
marks map[string]string
renameOldPath string
renameNewPath string
selections map[string]int
tags map[string]string
selectionInd int
height int
find string
findBack bool
search string
searchBack bool
searchInd int
searchPos int
prevFilter []string
volatilePreview bool
previewTimer *time.Timer
previewLoading bool
jumpList []string
jumpListInd int
}
func (nav *nav) loadDirInternal(path string) *dir {
nav.startPreview()
d := &dir{
loading: true,
loadTime: time.Now(),
path: path,
sortType: getSortType(path),
hiddenfiles: gOpts.hiddenfiles,
ignorecase: gOpts.ignorecase,
ignoredia: gOpts.ignoredia,
}
go func() {
d := newDir(path)
d.sort()
d.ind, d.pos = 0, 0
if gOpts.dirpreviews {
nav.dirPreviewChan <- d
}
nav.dirChan <- d
}()
return d
}
func (nav *nav) loadDir(path string) *dir {
if gOpts.dircache {
d, ok := nav.dirCache[path]
if !ok {
d = nav.loadDirInternal(path)
nav.dirCache[path] = d
return d
}
nav.checkDir(d)
return d
}
return nav.loadDirInternal(path)
}
func (nav *nav) checkDir(dir *dir) {
s, err := os.Stat(dir.path)
if err != nil {
log.Printf("getting directory info: %s", err)
return
}
switch {
case s.ModTime().After(dir.loadTime):
now := time.Now()
// XXX: Linux builtin exFAT drivers are able to predict modifications in the future
// https://bugs.launchpad.net/ubuntu/+source/ubuntu-meta/+bug/1872504
if s.ModTime().After(now) {
return
}
nav.startPreview()
dir.loading = true
dir.loadTime = now
go func() {
nd := newDir(dir.path)
nd.filter = dir.filter
nd.sort()
if gOpts.dirpreviews {
nav.dirPreviewChan <- nd
}
nav.dirChan <- nd
}()
case dir.sortType != getSortType(dir.path) ||
dir.dironly != getDirOnly(dir.path) ||
!reflect.DeepEqual(dir.hiddenfiles, gOpts.hiddenfiles) ||
dir.ignorecase != gOpts.ignorecase ||
dir.ignoredia != gOpts.ignoredia:
dir.loading = true
sd := *dir
go func() {
sd.sort()
sd.loading = false
nav.dirChan <- &sd
}()
}
}
func (nav *nav) getDirs(wd string) {
var dirs []*dir
wd = filepath.Clean(wd)
for curr, base := wd, ""; !isRoot(base); curr, base = filepath.Dir(curr), filepath.Base(curr) {
dir := nav.loadDir(curr)
if base != "" {
dir.sel(base, nav.height)
}
dirs = append(dirs, dir)
}
for i, j := 0, len(dirs)-1; i < j; i, j = i+1, j-1 {
dirs[i], dirs[j] = dirs[j], dirs[i]
}
nav.dirs = dirs
}
func newNav(height int) *nav {
nav := &nav{
copyBytesChan: make(chan int64, 1024),
copyTotalChan: make(chan int64, 1024),
moveCountChan: make(chan int, 1024),
moveTotalChan: make(chan int, 1024),
deleteCountChan: make(chan int, 1024),
deleteTotalChan: make(chan int, 1024),
previewChan: make(chan string, 1024),
dirPreviewChan: make(chan *dir, 1024),
dirChan: make(chan *dir),
regChan: make(chan *reg),
dirCache: make(map[string]*dir),
regCache: make(map[string]*reg),
saves: make(map[string]bool),
marks: make(map[string]string),
selections: make(map[string]int),
tags: make(map[string]string),
selectionInd: 0,
height: height,
previewTimer: time.NewTimer(0),
jumpList: make([]string, 0),
jumpListInd: -1,
}
return nav
}
func (nav *nav) addJumpList() {
currPath := nav.currDir().path
if nav.jumpListInd >= 0 && nav.jumpListInd < len(nav.jumpList)-1 {
if nav.jumpList[nav.jumpListInd] == currPath {
// walking the jumpList
return
}
nav.jumpList = nav.jumpList[:nav.jumpListInd+1]
}
if len(nav.jumpList) == 0 || nav.jumpList[len(nav.jumpList)-1] != currPath {
nav.jumpList = append(nav.jumpList, currPath)
}
nav.jumpListInd = len(nav.jumpList) - 1
}
func (nav *nav) cdJumpListPrev() {
if nav.jumpListInd > 0 {
nav.jumpListInd -= 1
nav.cd(nav.jumpList[nav.jumpListInd])
}
}
func (nav *nav) cdJumpListNext() {
if nav.jumpListInd < len(nav.jumpList)-1 {
nav.jumpListInd += 1
nav.cd(nav.jumpList[nav.jumpListInd])
}
}
func (nav *nav) renew() {
for _, d := range nav.dirs {
nav.checkDir(d)
}
for m := range nav.selections {
if _, err := os.Lstat(m); os.IsNotExist(err) {
delete(nav.selections, m)
}
}
if len(nav.selections) == 0 {
nav.selectionInd = 0
}
}
func (nav *nav) reload() error {
nav.dirCache = make(map[string]*dir)
nav.regCache = make(map[string]*reg)
curr, err := nav.currFile()
nav.getDirs(nav.currDir().path)
if err == nil {
last := nav.dirs[len(nav.dirs)-1]
last.files = append(last.files, curr)
}
return nil
}
func (nav *nav) position() {
if !nav.init {
return
}
path := nav.currDir().path
for i := len(nav.dirs) - 2; i >= 0; i-- {
nav.dirs[i].sel(filepath.Base(path), nav.height)
path = filepath.Dir(path)
}
}
func (nav *nav) exportFiles() {
if !nav.init {
return
}
var currFile string
if curr, err := nav.currFile(); err == nil {
currFile = quoteString(curr.path)
}
var selections []string
for _, selection := range nav.currSelections() {
selections = append(selections, quoteString(selection))
}
currSelections := strings.Join(selections, gOpts.filesep)
os.Setenv("f", currFile)
os.Setenv("fs", currSelections)
os.Setenv("PWD", quoteString(nav.currDir().path))
if len(selections) == 0 {
os.Setenv("fx", currFile)
} else {
os.Setenv("fx", currSelections)
}
}
func (nav *nav) dirPreviewLoop(ui *ui) {
var prevPath string
for dir := range nav.dirPreviewChan {
if dir == nil && len(gOpts.previewer) != 0 && len(gOpts.cleaner) != 0 && nav.volatilePreview {
cmd := exec.Command(gOpts.cleaner, prevPath)
if err := cmd.Run(); err != nil {
log.Printf("cleaning preview: %s", err)
}
nav.volatilePreview = false
} else if dir != nil {
win := ui.wins[len(ui.wins)-1]
nav.previewDir(dir, win)
prevPath = dir.path
}
}
}
func (nav *nav) previewLoop(ui *ui) {
var prev string
for path := range nav.previewChan {
clear := len(path) == 0
loop:
for {
select {
case path = <-nav.previewChan:
clear = clear || len(path) == 0
default:
break loop
}
}
win := ui.wins[len(ui.wins)-1]
if clear && len(gOpts.previewer) != 0 && len(gOpts.cleaner) != 0 && nav.volatilePreview {
cmd := exec.Command(gOpts.cleaner, prev,
strconv.Itoa(win.w),
strconv.Itoa(win.h),
strconv.Itoa(win.x),
strconv.Itoa(win.y),
path)
if err := cmd.Run(); err != nil {
log.Printf("cleaning preview: %s", err)
}
nav.volatilePreview = false
}
if len(path) != 0 {
nav.preview(path, win)
prev = path
}
}
}
//lint:ignore U1000 This function is not used on Windows
func matchPattern(pattern, name, path string) bool {
s := name
pattern = replaceTilde(pattern)
if filepath.IsAbs(pattern) {
s = filepath.Join(path, name)
}
// pattern errors are checked when 'hiddenfiles' option is set
matched, _ := filepath.Match(pattern, s)
return matched
}
func (nav *nav) previewDir(dir *dir, win *win) {
defer func() {
dir.loading = false
nav.dirChan <- dir
}()
var reader io.Reader
if len(gOpts.previewer) != 0 {
cmd := exec.Command(gOpts.previewer, dir.path,
strconv.Itoa(win.w),
strconv.Itoa(win.h),
strconv.Itoa(win.x),
strconv.Itoa(win.y))
out, err := cmd.StdoutPipe()
if err != nil {
log.Printf("previewing dir: %s", err)
return
}
if err := cmd.Start(); err != nil {
log.Printf("previewing dir: %s", err)
out.Close()
return
}
defer func() {
if err := cmd.Wait(); err != nil {
if e, ok := err.(*exec.ExitError); ok {
if e.ExitCode() != 0 {
nav.volatilePreview = true
}
} else {
log.Printf("loading dir: %s", err)
}
}
}()
defer out.Close()
reader = out
buf := bufio.NewScanner(reader)
for i := 0; i < win.h && buf.Scan(); i++ {
for _, r := range buf.Text() {
if r == 0 {
dir.lines = []string{"\033[7mbinary\033[0m"}
return
}
}
dir.lines = append(dir.lines, buf.Text())
}
if buf.Err() != nil {
log.Printf("loading dir: %s", buf.Err())
}
}
}
func (nav *nav) preview(path string, win *win) {
reg := ®{loadTime: time.Now(), path: path}
defer func() { nav.regChan <- reg }()
var reader *bufio.Reader
if len(gOpts.previewer) != 0 {
cmd := exec.Command(gOpts.previewer, path,
strconv.Itoa(win.w),
strconv.Itoa(win.h),
strconv.Itoa(win.x),
strconv.Itoa(win.y))
out, err := cmd.StdoutPipe()
if err != nil {
log.Printf("previewing file: %s", err)
return
}
if err := cmd.Start(); err != nil {
log.Printf("previewing file: %s", err)
out.Close()
return
}
defer func() {
if err := cmd.Wait(); err != nil {
if e, ok := err.(*exec.ExitError); ok {
if e.ExitCode() != 0 {
reg.volatile = true
nav.volatilePreview = true
}
} else {
log.Printf("loading file: %s", err)
}
}
}()
defer out.Close()
reader = bufio.NewReader(out)
} else {
f, err := os.Open(path)
if err != nil {
log.Printf("opening file: %s", err)
return
}
defer f.Close()
reader = bufio.NewReader(f)
}
if gOpts.sixel {
prefix, err := reader.Peek(2)
if err == nil && string(prefix) == gSixelBegin {
b, err := io.ReadAll(reader)
if err != nil {
log.Printf("loading sixel: %s", err)
}
str := string(b)
reg.sixel = &str
return
}
}
// bufio.Scanner can't handle files containing long lines if they exceed the
// size of its internal buffer
addLine := true
for len(reg.lines) < win.h {
line, isPrefix, err := reader.ReadLine()
if err != nil {
break
}
for _, r := range line {
if r == 0 {
reg.lines = []string{"\033[7mbinary\033[0m"}
return
}
}
if addLine {
reg.lines = append(reg.lines, string(line))
}
addLine = !isPrefix
}
}
func (nav *nav) loadReg(path string, volatile bool) *reg {
r, ok := nav.regCache[path]
if !ok || (volatile && r.volatile) {
r := ®{loading: true, loadTime: time.Now(), path: path, volatile: true}
nav.regCache[path] = r
nav.startPreview()
nav.previewChan <- path
return r
}
nav.checkReg(r)
return r
}
func (nav *nav) checkReg(reg *reg) {
s, err := os.Stat(reg.path)
if err != nil {
return
}
now := time.Now()
// XXX: Linux builtin exFAT drivers are able to predict modifications in the future
// https://bugs.launchpad.net/ubuntu/+source/ubuntu-meta/+bug/1872504
if s.ModTime().After(now) {
return
}
if s.ModTime().After(reg.loadTime) {
reg.loadTime = now
nav.startPreview()
nav.previewChan <- reg.path
}
}
func (nav *nav) startPreview() {
nav.previewTimer.Stop()
nav.previewLoading = false
nav.previewTimer.Reset(100 * time.Millisecond)
}
func (nav *nav) sort() {
for _, d := range nav.dirs {
name := d.name()
d.sort()
d.sel(name, nav.height)
}
}
func (nav *nav) setFilter(filter []string) error {
newfilter := []string{}
for _, tok := range filter {
_, err := filepath.Match(tok, "a")
if err != nil {
return err
}
if tok != "" {
newfilter = append(newfilter, tok)
}
}
dir := nav.currDir()
dir.filter = newfilter
// Apply filter, by sorting current dir (see nav.sort())
name := dir.name()
dir.sort()
dir.sel(name, nav.height)
return nil
}
func (nav *nav) up(dist int) bool {
dir := nav.currDir()
old := dir.ind
if dir.ind == 0 {
if gOpts.wrapscroll {
nav.bottom()
}
return old != dir.ind
}
dir.ind -= dist
dir.ind = max(0, dir.ind)
dir.pos -= dist
dir.boundPos(nav.height)