-
Notifications
You must be signed in to change notification settings - Fork 138
/
termdashdemo.go
997 lines (909 loc) · 23.6 KB
/
termdashdemo.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
// Copyright 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Binary termdashdemo demonstrates the functionality of termdash and its various widgets.
// Exits when 'q' is pressed.
package main
import (
"context"
"flag"
"fmt"
"image"
"log"
"math"
"math/rand"
"sync"
"time"
"github.com/mum4k/termdash"
"github.com/mum4k/termdash/align"
"github.com/mum4k/termdash/cell"
"github.com/mum4k/termdash/container"
"github.com/mum4k/termdash/container/grid"
"github.com/mum4k/termdash/keyboard"
"github.com/mum4k/termdash/linestyle"
"github.com/mum4k/termdash/terminal/tcell"
"github.com/mum4k/termdash/terminal/termbox"
"github.com/mum4k/termdash/terminal/terminalapi"
"github.com/mum4k/termdash/widgets/barchart"
"github.com/mum4k/termdash/widgets/button"
"github.com/mum4k/termdash/widgets/donut"
"github.com/mum4k/termdash/widgets/gauge"
"github.com/mum4k/termdash/widgets/linechart"
"github.com/mum4k/termdash/widgets/segmentdisplay"
"github.com/mum4k/termdash/widgets/sparkline"
"github.com/mum4k/termdash/widgets/text"
"github.com/mum4k/termdash/widgets/textinput"
)
// redrawInterval is how often termdash redraws the screen.
const redrawInterval = 250 * time.Millisecond
// widgets holds the widgets used by this demo.
type widgets struct {
segDist *segmentdisplay.SegmentDisplay
input *textinput.TextInput
rollT *text.Text
spGreen *sparkline.SparkLine
spRed *sparkline.SparkLine
gauge *gauge.Gauge
heartLC *linechart.LineChart
barChart *barchart.BarChart
donut *donut.Donut
leftB *button.Button
rightB *button.Button
sineLC *linechart.LineChart
buttons *layoutButtons
}
// newWidgets creates all widgets used by this demo.
func newWidgets(ctx context.Context, t terminalapi.Terminal, c *container.Container) (*widgets, error) {
updateText := make(chan string)
sd, err := newSegmentDisplay(ctx, t, updateText)
if err != nil {
return nil, err
}
input, err := newTextInput(updateText)
if err != nil {
return nil, err
}
rollT, err := newRollText(ctx)
if err != nil {
return nil, err
}
spGreen, spRed, err := newSparkLines(ctx)
if err != nil {
return nil, err
}
g, err := newGauge(ctx)
if err != nil {
return nil, err
}
heartLC, err := newHeartbeat(ctx)
if err != nil {
return nil, err
}
bc, err := newBarChart(ctx)
if err != nil {
return nil, err
}
don, err := newDonut(ctx)
if err != nil {
return nil, err
}
leftB, rightB, sineLC, err := newSines(ctx)
if err != nil {
return nil, err
}
return &widgets{
segDist: sd,
input: input,
rollT: rollT,
spGreen: spGreen,
spRed: spRed,
gauge: g,
heartLC: heartLC,
barChart: bc,
donut: don,
leftB: leftB,
rightB: rightB,
sineLC: sineLC,
}, nil
}
// layoutType represents the possible layouts the buttons switch between.
type layoutType int
const (
// layoutAll displays all the widgets.
layoutAll layoutType = iota
// layoutText focuses onto the text widget.
layoutText
// layoutSparkLines focuses onto the sparklines.
layoutSparkLines
// layoutLineChart focuses onto the linechart.
layoutLineChart
)
// gridLayout prepares container options that represent the desired screen layout.
// This function demonstrates the use of the grid builder.
// gridLayout() and contLayout() demonstrate the two available layout APIs and
// both produce equivalent layouts for layoutType layoutAll.
func gridLayout(w *widgets, lt layoutType) ([]container.Option, error) {
leftRows := []grid.Element{
grid.RowHeightPerc(25,
grid.Widget(w.segDist,
container.Border(linestyle.Light),
container.BorderTitle("Press Esc to quit"),
),
),
grid.RowHeightPerc(5,
grid.Widget(w.input),
),
grid.RowHeightPerc(5,
grid.ColWidthPerc(25,
grid.Widget(w.buttons.allB),
),
grid.ColWidthPerc(25,
grid.Widget(w.buttons.textB),
),
grid.ColWidthPerc(25,
grid.Widget(w.buttons.spB),
),
grid.ColWidthPerc(25,
grid.Widget(w.buttons.lcB),
),
),
}
switch lt {
case layoutAll:
leftRows = append(leftRows,
grid.RowHeightPerc(20,
grid.ColWidthPerc(50,
grid.Widget(w.rollT,
container.Border(linestyle.Light),
container.BorderTitle("A rolling text"),
),
),
grid.ColWidthPerc(50,
grid.RowHeightPerc(50,
grid.Widget(w.spGreen,
container.Border(linestyle.Light),
container.BorderTitle("Green SparkLine"),
),
),
grid.RowHeightPerc(50,
grid.Widget(w.spRed,
container.Border(linestyle.Light),
container.BorderTitle("Red SparkLine"),
),
),
),
),
grid.RowHeightPerc(7,
grid.Widget(w.gauge,
container.Border(linestyle.Light),
container.BorderTitle("A Gauge"),
container.BorderColor(cell.ColorNumber(39)),
),
),
grid.RowHeightPerc(38,
grid.Widget(w.heartLC,
container.Border(linestyle.Light),
container.BorderTitle("A LineChart"),
),
),
)
case layoutText:
leftRows = append(leftRows,
grid.RowHeightPerc(65,
grid.Widget(w.rollT,
container.Border(linestyle.Light),
container.BorderTitle("A rolling text"),
),
),
)
case layoutSparkLines:
leftRows = append(leftRows,
grid.RowHeightPerc(32,
grid.Widget(w.spGreen,
container.Border(linestyle.Light),
container.BorderTitle("Green SparkLine"),
),
),
grid.RowHeightPerc(33,
grid.Widget(w.spRed,
container.Border(linestyle.Light),
container.BorderTitle("Red SparkLine"),
),
),
)
case layoutLineChart:
leftRows = append(leftRows,
grid.RowHeightPerc(65,
grid.Widget(w.heartLC,
container.Border(linestyle.Light),
container.BorderTitle("A LineChart"),
),
),
)
}
builder := grid.New()
builder.Add(
grid.ColWidthPerc(70, leftRows...),
)
builder.Add(
grid.ColWidthPerc(30,
grid.RowHeightPerc(30,
grid.Widget(w.barChart,
container.Border(linestyle.Light),
container.BorderTitle("BarChart"),
container.BorderTitleAlignRight(),
),
),
grid.RowHeightPerc(21,
grid.Widget(w.donut,
container.Border(linestyle.Light),
container.BorderTitle("A Donut"),
container.BorderTitleAlignRight(),
),
),
grid.RowHeightPerc(40,
grid.Widget(w.sineLC,
container.Border(linestyle.Light),
container.BorderTitle("Multiple series"),
container.BorderTitleAlignRight(),
),
),
grid.RowHeightPerc(9,
grid.ColWidthPerc(50,
grid.Widget(w.leftB,
container.AlignHorizontal(align.HorizontalRight),
container.PaddingRight(1),
),
),
grid.ColWidthPerc(50,
grid.Widget(w.rightB,
container.AlignHorizontal(align.HorizontalLeft),
container.PaddingLeft(1),
),
),
),
),
)
gridOpts, err := builder.Build()
if err != nil {
return nil, err
}
return gridOpts, nil
}
// contLayout prepares container options that represent the desired screen layout.
// This function demonstrates the direct use of the container API.
// gridLayout() and contLayout() demonstrate the two available layout APIs and
// both produce equivalent layouts for layoutType layoutAll.
// contLayout only produces layoutAll.
func contLayout(w *widgets) ([]container.Option, error) {
buttonRow := []container.Option{
container.SplitVertical(
container.Left(
container.SplitVertical(
container.Left(
container.PlaceWidget(w.buttons.allB),
),
container.Right(
container.PlaceWidget(w.buttons.textB),
),
),
),
container.Right(
container.SplitVertical(
container.Left(
container.PlaceWidget(w.buttons.spB),
),
container.Right(
container.PlaceWidget(w.buttons.lcB),
),
),
),
),
}
textAndSparks := []container.Option{
container.SplitVertical(
container.Left(
container.Border(linestyle.Light),
container.BorderTitle("A rolling text"),
container.PlaceWidget(w.rollT),
),
container.Right(
container.SplitHorizontal(
container.Top(
container.Border(linestyle.Light),
container.BorderTitle("Green SparkLine"),
container.PlaceWidget(w.spGreen),
),
container.Bottom(
container.Border(linestyle.Light),
container.BorderTitle("Red SparkLine"),
container.PlaceWidget(w.spRed),
),
),
),
),
}
segmentTextInputSparks := []container.Option{
container.SplitHorizontal(
container.Top(
container.Border(linestyle.Light),
container.BorderTitle("Press Esc to quit"),
container.PlaceWidget(w.segDist),
),
container.Bottom(
container.SplitHorizontal(
container.Top(
container.SplitHorizontal(
container.Top(
container.PlaceWidget(w.input),
),
container.Bottom(buttonRow...),
),
),
container.Bottom(textAndSparks...),
container.SplitPercent(40),
),
),
container.SplitPercent(50),
),
}
gaugeAndHeartbeat := []container.Option{
container.SplitHorizontal(
container.Top(
container.Border(linestyle.Light),
container.BorderTitle("A Gauge"),
container.BorderColor(cell.ColorNumber(39)),
container.PlaceWidget(w.gauge),
),
container.Bottom(
container.Border(linestyle.Light),
container.BorderTitle("A LineChart"),
container.PlaceWidget(w.heartLC),
),
container.SplitPercent(20),
),
}
leftSide := []container.Option{
container.SplitHorizontal(
container.Top(segmentTextInputSparks...),
container.Bottom(gaugeAndHeartbeat...),
container.SplitPercent(50),
),
}
lcAndButtons := []container.Option{
container.SplitHorizontal(
container.Top(
container.Border(linestyle.Light),
container.BorderTitle("Multiple series"),
container.BorderTitleAlignRight(),
container.PlaceWidget(w.sineLC),
),
container.Bottom(
container.SplitVertical(
container.Left(
container.PlaceWidget(w.leftB),
container.AlignHorizontal(align.HorizontalRight),
container.PaddingRight(1),
),
container.Right(
container.PlaceWidget(w.rightB),
container.AlignHorizontal(align.HorizontalLeft),
container.PaddingLeft(1),
),
),
),
container.SplitPercent(80),
),
}
rightSide := []container.Option{
container.SplitHorizontal(
container.Top(
container.Border(linestyle.Light),
container.BorderTitle("BarChart"),
container.PlaceWidget(w.barChart),
container.BorderTitleAlignRight(),
),
container.Bottom(
container.SplitHorizontal(
container.Top(
container.Border(linestyle.Light),
container.BorderTitle("A Donut"),
container.BorderTitleAlignRight(),
container.PlaceWidget(w.donut),
),
container.Bottom(lcAndButtons...),
container.SplitPercent(30),
),
),
container.SplitPercent(30),
),
}
return []container.Option{
container.SplitVertical(
container.Left(leftSide...),
container.Right(rightSide...),
container.SplitPercent(70),
),
}, nil
}
// rootID is the ID assigned to the root container.
const rootID = "root"
// Terminal implementations
const (
termboxTerminal = "termbox"
tcellTerminal = "tcell"
)
func main() {
terminalPtr := flag.String("terminal",
"tcell",
"The terminal implementation to use. Available implementations are 'termbox' and 'tcell' (default = tcell).")
flag.Parse()
var t terminalapi.Terminal
var err error
switch terminal := *terminalPtr; terminal {
case termboxTerminal:
t, err = termbox.New(termbox.ColorMode(terminalapi.ColorMode256))
case tcellTerminal:
t, err = tcell.New(tcell.ColorMode(terminalapi.ColorMode256))
default:
log.Fatalf("Unknown terminal implementation '%s' specified. Please choose between 'termbox' and 'tcell'.", terminal)
return
}
if err != nil {
panic(err)
}
defer t.Close()
c, err := container.New(t, container.ID(rootID))
if err != nil {
panic(err)
}
ctx, cancel := context.WithCancel(context.Background())
w, err := newWidgets(ctx, t, c)
if err != nil {
panic(err)
}
lb, err := newLayoutButtons(c, w)
if err != nil {
panic(err)
}
w.buttons = lb
gridOpts, err := gridLayout(w, layoutAll) // equivalent to contLayout(w)
if err != nil {
panic(err)
}
if err := c.Update(rootID, gridOpts...); err != nil {
panic(err)
}
quitter := func(k *terminalapi.Keyboard) {
if k.Key == keyboard.KeyEsc || k.Key == keyboard.KeyCtrlC {
cancel()
}
}
if err := termdash.Run(ctx, t, c, termdash.KeyboardSubscriber(quitter), termdash.RedrawInterval(redrawInterval)); err != nil {
panic(err)
}
}
// periodic executes the provided closure periodically every interval.
// Exits when the context expires.
func periodic(ctx context.Context, interval time.Duration, fn func() error) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if err := fn(); err != nil {
panic(err)
}
case <-ctx.Done():
return
}
}
}
// textState creates a rotated state for the text we are displaying.
func textState(text string, capacity, step int) []rune {
if capacity == 0 {
return nil
}
var state []rune
for i := 0; i < capacity; i++ {
state = append(state, ' ')
}
state = append(state, []rune(text)...)
step = step % len(state)
return rotateRunes(state, step)
}
// newTextInput creates a new TextInput field that changes the text on the
// SegmentDisplay.
func newTextInput(updateText chan<- string) (*textinput.TextInput, error) {
input, err := textinput.New(
textinput.Label("Change text to: ", cell.FgColor(cell.ColorNumber(33))),
textinput.MaxWidthCells(20),
textinput.PlaceHolder("enter any text"),
textinput.OnSubmit(func(text string) error {
updateText <- text
return nil
}),
textinput.ClearOnSubmit(),
)
if err != nil {
return nil, err
}
return input, err
}
// newSegmentDisplay creates a new SegmentDisplay that initially shows the
// Termdash name. Shows any text that is sent over the channel.
func newSegmentDisplay(ctx context.Context, t terminalapi.Terminal, updateText <-chan string) (*segmentdisplay.SegmentDisplay, error) {
sd, err := segmentdisplay.New()
if err != nil {
return nil, err
}
colors := []cell.Color{
cell.ColorNumber(33),
cell.ColorRed,
cell.ColorYellow,
cell.ColorNumber(33),
cell.ColorGreen,
cell.ColorRed,
cell.ColorGreen,
cell.ColorRed,
}
text := "Termdash"
step := 0
go func() {
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
capacity := 0
termSize := t.Size()
for {
select {
case <-ticker.C:
if capacity == 0 {
// The segment display only knows its capacity after both
// text size and terminal size are known.
capacity = sd.Capacity()
}
if t.Size().Eq(image.ZP) || !t.Size().Eq(termSize) {
// Update the capacity initially the first time the
// terminal reports a non-zero size and then every time the
// terminal resizes.
//
// This is better than updating the capacity on every
// iteration since that leads to edge cases - segment
// display capacity depends on the length of text and here
// we are trying to adjust the text length to the capacity.
termSize = t.Size()
capacity = sd.Capacity()
}
state := textState(text, capacity, step)
var chunks []*segmentdisplay.TextChunk
for i := 0; i < capacity; i++ {
if i >= len(state) {
break
}
color := colors[i%len(colors)]
chunks = append(chunks, segmentdisplay.NewChunk(
string(state[i]),
segmentdisplay.WriteCellOpts(cell.FgColor(color)),
))
}
if len(chunks) == 0 {
continue
}
if err := sd.Write(chunks); err != nil {
panic(err)
}
step++
case t := <-updateText:
text = t
sd.Reset()
step = 0
case <-ctx.Done():
return
}
}
}()
return sd, nil
}
// newRollText creates a new Text widget that displays rolling text.
func newRollText(ctx context.Context) (*text.Text, error) {
t, err := text.New(text.RollContent())
if err != nil {
return nil, err
}
i := 0
go periodic(ctx, 1*time.Second, func() error {
if err := t.Write(fmt.Sprintf("Writing line %d.\n", i), text.WriteCellOpts(cell.FgColor(cell.ColorNumber(142)))); err != nil {
return err
}
i++
return nil
})
return t, nil
}
// newSparkLines creates two new sparklines displaying random values.
func newSparkLines(ctx context.Context) (*sparkline.SparkLine, *sparkline.SparkLine, error) {
spGreen, err := sparkline.New(
sparkline.Color(cell.ColorGreen),
)
if err != nil {
return nil, nil, err
}
const max = 100
go periodic(ctx, 250*time.Millisecond, func() error {
v := int(rand.Int31n(max + 1))
return spGreen.Add([]int{v})
})
spRed, err := sparkline.New(
sparkline.Color(cell.ColorRed),
)
if err != nil {
return nil, nil, err
}
go periodic(ctx, 500*time.Millisecond, func() error {
v := int(rand.Int31n(max + 1))
return spRed.Add([]int{v})
})
return spGreen, spRed, nil
}
// newGauge creates a demo Gauge widget.
func newGauge(ctx context.Context) (*gauge.Gauge, error) {
g, err := gauge.New()
if err != nil {
return nil, err
}
const start = 35
progress := start
go periodic(ctx, 2*time.Second, func() error {
if err := g.Percent(progress); err != nil {
return err
}
progress++
if progress > 100 {
progress = start
}
return nil
})
return g, nil
}
// newDonut creates a demo Donut widget.
func newDonut(ctx context.Context) (*donut.Donut, error) {
d, err := donut.New(donut.CellOpts(
cell.FgColor(cell.ColorNumber(33))),
)
if err != nil {
return nil, err
}
const start = 35
progress := start
go periodic(ctx, 500*time.Millisecond, func() error {
if err := d.Percent(progress); err != nil {
return err
}
progress++
if progress > 100 {
progress = start
}
return nil
})
return d, nil
}
// newHeartbeat returns a line chart that displays a heartbeat-like progression.
func newHeartbeat(ctx context.Context) (*linechart.LineChart, error) {
var inputs []float64
for i := 0; i < 100; i++ {
v := math.Pow(math.Sin(float64(i)), 63) * math.Sin(float64(i)+1.5) * 8
inputs = append(inputs, v)
}
lc, err := linechart.New(
linechart.AxesCellOpts(cell.FgColor(cell.ColorRed)),
linechart.YLabelCellOpts(cell.FgColor(cell.ColorGreen)),
linechart.XLabelCellOpts(cell.FgColor(cell.ColorGreen)),
)
if err != nil {
return nil, err
}
step := 0
go periodic(ctx, redrawInterval/3, func() error {
step = (step + 1) % len(inputs)
return lc.Series("heartbeat", rotateFloats(inputs, step),
linechart.SeriesCellOpts(cell.FgColor(cell.ColorNumber(87))),
linechart.SeriesXLabels(map[int]string{
0: "zero",
}),
)
})
return lc, nil
}
// newBarChart returns a BarcChart that displays random values on multiple bars.
func newBarChart(ctx context.Context) (*barchart.BarChart, error) {
bc, err := barchart.New(
barchart.BarColors([]cell.Color{
cell.ColorNumber(33),
cell.ColorNumber(39),
cell.ColorNumber(45),
cell.ColorNumber(51),
cell.ColorNumber(81),
cell.ColorNumber(87),
}),
barchart.ValueColors([]cell.Color{
cell.ColorBlack,
cell.ColorBlack,
cell.ColorBlack,
cell.ColorBlack,
cell.ColorBlack,
cell.ColorBlack,
}),
barchart.ShowValues(),
)
if err != nil {
return nil, err
}
const (
bars = 6
max = 100
)
values := make([]int, bars)
go periodic(ctx, 1*time.Second, func() error {
for i := range values {
values[i] = int(rand.Int31n(max + 1))
}
return bc.Values(values, max)
})
return bc, nil
}
// distance is a thread-safe int value used by the newSince method.
// Buttons write it and the line chart reads it.
type distance struct {
v int
mu sync.Mutex
}
// add adds the provided value to the one stored.
func (d *distance) add(v int) {
d.mu.Lock()
defer d.mu.Unlock()
d.v += v
}
// get returns the current value.
func (d *distance) get() int {
d.mu.Lock()
defer d.mu.Unlock()
return d.v
}
// newSines returns a line chart that displays multiple sine series and two buttons.
// The left button shifts the second series relative to the first series to
// the left and the right button shifts it to the right.
func newSines(ctx context.Context) (left, right *button.Button, lc *linechart.LineChart, err error) {
var inputs []float64
for i := 0; i < 200; i++ {
v := math.Sin(float64(i) / 100 * math.Pi)
inputs = append(inputs, v)
}
sineLc, err := linechart.New(
linechart.AxesCellOpts(cell.FgColor(cell.ColorRed)),
linechart.YLabelCellOpts(cell.FgColor(cell.ColorGreen)),
linechart.XLabelCellOpts(cell.FgColor(cell.ColorGreen)),
)
if err != nil {
return nil, nil, nil, err
}
step1 := 0
secondDist := &distance{v: 100}
go periodic(ctx, redrawInterval/3, func() error {
step1 = (step1 + 1) % len(inputs)
if err := lc.Series("first", rotateFloats(inputs, step1),
linechart.SeriesCellOpts(cell.FgColor(cell.ColorNumber(33))),
); err != nil {
return err
}
step2 := (step1 + secondDist.get()) % len(inputs)
return lc.Series("second", rotateFloats(inputs, step2), linechart.SeriesCellOpts(cell.FgColor(cell.ColorWhite)))
})
// diff is the difference a single button press adds or removes to the
// second series.
const diff = 20
leftB, err := button.New("(l)eft", func() error {
secondDist.add(diff)
return nil
},
button.GlobalKey('l'),
button.WidthFor("(r)ight"),
button.FillColor(cell.ColorNumber(220)),
)
if err != nil {
return nil, nil, nil, err
}
rightB, err := button.New("(r)ight", func() error {
secondDist.add(-diff)
return nil
},
button.GlobalKey('r'),
button.FillColor(cell.ColorNumber(196)),
)
if err != nil {
return nil, nil, nil, err
}
return leftB, rightB, sineLc, nil
}
// setLayout sets the specified layout.
func setLayout(c *container.Container, w *widgets, lt layoutType) error {
gridOpts, err := gridLayout(w, lt)
if err != nil {
return err
}
return c.Update(rootID, gridOpts...)
}
// layoutButtons are buttons that change the layout.
type layoutButtons struct {
allB *button.Button
textB *button.Button
spB *button.Button
lcB *button.Button
}
// newLayoutButtons returns buttons that dynamically switch the layouts.
func newLayoutButtons(c *container.Container, w *widgets) (*layoutButtons, error) {
opts := []button.Option{
button.WidthFor("sparklines"),
button.FillColor(cell.ColorNumber(220)),
button.Height(1),
}
allB, err := button.New("all", func() error {
return setLayout(c, w, layoutAll)
}, opts...)
if err != nil {
return nil, err
}
textB, err := button.New("text", func() error {
return setLayout(c, w, layoutText)
}, opts...)
if err != nil {
return nil, err
}
spB, err := button.New("sparklines", func() error {
return setLayout(c, w, layoutSparkLines)
}, opts...)
if err != nil {
return nil, err
}
lcB, err := button.New("linechart", func() error {
return setLayout(c, w, layoutLineChart)
}, opts...)
if err != nil {
return nil, err
}
return &layoutButtons{
allB: allB,
textB: textB,
spB: spB,
lcB: lcB,
}, nil
}
// rotateFloats returns a new slice with inputs rotated by step.
// I.e. for a step of one:
//
// inputs[0] -> inputs[len(inputs)-1]
// inputs[1] -> inputs[0]
//
// And so on.
func rotateFloats(inputs []float64, step int) []float64 {
return append(inputs[step:], inputs[:step]...)
}
// rotateRunes returns a new slice with inputs rotated by step.
// I.e. for a step of one:
//
// inputs[0] -> inputs[len(inputs)-1]
// inputs[1] -> inputs[0]
//
// And so on.
func rotateRunes(inputs []rune, step int) []rune {
return append(inputs[step:], inputs[:step]...)
}