/
layout.go
695 lines (593 loc) · 17.2 KB
/
layout.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
package peco
import (
"fmt"
"time"
"unicode/utf8"
"github.com/mattn/go-runewidth"
"github.com/nsf/termbox-go"
)
var extraOffset = 0
// Crop returns a new LineBuffer whose contents are
// bound within the given range
func (pf PageCrop) Crop(in LineBuffer) LineBuffer {
out := &FilteredLineBuffer{
src: in,
selection: []int{},
}
s := pf.perPage * (pf.currentPage - 1)
e := s + pf.perPage
if s > in.Size() {
return out
}
if e >= in.Size() {
e = in.Size()
}
for i := s; i < e; i++ {
out.SelectSourceLineAt(i)
}
return out
}
const (
// LayoutTypeTopDown is the default. All the items read from top to bottom
LayoutTypeTopDown = "top-down"
// LayoutTypeBottomUp changes the layout to read from bottom to up
LayoutTypeBottomUp = "bottom-up"
)
// IsValidLayoutType checks if a string is a supported layout type
func IsValidLayoutType(v LayoutType) bool {
return v == LayoutTypeTopDown || v == LayoutTypeBottomUp
}
const (
// AnchorTop anchors elements towards the top of the screen
AnchorTop VerticalAnchor = iota + 1
// AnchorBottom anchors elements towards the bottom of the screen
AnchorBottom
)
// IsValidVerticalAnchor checks if the specified anchor is supported
func IsValidVerticalAnchor(anchor VerticalAnchor) bool {
return anchor == AnchorTop || anchor == AnchorBottom
}
// Utility function
func mergeAttribute(a, b termbox.Attribute) termbox.Attribute {
if a&0x0F == 0 || b&0x0F == 0 {
return a | b
}
return ((a - 1) | (b - 1)) + 1
}
// Utility function
func printScreen(x, y int, fg, bg termbox.Attribute, msg string, fill bool) int {
return printScreenWithOffset(x, y, 0, fg, bg, msg, fill)
}
func printScreenWithOffset(x, y, xOffset int, fg, bg termbox.Attribute, msg string, fill bool) int {
var written int
for len(msg) > 0 {
c, w := utf8.DecodeRuneInString(msg)
if c == utf8.RuneError {
c = '?'
w = 1
}
msg = msg[w:]
if c == '\t' {
// In case we found a tab, we draw it as 4 spaces
n := 4 - (x+xOffset)%4
for i := 0; i <= n; i++ {
screen.SetCell(x+i, y, ' ', fg, bg)
}
written += n
x += n
} else {
screen.SetCell(x, y, c, fg, bg)
n := runewidth.RuneWidth(c)
x += n
written += n
}
}
if !fill {
return written
}
width, _ := screen.Size()
for ; x < width; x++ {
screen.SetCell(x, y, ' ', fg, bg)
}
written += width - x
return written
}
// NewAnchorSettings creates a new AnchorSetting struct. Panics if
// an unknown VerticalAnchor is sent
func NewAnchorSettings(anchor VerticalAnchor, offset int) *AnchorSettings {
if !IsValidVerticalAnchor(anchor) {
panic("Invalid vertical anchor specified")
}
return &AnchorSettings{anchor, offset}
}
// AnchorPosition returns the starting y-offset, based on the
// anchor type and offset
func (as AnchorSettings) AnchorPosition() int {
var pos int
switch as.anchor {
case AnchorTop:
pos = as.anchorOffset
case AnchorBottom:
_, h := screen.Size()
pos = h - as.anchorOffset - 1 // -1 is required because y is 0 base, but h is 1 base
default:
panic("Unknown anchor type!")
}
return pos
}
// NewUserPrompt creates a new UserPrompt struct
func NewUserPrompt(ctx *Ctx, anchor VerticalAnchor, anchorOffset int) *UserPrompt {
prefix := ctx.config.Prompt
if len(prefix) <= 0 { // default
prefix = "QUERY>"
}
prefixLen := runewidth.StringWidth(prefix)
return &UserPrompt{
Ctx: ctx,
AnchorSettings: &AnchorSettings{anchor, anchorOffset},
prefix: prefix,
prefixLen: prefixLen,
basicStyle: ctx.config.Style.Basic,
queryStyle: ctx.config.Style.Query,
}
}
// Draw draws the query prompt
func (u UserPrompt) Draw() {
trace("UserPrompt.Draw: START")
defer trace("UserPrompt.Draw: END")
location := u.AnchorPosition()
// print "QUERY>"
printScreen(0, location, u.basicStyle.fg, u.basicStyle.bg, u.prefix, false)
pos := u.CaretPos()
if pos <= 0 { // XXX Do we really need this?
u.SetCaretPos(0) // sanity
}
qs := u.QueryString()
ql := u.QueryLen()
if pos > ql { // XXX Do we really need this?
u.SetCaretPos(ql)
}
fg := u.queryStyle.fg
bg := u.queryStyle.bg
switch ql {
case 0:
printScreen(u.prefixLen, location, fg, bg, "", true)
printScreen(u.prefixLen+1, location, fg|termbox.AttrReverse, bg|termbox.AttrReverse, " ", false)
case u.CaretPos():
// the entire string + the caret after the string
printScreen(u.prefixLen, location, fg, bg, "", true)
printScreen(u.prefixLen+1, location, fg, bg, qs, false)
printScreen(u.prefixLen+runewidth.StringWidth(qs)+1, location, fg|termbox.AttrReverse, bg|termbox.AttrReverse, " ", false)
default:
// the caret is in the middle of the string
prev := 0
for i, r := range []rune(u.Query()) {
fg := u.queryStyle.fg
bg := u.queryStyle.bg
if i == u.CaretPos() {
fg |= termbox.AttrReverse
bg |= termbox.AttrReverse
}
screen.SetCell(u.prefixLen+1+prev, location, r, fg, bg)
prev += runewidth.RuneWidth(r)
}
fg := u.queryStyle.fg
bg := u.queryStyle.bg
printScreen(u.prefixLen+prev+1, location, fg, bg, "", true)
}
width, _ := screen.Size()
pmsg := fmt.Sprintf("%s [%d (%d/%d)]", u.Filter().String(), u.currentPage.total, u.currentPage.page, u.currentPage.maxPage)
printScreen(width-runewidth.StringWidth(pmsg), location, u.basicStyle.fg, u.basicStyle.bg, pmsg, false)
screen.Flush()
}
// NewStatusBar creates a new StatusBar struct
func NewStatusBar(ctx *Ctx, anchor VerticalAnchor, anchorOffset int) *StatusBar {
return &StatusBar{
Ctx: ctx,
AnchorSettings: NewAnchorSettings(anchor, anchorOffset),
clearTimer: nil,
timerMutex: newMutex(),
basicStyle: ctx.config.Style.Basic,
}
}
func (s *StatusBar) stopTimer() {
s.timerMutex.Lock()
defer s.timerMutex.Unlock()
if t := s.clearTimer; t != nil {
t.Stop()
s.clearTimer = nil
}
}
func (s *StatusBar) setClearTimer(t *time.Timer) {
s.timerMutex.Lock()
defer s.timerMutex.Unlock()
s.clearTimer = t
}
// PrintStatus prints a new status message. This also resets the
// timer created by ClearStatus()
func (s *StatusBar) PrintStatus(msg string, clearDelay time.Duration) {
s.stopTimer()
s.timerMutex.Lock()
location := s.AnchorPosition()
w, _ := screen.Size()
width := runewidth.StringWidth(msg)
for width > w {
_, rw := utf8.DecodeRuneInString(msg)
width = width - rw
msg = msg[rw:]
}
var pad []byte
if w > width {
pad = make([]byte, w-width)
for i := 0; i < w-width; i++ {
pad[i] = ' '
}
}
fgAttr := s.basicStyle.fg
bgAttr := s.basicStyle.bg
if w > width {
printScreen(0, location, fgAttr, bgAttr, string(pad), false)
}
if width > 0 {
printScreen(w-width, location, fgAttr|termbox.AttrReverse|termbox.AttrBold|termbox.AttrReverse, bgAttr|termbox.AttrReverse, msg, false)
}
screen.Flush()
s.timerMutex.Unlock()
// if everything is successful AND the clearDelay timer is specified,
// then set a timer to clear the status
if clearDelay != 0 {
s.setClearTimer(time.AfterFunc(clearDelay, func() {
s.PrintStatus("", 0)
}))
}
}
// NewListArea creates a new ListArea struct
func NewListArea(ctx *Ctx, anchor VerticalAnchor, anchorOffset int, sortTopDown bool) *ListArea {
return &ListArea{
Ctx: ctx,
AnchorSettings: NewAnchorSettings(anchor, anchorOffset),
sortTopDown: sortTopDown,
displayCache: []Line{},
dirty: false,
basicStyle: ctx.config.Style.Basic,
queryStyle: ctx.config.Style.Query,
matchedStyle: ctx.config.Style.Matched,
selectedStyle: ctx.config.Style.Selected,
savedSelectionStyle: ctx.config.Style.SavedSelection,
}
}
func (l *ListArea) purgeDisplayCache() {
l.displayCache = []Line{}
}
func (l *ListArea) IsDirty() bool {
return l.dirty
}
func (l *ListArea) SetDirty(dirty bool) {
l.dirty = dirty
}
// Draw displays the ListArea on the screen
func (l *ListArea) Draw(parent Layout, perPage int, runningQuery bool) {
trace("ListArea.Draw: START")
defer trace("ListArea.Draw: END")
currentPage := l.currentPage
linebuf := l.GetCurrentLineBuffer()
// Should only get into this clause if we are RUNNING A QUERY.
// regular paging shouldn't be affected. This clause basically
// makes sure that we never have an empty screen when we are
// at a large enough page, but we don't have enough entries
// to fill that many pages in the buffer
if runningQuery {
bufsiz := linebuf.Size()
page := currentPage.page
for page > 1 {
if (currentPage.perPage*(page-1) < bufsiz) &&
(currentPage.perPage*page) >= bufsiz {
break
}
page--
}
if currentPage.page != page {
currentPage.page = page
parent.DrawPrompt()
}
}
pf := PageCrop{perPage: currentPage.perPage, currentPage: currentPage.page}
buf := pf.Crop(linebuf)
bufsiz := buf.Size()
// This protects us from losing the selected line in case our selected
// line is greater than the buffer
if lbufsiz := linebuf.Size(); lbufsiz > 0 && l.currentLine >= lbufsiz {
l.currentLine = lbufsiz - 1
}
// previously drawn lines are cached. first, truncate the cache
// to current size of the drawable area
if ldc := len(l.displayCache); ldc != perPage {
newCache := make([]Line, perPage)
copy(newCache, l.displayCache)
l.displayCache = newCache
}
var y int
start := l.AnchorPosition()
// If our buffer is smaller than perPage, we may need to
// clear some lines
trace("ListeArea.Draw: buffer size is %d, our view area is %d\n", bufsiz, perPage)
for n := bufsiz; n < perPage; n++ {
l.displayCache[n] = nil
if l.sortTopDown {
y = n + start
} else {
y = start - n
}
trace("ListArea.Draw: clearing row %d", y)
printScreen(0, y, l.basicStyle.fg, l.basicStyle.bg, "", true)
}
var cached, written int
var fgAttr, bgAttr termbox.Attribute
for n := 0; n < perPage; n++ {
switch {
case n+currentPage.offset == l.currentLine:
fgAttr = l.selectedStyle.fg
bgAttr = l.selectedStyle.bg
case l.SelectionContains(n + currentPage.offset):
fgAttr = l.savedSelectionStyle.fg
bgAttr = l.savedSelectionStyle.bg
default:
fgAttr = l.basicStyle.fg
bgAttr = l.basicStyle.bg
}
if n >= bufsiz {
break
}
if l.sortTopDown {
y = n + start
} else {
y = start - n
}
target, err := buf.LineAt(n)
if err != nil {
break
}
if l.IsDirty() || target.IsDirty() {
target.SetDirty(false)
} else if l.displayCache[n] == target {
cached++
continue
}
written++
l.displayCache[n] = target
x := -l.currentCol
xOffset := l.currentCol
line := target.DisplayString()
if l.IsSingleKeyJumpMode() || l.config.SingleKeyJump.ShowPrefix {
if n < len(l.config.SingleKeyJump.PrefixList) {
printScreenWithOffset(x, y, xOffset, fgAttr|termbox.AttrBold|termbox.AttrReverse, bgAttr, fmt.Sprintf("%c", l.config.SingleKeyJump.PrefixList[n]), false)
printScreenWithOffset(x+1, y, xOffset, fgAttr, bgAttr, " ", false)
} else {
printScreenWithOffset(x, y, xOffset, fgAttr, bgAttr, " ", false)
}
x += 2
}
matches := target.Indices()
if matches == nil {
printScreenWithOffset(x, y, xOffset, fgAttr, bgAttr, line, true)
continue
}
prev := x
index := 0
for _, m := range matches {
if m[0] > index {
c := line[index:m[0]]
n := printScreenWithOffset(prev, y, xOffset, fgAttr, bgAttr, c, false)
prev += n
index += len(c)
}
c := line[m[0]:m[1]]
n := printScreenWithOffset(prev, y, xOffset, l.matchedStyle.fg, mergeAttribute(bgAttr, l.matchedStyle.bg), c, true)
prev += n
index += len(c)
}
m := matches[len(matches)-1]
if m[0] > index {
printScreenWithOffset(prev, y, xOffset, l.queryStyle.fg, mergeAttribute(bgAttr, l.queryStyle.bg), line[m[0]:m[1]], true)
} else if len(line) > m[1] {
printScreenWithOffset(prev, y, xOffset, fgAttr, bgAttr, line[m[1]:len(line)], true)
}
}
l.SetDirty(false)
trace("ListArea.Draw: Written total of %d lines (%d cached)\n", written+cached, cached)
}
// NewDefaultLayout creates a new Layout in the default format (top-down)
func NewDefaultLayout(ctx *Ctx) *BasicLayout {
return &BasicLayout{
Ctx: ctx,
StatusBar: NewStatusBar(ctx, AnchorBottom, 0+extraOffset),
// The prompt is at the top
prompt: NewUserPrompt(ctx, AnchorTop, 0),
// The list area is at the top, after the prompt
// It's also displayed top-to-bottom order
list: NewListArea(ctx, AnchorTop, 1, true),
}
}
// NewBottomUpLayout creates a new Layout in bottom-up format
func NewBottomUpLayout(ctx *Ctx) *BasicLayout {
return &BasicLayout{
Ctx: ctx,
StatusBar: NewStatusBar(ctx, AnchorBottom, 0+extraOffset),
// The prompt is at the bottom, above the status bar
prompt: NewUserPrompt(ctx, AnchorBottom, 1+extraOffset),
// The list area is at the bottom, above the prompt
// It's displayed in bottom-to-top order
list: NewListArea(ctx, AnchorBottom, 2+extraOffset, false),
}
}
func (l *BasicLayout) PurgeDisplayCache() {
l.list.purgeDisplayCache()
}
// CalculatePage calculates which page we're displaying
func (l *BasicLayout) CalculatePage(perPage int) error {
buf := l.GetCurrentLineBuffer()
currentPage := l.currentPage
currentPage.page = (l.currentLine / perPage) + 1
currentPage.offset = (currentPage.page - 1) * perPage
currentPage.perPage = perPage
currentPage.total = buf.Size()
trace("BasicLayout.CalculatePage: %#v", currentPage)
if currentPage.total == 0 {
currentPage.maxPage = 1
} else {
currentPage.maxPage = ((currentPage.total + perPage - 1) / perPage)
}
if currentPage.maxPage < currentPage.page {
if buf.Size() == 0 {
// wait for targets
return fmt.Errorf("no targets or query. nothing to do")
}
l.currentLine = currentPage.offset
}
return nil
}
// DrawPrompt draws the prompt to the terminal
func (l *BasicLayout) DrawPrompt() {
l.prompt.Draw()
}
// DrawScreen draws the entire screen
func (l *BasicLayout) DrawScreen(runningQuery bool) {
trace("DrawScreen: START")
defer trace("DrawScreen: END")
perPage := linesPerPage()
if err := l.CalculatePage(perPage); err != nil {
return
}
l.DrawPrompt()
l.list.Draw(l, perPage, runningQuery)
if err := screen.Flush(); err != nil {
return
}
}
func linesPerPage() int {
_, height := screen.Size()
// list area is always the display area - 2 lines for prompt and status
reservedLines := 2 + extraOffset
return height - reservedLines
}
// MovePage scrolls the screen
func (l *BasicLayout) MovePage(p PagingRequest) (moved bool) {
switch p {
case ToScrollLeft, ToScrollRight:
moved = horizontalScroll(l, p)
default:
moved = verticalScroll(l, p)
}
return
}
// verticalScroll moves the cursor position vertically
func verticalScroll(l *BasicLayout, p PagingRequest) bool {
// Before we move, on which line were we located?
lineBefore := l.currentLine
defer func() { trace("currentLine changed from %d -> %d", lineBefore, l.currentLine) }()
cp := l.currentPage
buf := l.GetCurrentLineBuffer()
lcur := buf.Size()
defer func() {
for _, lno := range []int{lineBefore, l.currentLine} {
if oldLine, err := buf.LineAt(lno); err == nil {
trace("Setting line %d dirty", lno)
oldLine.SetDirty(true)
}
}
}()
lpp := linesPerPage()
if l.list.sortTopDown {
switch p.Type() {
case ToLineAbove:
l.currentLine--
case ToLineBelow:
l.currentLine++
case ToScrollPageDown:
l.currentLine += lpp
if cp.page == cp.maxPage-1 && lcur < l.currentLine && (lcur-lineBefore) < lpp {
l.currentLine = lcur - 1
}
case ToScrollPageUp:
l.currentLine -= lpp
case ToLineInPage:
l.currentLine = cp.perPage*(cp.page-1) + p.(JumpToLineRequest).Line()
}
} else {
switch p {
case ToLineAbove:
l.currentLine++
case ToLineBelow:
l.currentLine--
case ToScrollPageDown:
l.currentLine -= lpp
case ToScrollPageUp:
l.currentLine += lpp
case ToLineInPage:
l.currentLine = cp.perPage*(cp.page-1) - p.(JumpToLineRequest).Line()
}
}
if l.currentLine < 0 {
if lcur > 0 {
// Go to last page, if possible
l.currentLine = lcur - 1
} else {
l.currentLine = 0
}
} else if lcur > 0 && l.currentLine >= lcur {
l.currentLine = 0
}
// if we were in range mode, we need to do stuff. otherwise
// just bail out
if !l.IsRangeMode() {
return true
}
if l.list.sortTopDown {
if l.currentLine < l.selectionRangeStart {
for lineno := l.currentLine; lineno <= l.selectionRangeStart; lineno++ {
l.SelectionAdd(lineno)
}
switch {
case l.selectionRangeStart <= lineBefore:
for lineno := l.selectionRangeStart; lineno <= lcur && lineno < lineBefore; lineno++ {
l.SelectionRemove(lineno)
}
case lineBefore < l.currentLine:
for lineno := lineBefore; lineno < l.currentLine; lineno++ {
l.SelectionRemove(lineno)
}
}
} else {
for lineno := l.selectionRangeStart; lineno <= lcur && lineno <= l.currentLine; lineno++ {
l.SelectionAdd(lineno)
}
switch {
case lineBefore <= l.selectionRangeStart:
for lineno := lineBefore; lineno < l.selectionRangeStart; lineno++ {
l.SelectionRemove(lineno)
}
case l.currentLine < lineBefore:
for lineno := l.currentLine; lineno <= lineBefore; lineno++ {
l.SelectionRemove(lineno)
}
}
}
}
return true
}
// horizontalScroll scrolls screen horizontal
func horizontalScroll(l *BasicLayout, p PagingRequest) bool {
width, _ := screen.Size()
if p == ToScrollRight {
l.currentCol += width / 2
} else if l.currentCol > 0 {
l.currentCol -= width / 2
if l.currentCol < 0 {
l.currentCol = 0
}
} else {
return false
}
l.list.SetDirty(true)
return true
}