-
Notifications
You must be signed in to change notification settings - Fork 2
/
itree.go
executable file
·608 lines (544 loc) · 15.7 KB
/
itree.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
package main
import (
"bytes"
"errors"
"fmt"
"math"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"github.com/nsf/termbox-go"
"github.com/lobocv/itree/ctx"
)
func max(i, j int) int {
if i > j {
return i
}
return j
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// Create an enumeration for tracking what the screen's "state" is
// This governs what the screen should draw when .draw() is called.
type ScreenState int
const (
Directory ScreenState = iota
Help
)
type CaptureMode int
const (
modeSearch CaptureMode = iota
modeExitCommand
modeFilePerm
)
type ExitCommand struct {
command string
args []string
}
func (cmd *ExitCommand) FullCommand() string {
return cmd.command + " " + strings.Join(cmd.args, " ")
}
// Screen represents the application
type Screen struct {
CurrentDir *ctx.Directory
state ScreenState
searchString []rune
commandString []rune
captureInput bool
captureMode CaptureMode
showPermissions bool
maxLevelWidth int
highlightedColor termbox.Attribute
filteredColor termbox.Attribute
directoryColor termbox.Attribute
fileColor termbox.Attribute
}
// Move up by half the distance between the selected file
// Always move at least 2 steps
func (s *Screen) jumpUp() {
by := -max(2, s.CurrentDir.FileIdx/2)
s.CurrentDir.MoveSelector(by)
}
// Move down by half the distance between the selected file
// Always move at least 2 steps
func (s *Screen) jumpDown() {
by := max(2, (len(s.CurrentDir.Files)-s.CurrentDir.FileIdx)/2)
s.CurrentDir.MoveSelector(by)
}
// Prints text to the terminal at the provided position and color
func (s *Screen) Print(x, y int, fg, bg termbox.Attribute, msg string) {
for _, c := range msg {
termbox.SetCell(x, y, c, fg, bg)
x++
}
}
// Prints the structure of the directory path provided
func (s *Screen) drawDirContents(x0, y0 int, dirlist ctx.DirView) error {
var levelOffsetX, levelOffsetY int // draw position offset
var stretch int // Length of line connecting subdirectories
var maxLineWidth int // Length of longest item in the directory
var scrollOffsety int // Offset to scroll the visible directory text by
var subDirSpacing = 2 // Spacing between subdirectories (on top of max item length)
screenWidth, screenHeight := termbox.Size()
levelOffsetX = x0
levelOffsetY = y0
// Determine the scrolling offset
scrollOffsety = levelOffsetY
for _, dir := range dirlist {
scrollOffsety += dir.FileIdx
}
// If the selected item is off the screen then shift the entire view up in order
// to make it visible.
scrollOffsety -= screenHeight - levelOffsetY
if scrollOffsety < 0 {
scrollOffsety = 0
} else {
pagejump := float64(screenHeight) / 5
scrollOffsety = int(math.Ceil(float64(scrollOffsety)/pagejump) * pagejump)
}
lastLevel := len(dirlist) - 1
// Iterate through the directory list, drawing a tree structure
for level, dir := range dirlist {
maxLineWidth = s.maxLevelWidth
if level == len(dirlist)-1 {
maxLineWidth = 0
}
for ii, f := range dir.Files {
// Keep track of the longest length item in the directory
filenameLen := len(f.Name())
if s.maxLevelWidth == 0 && filenameLen > maxLineWidth {
maxLineWidth = filenameLen
}
// Determine the color of the currently printing directory item
var color termbox.Attribute
if dir.FileIdx == ii && level == len(dirlist)-1 {
color = s.highlightedColor
} else {
if _, ok := dir.FilteredFiles[ii]; ok {
color = s.filteredColor
} else if f.IsDir() {
color = s.directoryColor
} else {
color = s.fileColor
}
}
// Start creating the line to be printed
line := bytes.Buffer{}
if ii == 0 {
line.WriteString(strings.Repeat("─", stretch))
}
switch ii {
case 0:
if level > 0 {
if len(dir.Files) < 2 {
line.WriteString(strings.Repeat("─", subDirSpacing))
} else {
line.WriteString(strings.Repeat("─", subDirSpacing))
line.WriteString("┬─")
}
} else {
line.WriteString(strings.Repeat(" ", subDirSpacing))
line.WriteString("├─")
}
case len(dir.Files) - 1:
line.WriteString(strings.Repeat(" ", subDirSpacing))
line.WriteString("└─")
default:
line.WriteString(strings.Repeat(" ", subDirSpacing))
line.WriteString("├─")
}
// Create the item label, add / if it is a directory
itemName := f.Name()
if maxLineWidth > 0 && len(itemName) > maxLineWidth {
line.WriteString(itemName[:min(len(itemName), maxLineWidth-3)])
line.WriteString("...")
} else {
line.WriteString(itemName)
}
if f.IsDir() {
line.WriteString("/")
}
if level == lastLevel && s.showPermissions {
line.WriteString("\t")
line.WriteString(f.Mode().Perm().String())
}
// Calculate the draw position
y := levelOffsetY + ii - scrollOffsety
x := levelOffsetX
if ii == 0 {
// The first item is connected to the parent directory with a line
// shift the position left to account for this line
x -= stretch
}
if x+len(line.String()) > screenWidth && len(dirlist) > 1 {
return errors.New("DisplayOverflow")
}
if y < y0 {
y = y0
}
s.Print(x, y, color, termbox.ColorDefault, line.String())
}
// Determine the length of line we need to draw to connect to the next directory
if len(dir.Files) > 0 {
stretch = maxLineWidth - len(dir.Files[dir.FileIdx].Name())
if stretch < 0 {
stretch = 0
}
}
// Shift the draw position in preparation for the next directory
levelOffsetY += dir.FileIdx
levelOffsetX += maxLineWidth + 2 + subDirSpacing
}
return nil
}
// Toggles the state of the screen between regular view and the help screen
func (s *Screen) toggleHelp() ScreenState {
if s.state != Help {
s.state = Help
} else {
s.state = Directory
}
return s.state
}
// Draw the current representation of the screen
func (s *Screen) draw() {
switch s.state {
case Help:
var lc int
var help = []string{
"Calvin Lobo, 2018 - https://github.com/lobocv/itree",
"",
"An interactive tree application for file system navigation.",
"",
" CONTROLS ",
"================================================================",
}
hotkeys := []struct{ hotkey, description string }{
{"Left / Right", "Enter / exit currently selected directory"},
{"Up / Down", "Move directory item selector position by one"},
{"ESC or q", "Exit and change directory"},
{"CTRL + C", "Exit without changing directory"},
{"CTRL + h", "Opens help menu to show the list of hotkey mappings"},
{"h", "Toggle on / off visibility of hidden files"},
{"e", "Move selector half the distance between the current position and the top of the directory"},
{"d", "Move selector half the distance between the current position and the bottom of the directory"},
{"c", "Toggle position"},
{"a", "Jump up two directories"},
{"p", "Show file permissions"},
{"CTRL + p", "Set file permissions bitmask (eg 644, 777, 400)"},
{"/", "Enters input capture mode for directory filtering"},
{":", "Enters input capture mode for exit command"},
}
s.clearScreen()
for _, line := range help {
s.Print(0, lc, termbox.ColorWhite, termbox.ColorDefault, line)
lc++
}
lc++
for _, hotkey := range hotkeys {
hk := fmt.Sprintf("%-12v - ", hotkey.hotkey)
s.Print(0, lc, termbox.ColorWhite, termbox.ColorDefault, hk)
s.Print(len(hk), lc, termbox.ColorWhite, termbox.ColorDefault, hotkey.description)
lc++
}
lc += 2
s.Print(0, lc, termbox.ColorWhite, termbox.ColorDefault, "Press q to exit this menu.")
case Directory:
upperLevels, err := strconv.Atoi(os.Getenv("MaxUpperLevels"))
if err != nil {
upperLevels = 3
}
for {
s.clearScreen()
var instruction string
// Print the current path
s.Print(0, 0, termbox.ColorRed, termbox.ColorDefault, s.CurrentDir.AbsPath)
if s.captureInput {
switch s.captureMode {
case modeSearch:
instruction = "Enter a search string: " + string(s.searchString)
case modeFilePerm:
instruction = "Enter the file permissions: " + string(s.commandString)
case modeExitCommand:
instruction = "Enter a terminal command and hit enter: " + string(s.commandString)
}
s.Print(0, 1, termbox.ColorWhite, termbox.ColorDefault, instruction)
}
dirlist := s.getDirView(upperLevels)
err := s.drawDirContents(0, 2, dirlist)
if err == nil {
break
} else {
upperLevels -= 1
}
}
}
termbox.Flush()
}
// Clear the contents of the screen
func (s *Screen) clearScreen() {
termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
}
// Get a subset of the directory chain as a slice where the last element is the current directory
// upperLevels is the number of directory levels above the current directory to include in the slice.
func (s *Screen) getDirView(upperLevels int) ctx.DirView {
// Create a slice of the directory chain containing upperLevels number of parents
dir := s.CurrentDir
dirlist := make([]*ctx.Directory, 0, 1+upperLevels)
dirlist = append(dirlist, dir)
next := dir.Parent
for ii := 0; next != nil; ii++ {
if ii >= upperLevels {
break
}
dirlist = append([]*ctx.Directory{next}, dirlist...)
next = next.Parent
}
return dirlist
}
// Enters the currently selected directory
func (s *Screen) enterCurrentDirectory() {
dir := s.CurrentDir
dir.Descend()
s.searchString = s.searchString[:0]
dir.FilterContents(string(s.searchString))
nextdir, err := dir.Descend()
if nextdir != nil && err == nil {
s.CurrentDir = nextdir
}
s.stopCapturingInput()
}
// Exits the current directory.
func (s *Screen) exitCurrentDirectory() {
s.captureInput = false
s.searchString = s.searchString[:0]
s.CurrentDir.FilterContents(string(s.searchString))
nextdir, err := s.CurrentDir.Ascend()
if nextdir != nil && err == nil {
s.CurrentDir = nextdir
}
s.stopCapturingInput()
}
func (s *Screen) setCaptureMode(mode CaptureMode) {
s.captureMode = mode
}
// Sets the application in the mode to capture input for the search string
func (s *Screen) startCapturingInput() {
s.captureInput = true
switch s.captureMode {
case modeSearch:
s.searchString = s.searchString[:]
case modeExitCommand:
s.commandString = s.commandString[:]
case modeFilePerm:
s.commandString = s.commandString[:0]
}
}
// Exits the mode to capture input
func (s *Screen) stopCapturingInput() {
s.captureInput = false
if s.captureMode == modeSearch {
s.searchString = s.searchString[:0]
s.CurrentDir.FilterContents(string(s.searchString))
}
}
// Add a character to the currently capturing string
func (s *Screen) appendToCaptureInput(ch rune) {
switch s.captureMode {
case modeSearch:
s.searchString = append(s.searchString, ch)
s.CurrentDir.FilterContents(string(s.searchString))
case modeExitCommand, modeFilePerm:
s.commandString = append(s.commandString, ch)
}
}
// Remove a character from the currently capturing string
func (s *Screen) popFromCaptureInput() {
switch s.captureMode {
case modeSearch:
if len(s.searchString) > 0 {
s.searchString = s.searchString[:len(s.searchString)-1]
s.CurrentDir.FilterContents(string(s.searchString))
}
case modeExitCommand, modeFilePerm:
if len(s.commandString) > 0 {
s.commandString = s.commandString[:len(s.commandString)-1]
}
}
}
// Toggle position between first and last file in the directory
func (s *Screen) toggleIndexToExtremities() {
if s.CurrentDir.FileIdx == 0 {
s.CurrentDir.FileIdx = len(s.CurrentDir.Files) - 1
} else {
s.CurrentDir.FileIdx = 0
}
}
// Toggle position between first and last file in the directory
func (s *Screen) togglePermissions() {
s.showPermissions = !s.showPermissions
}
// Main loop of the application
func (s *Screen) Main() ExitCommand {
MainLoop:
for {
s.draw()
ev := termbox.PollEvent()
if s.captureInput {
if ev.Key == termbox.KeyEsc || ev.Key == termbox.KeyCtrlC {
s.stopCapturingInput()
continue
} else if ev.Key == termbox.KeyBackspace2 || ev.Key == termbox.KeyBackspace {
s.popFromCaptureInput()
} else if ev.Ch != 0 || ev.Key == termbox.KeySpace {
s.appendToCaptureInput(ev.Ch)
continue MainLoop
}
}
switch ev.Type {
case termbox.EventKey:
switch ev.Key {
case termbox.KeyEsc:
if s.state == Help {
s.toggleHelp()
} else {
break MainLoop
}
case termbox.KeyCtrlC:
return ExitCommand{"", nil}
case termbox.KeyArrowUp:
s.CurrentDir.MoveSelector(-1)
case termbox.KeyArrowDown:
s.CurrentDir.MoveSelector(1)
case termbox.KeyArrowLeft:
s.exitCurrentDirectory()
case termbox.KeyArrowRight:
s.enterCurrentDirectory()
case termbox.KeyPgup:
s.jumpUp()
case termbox.KeyPgdn:
s.jumpDown()
case termbox.KeyCtrlH:
s.toggleHelp()
case termbox.KeyCtrlP:
s.setCaptureMode(modeFilePerm)
s.startCapturingInput()
case termbox.KeyEnter:
if s.captureInput {
if curFile, err := s.CurrentDir.CurrentFile(); err == nil {
switch s.captureMode {
case modeExitCommand:
return ExitCommand{command: string(s.commandString),
args: []string{path.Join(s.CurrentDir.AbsPath, curFile.Name())}}
case modeFilePerm:
m, err := strconv.ParseUint(string(s.commandString), 8, 64)
if err == nil {
err = os.Chmod(curFile.Name(), os.FileMode(m))
if err != nil {
fatal(err)
}
s.CurrentDir.UpdateContents()
}
}
}
s.stopCapturingInput()
}
}
switch ev.Ch {
case 'q':
if s.state == Help {
s.toggleHelp()
} else {
break MainLoop
}
case '/':
s.setCaptureMode(modeSearch)
s.startCapturingInput()
case ':':
s.setCaptureMode(modeExitCommand)
s.startCapturingInput()
case 'h':
s.CurrentDir.SetShowHidden(!s.CurrentDir.ShowHidden)
case 'a':
s.exitCurrentDirectory()
s.exitCurrentDirectory()
case 'e':
s.jumpUp()
case 'd':
s.jumpDown()
case 'p':
s.togglePermissions()
case 'c':
s.toggleIndexToExtremities()
}
}
}
// Return the directory we end up in
currentItem, err := s.CurrentDir.CurrentFile()
if err == nil && currentItem.IsDir() && os.Getenv("EnterLastSelected") == "1" {
return ExitCommand{command: "cd", args: []string{path.Join(s.CurrentDir.AbsPath, currentItem.Name())}}
} else {
return ExitCommand{command: "cd", args: []string{s.CurrentDir.AbsPath}}
}
}
// Print error message to stderr and exit with error code 1
func fatal(err error) {
fmt.Fprintln(os.Stderr, fmt.Sprintf("Error: %v", err))
os.Exit(1)
}
func main() {
var err error
for _, arg := range os.Args {
switch arg {
case "-h", "--help":
fmt.Fprintln(os.Stderr, "itree - A visual file system navigation tool.\n"+
"Press h for information on hotkeys.")
os.Exit(0)
}
}
cwd, err := os.Getwd()
if err != nil {
panic("Cannot get current working directory")
}
cwd, err = filepath.Abs(cwd)
if err != nil {
panic("Cannot get absolute directory.")
}
// Initialize the library that draws to the terminal
err = termbox.Init()
if err != nil {
panic(err)
}
defer termbox.Close()
// Set the current directory context
var curDir *ctx.Directory
curDir, err = ctx.CreateDirectoryChain(cwd)
if curDir == nil {
fatal(err)
}
if err != nil {
fatal(err)
}
s := Screen{searchString: make([]rune, 0, 100),
commandString: make([]rune, 0, 100),
CurrentDir: curDir,
state: Directory,
captureMode: modeSearch,
showPermissions: false,
maxLevelWidth: 15,
highlightedColor: termbox.ColorCyan,
filteredColor: termbox.ColorGreen,
directoryColor: termbox.ColorYellow,
fileColor: termbox.ColorWhite,
}
exitCommand := s.Main()
// Print the command we want to execute in the current shell
// The companion shell script will execute this command in the current shell.
fmt.Print(exitCommand.FullCommand())
}