-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy patheditor.go
More file actions
1616 lines (1421 loc) · 40.1 KB
/
editor.go
File metadata and controls
1616 lines (1421 loc) · 40.1 KB
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
// MIT License
//
// Copyright (c) 2024 Andrew Healey
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package noter
import (
"fmt"
"image/color"
"log"
"sort"
"unicode"
"github.com/hajimehoshi/bitmapfont/v3"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/ebitenutil"
"github.com/hajimehoshi/ebiten/v2/inpututil"
"github.com/hajimehoshi/ebiten/v2/text"
"golang.org/x/image/font"
)
const (
EDITOR_DEFAULT_ROWS = 25
EDITOR_DEFAULT_COLS = 80
)
type editorLine struct {
prev *editorLine
next *editorLine
values []rune
}
type editorCursor struct {
line *editorLine
x int
}
func (c *editorCursor) FixPosition() {
limit := len(c.line.values) - 1
if c.x > limit {
c.x = limit
}
}
// Content is an interface to a clipboard or file to read/write data.
// We use this instead of io.ReadWriter as we do not want to handle
// errors or buffered reads in the Editor; we force that to the caller
// of the editor.
type Content interface {
ReadText() []byte // Read the entire content of the text clipboard.
WriteText([]byte) // Write replaces the entire content of the text clipboard.
}
// dummyContent provides a trivial text storage implementation.
type dummyContent struct {
content string
}
func (cb *dummyContent) ReadText() []byte {
return []byte(cb.content)
}
func (cb *dummyContent) WriteText(content []byte) {
// 'string' cast will make a duplicate of the content.
cb.content = string(content)
}
type fontInfo struct {
face font.Face // Font itself.
ascent int // ascent of the font above the baseline's origin.
xUnit int // xUnit is the text advance of the '0' glyph.
yUnit int // yUnit is the line height of the font.
}
// Create a new fontInfo
func newfontInfo(font_face font.Face) (fi *fontInfo) {
metrics := font_face.Metrics()
advance, _ := font_face.GlyphAdvance('0')
fi = &fontInfo{
face: font_face,
ascent: metrics.Ascent.Ceil(),
xUnit: advance.Ceil(),
yUnit: metrics.Height.Ceil(),
}
return fi
}
const (
EDIT_MODE = iota
SEARCH_MODE
)
var noop = func() bool { return false }
// Editor is a simple text editor, compliant to the ebiten.Game interface.
//
// The Meta or Control key can be used with the following command keys:
//
// | Keystroke | Action |
// | --- | --- |
// | COMMAND-S | Save the content. |
// | COMMAND-L | Load the content. |
// | COMMAND-C | Copy the selection to clipboard. |
// | COMMAND-V | Paste clipboard into the selection/current cursor. |
// | COMMAND-X | Cut the selection, saving a copy into the clipboard. |
// | COMMAND-F | Find text in the content. |
// | COMMAND-Q | Quit the editor. |
type Editor struct {
// Settable options
font_info *fontInfo
font_color color.Color
select_color color.Color
search_color color.Color
cursor_color color.Color
background_image *ebiten.Image
clipboard Content
content Content
content_name string
rows int
cols int
width int
height int
width_padding int
bot_bar bool
top_bar bool
// Internal state
screen *ebiten.Image
top_padding int
bot_padding int
mode uint
searchIndex int
searchTerm []rune
start *editorLine
firstVisible int
cursor *editorCursor
modified bool
highlighted map[*editorLine]map[int]bool
searchHighlights map[*editorLine]map[int]bool
undoStack []func() bool
quit func()
}
// EditorOption is an option that can be sent to NewEditor()
type EditorOption func(e *Editor)
// WithQuit sets the function to call when ^Q is pressed,
// nominally to quit the editor. The default is no action.
func WithQuit(opt func()) EditorOption {
return func(e *Editor) {
if opt == nil {
opt = func() {}
}
e.quit = opt
}
}
// WithContent sets the content accessor, and permits saving and loading.
// If set to nil, an in-memory content manager is used.
func WithContent(opt Content) EditorOption {
return func(e *Editor) {
if opt == nil {
opt = &dummyContent{}
}
e.content = opt
}
}
// WithContentName sets the name of the content
func WithContentName(opt string) EditorOption {
return func(e *Editor) {
e.content_name = opt
}
}
// WithTopBar enables the display of the first row as a top bar.
func WithTopBar(enabled bool) EditorOption {
return func(e *Editor) {
e.top_bar = enabled
}
}
// WithBottomBar enables the display of the last row as a help display.
func WithBottomBar(enabled bool) EditorOption {
return func(e *Editor) {
e.bot_bar = enabled
}
}
// WithClipboard sets the clipboard accessor.
// If set to nil, an in-memory content manager is used.
func WithClipboard(opt Content) EditorOption {
return func(e *Editor) {
if opt == nil {
opt = &dummyContent{}
}
e.clipboard = opt
}
}
// WithFontFace set the default font.
// If set to nil, the monospace font `github.com/hajimehoshi/bitmapfont/v3`
// is used.
func WithFontFace(opt font.Face) EditorOption {
return func(e *Editor) {
if opt == nil {
opt = bitmapfont.Face
}
e.font_info = newfontInfo(opt)
}
}
// WithFontColor sets the color of the text.
// It is recommended to have an Alpha component of 255.
func WithFontColor(opt color.Color) EditorOption {
return func(e *Editor) {
e.font_color = opt
}
}
// WithHighlightColor sets the color of the select highlight over the text.
// It is recommended to have an Alpha component of 70.
func WithHighlightColor(opt color.Color) EditorOption {
return func(e *Editor) {
e.select_color = opt
}
}
// WithSearchColor sets the color of the search highlight over the text.
// It is recommended to have an Alpha component of 70.
func WithSearchColor(opt color.Color) EditorOption {
return func(e *Editor) {
e.search_color = opt
}
}
// WithCursorColor sets the color of the cursor over the text.
// It is recommended to have an Alpha component of 90.
func WithCursorColor(opt color.Color) EditorOption {
return func(e *Editor) {
e.cursor_color = opt
}
}
// WithBackgroundColor sets the color of the background.
func WithBackgroundColor(opt color.Color) EditorOption {
return func(e *Editor) {
// Make a single pixel image with the background color.
// We will scale it to fit.
img := ebiten.NewImage(1, 1)
img.Fill(opt)
WithBackgroundImage(img)(e)
}
}
// WithBackgroundImage sets the ebiten.Image in the background.
// It will be scaled to fit the entire background of the editor.
func WithBackgroundImage(opt *ebiten.Image) EditorOption {
return func(e *Editor) {
e.background_image = opt
}
}
// WithRows sets the total number of rows in the editor, including
// the top bar and bottom bar, if enabled. If set to < 0, then:
// - if WithHeight is set, then the maximum number of rows that would
// fit, based on font height, is used.
// - if WithHeight is not set, then the number of rows defaults to 25.
func WithRows(opt int) EditorOption {
return func(e *Editor) {
e.rows = opt
}
}
// WidthHeight sets the image height of the editor.
// If WithRows is set, the font is scaled appropriately to the height.
// If WithRows is not set, the maximum number of rows that would fit
// are used, with any additional padding to the bottom of the editor.
// If not set, see the 'WithRows()' option for the calculation.
func WithHeight(opt int) EditorOption {
return func(e *Editor) {
e.height = opt
}
}
// WithColumns sets the total number of columns in the editor, including
// the line-number area, if enabled. If set to < 0, then:
// - if WithWidth is set, then the maximum number of columns that would
// fit, based on font advance of the glyph '0', is used.
// - if WithWidth is not set, then the number of columns defaults to 80.
func WithColumns(opt int) EditorOption {
return func(e *Editor) {
e.cols = opt
}
}
// WidthWidth sets the image width of the editor.
// If WithColumns is set, the font is scaled appropriately to the width.
// If WithColumns is not set, the maximum number of columns that would fit
// are used, with any additional padding to the bottom of the editor.
// If not set, see the 'WithColumns()' option for the calculation.
func WithWidth(opt int) EditorOption {
return func(e *Editor) {
e.width = opt
}
}
// WithWidthPadding sets the left and right side padding, in pixels.
// If not set, the default is 1/2 of the width of the text advance
// of the font's rune '0'.
func WithWithPadding(opt int) EditorOption {
return func(e *Editor) {
e.width_padding = opt
}
}
// NewEditor creates a new editor. See the EditorOption type for
// available options that can be passed to change its defaults.
//
// If neither the WithHeight nor WithRows options are set, the editor
// defaults to 25 rows.
// The resulting image width is `rows * font.Face.Metrics().Height`
//
// If neither the WithWidth nor the WithCols options are set, the
// editor defaults to 80 columns. The resulting image width
// is `cols * font.Face.GlyphAdvance('0')`
func NewEditor(options ...EditorOption) (e *Editor) {
e = &Editor{
rows: -1,
cols: -1,
width: -1,
height: -1,
width_padding: -1,
}
WithQuit(nil)(e)
WithContent(nil)(e)
WithClipboard(nil)(e)
WithFontFace(nil)(e)
WithFontColor(color.Black)(e)
WithBackgroundColor(color.White)(e)
WithCursorColor(color.RGBA{0, 0, 0, 90})(e)
WithHighlightColor(color.RGBA{0, 0, 200, 70})(e)
WithSearchColor(color.RGBA{0, 200, 0, 70})(e)
for _, opt := range options {
opt(e)
}
// Determine padding.
if e.width_padding < 0 {
e.width_padding = e.font_info.xUnit / 2
}
if e.top_bar {
e.top_padding = int(float64(e.font_info.yUnit) * 1.25)
}
if e.bot_bar {
e.bot_padding = int(float64(e.font_info.yUnit) * 1.25)
}
// Set geometry defaults.
if e.rows < 0 {
if e.height < 0 {
e.rows = EDITOR_DEFAULT_ROWS
} else {
e.rows = (e.height - (e.top_padding + e.bot_padding)) / e.font_info.yUnit
}
}
if e.cols < 0 {
if e.width < 0 {
e.cols = EDITOR_DEFAULT_COLS
} else {
e.cols = (e.width - e.width_padding*2) / e.font_info.xUnit
}
}
if e.width < 0 {
e.width = e.font_info.xUnit*e.cols + e.width_padding*2
}
if e.height < 0 {
e.height = e.font_info.yUnit*e.rows + e.top_padding + e.bot_padding
}
text_height := e.height - (e.top_padding + e.bot_padding)
text_width := e.width - (e.width_padding * 2)
// Clamp rows and cols to fit.
if e.rows > text_height/e.font_info.yUnit {
e.rows = text_height / e.font_info.yUnit
}
if e.cols > text_width/e.font_info.xUnit {
e.cols = text_width / e.font_info.xUnit
}
// Create the internal image
e.screen = ebiten.NewImage(e.width, e.height)
// Load content.
e.Load()
return e
}
func (e *Editor) searchMode() {
e.resetHighlight()
e.mode = SEARCH_MODE
e.searchHighlights = make(map[*editorLine]map[int]bool)
}
func (e *Editor) editMode() {
e.mode = EDIT_MODE
e.searchTerm = make([]rune, 0)
e.searchHighlights = make(map[*editorLine]map[int]bool)
}
func (e *Editor) fnDeleteHighlighted() func() bool {
highlightCount := 0
lastHighlightedLine := e.start
lastHighlightedX := 0
curLine := e.start
for curLine != nil {
if lineWithHighlights, ok := e.highlighted[curLine]; ok {
lastHighlightedLine = curLine
lastHighlightedX = 0
for index := range lineWithHighlights {
if lastHighlightedX < index {
lastHighlightedX = index
}
highlightCount++
}
}
curLine = curLine.next
}
e.cursor.line = lastHighlightedLine
e.cursor.x = lastHighlightedX + 1
// When a single new line character is highlighted
// we need to start deleting from the start of the
// next line so we can re-use existing deletion logic
if e.cursor.x == len(e.cursor.line.values) && e.cursor.line.next != nil {
e.cursor.line = e.cursor.line.next
e.cursor.x = 0
}
highlightedRunes := e.getHighlightedRunes()
for i := 0; i < highlightCount; i++ {
e.deletePrevious()
}
lineNum := e.getLineNumber()
curX := e.cursor.x
return func() bool {
e.MoveCursor(lineNum, curX)
for _, r := range highlightedRunes {
e.handleRune(r)
}
return true
}
}
func (e *Editor) resetHighlight() {
e.highlighted = make(map[*editorLine]map[int]bool)
}
func (e *Editor) setModified() {
e.modified = true
}
// IsModified returns true if the editor is in modified state.
func (e *Editor) IsModified() bool {
return e.modified
}
// Save saves the text to the Content assigned to the editor.
// This clears the 'modified' bit also.
func (e *Editor) Save() {
if e.content != nil {
e.content.WriteText(e.ReadText())
}
e.modified = false
}
// Load loads the text from the Content assigned to the editor.
func (e *Editor) Load() {
if e.content != nil {
e.WriteText(e.content.ReadText())
}
}
// ReadText returns all of the text in the editor.
// Note that this does not clear the 'modified' state of the editor.
func (e *Editor) ReadText() []byte {
allRunes := e.getAllRunes()
return []byte(string(allRunes))
}
// WriteText replaces all of the text in the editor.
// Note that this clears the 'modified' state of the editor, and disables
// all selection highlighting.
func (e *Editor) WriteText(text []byte) {
source := string(text)
e.editMode()
e.undoStack = make([]func() bool, 0)
e.searchTerm = make([]rune, 0)
e.highlighted = make(map[*editorLine]map[int]bool)
e.start = &editorLine{values: make([]rune, 0)}
e.cursor = &editorCursor{line: e.start, x: 0}
currentLine := e.start
if len(source) == 0 {
currentLine.values = append(currentLine.values, '\n')
} else {
for _, char := range source {
currentLine.values = append(currentLine.values, char)
if char == '\n' {
nextLine := &editorLine{values: make([]rune, 0)}
currentLine.next = nextLine
nextLine.prev = currentLine
currentLine = nextLine
}
}
}
// Ensure the final line ends with `\n`
if len(currentLine.values) > 0 && currentLine.values[len(currentLine.values)-1] != '\n' {
currentLine.values = append(currentLine.values, '\n')
}
// Remove dangling line
if currentLine.prev != nil {
currentLine.prev.next = nil
}
// Refresh the internal image.
e.updateImage()
}
func (e *Editor) search() {
// Always reset search highlights (for empty searches)
e.searchHighlights = make(map[*editorLine]map[int]bool)
if len(e.searchTerm) == 0 {
return
}
curLine := e.start
searchTermIndex := 0
// Store the location of all runes that are part of a result
// this will be used render search highlights
possibleMatches := make(map[*editorLine]map[int]bool, 0)
// Store the starting lines and line indexes of every match
// this will be used to tab between results
possibleLines := make([]*editorLine, 0)
possibleXs := make([]int, 0)
for curLine != nil {
for index, r := range curLine.values {
if unicode.ToLower(e.searchTerm[searchTermIndex]) == unicode.ToLower(r) {
// We've found the possible start of a match
if searchTermIndex == 0 {
possibleLines = append(possibleLines, curLine)
possibleXs = append(possibleXs, index)
}
searchTermIndex++
// We've found part of a possible match
if _, ok := possibleMatches[curLine]; !ok {
possibleMatches[curLine] = make(map[int]bool)
}
possibleMatches[curLine][index] = true
} else {
// Clear up the incorrect possible start
if searchTermIndex > 0 {
possibleLines = possibleLines[:len(possibleLines)-1]
possibleXs = possibleXs[:len(possibleXs)-1]
}
searchTermIndex = 0
// Clear up the incorrect possible match parts
possibleMatches = make(map[*editorLine]map[int]bool, 0)
}
// We found a full match. Save the match parts for highlighting
// and reset all state to check for more matches
if searchTermIndex == len(e.searchTerm) {
for line := range possibleMatches {
for x := range possibleMatches[line] {
if _, ok := e.searchHighlights[line]; !ok {
e.searchHighlights[line] = make(map[int]bool)
}
e.searchHighlights[line][x] = true
}
}
searchTermIndex = 0
possibleMatches = make(map[*editorLine]map[int]bool, 0)
}
}
curLine = curLine.next
}
// Were there any full matches?
if len(possibleLines) > 0 {
// Have we tabbed before the first full match?
if e.searchIndex == -1 {
e.cursor.line = possibleLines[len(possibleLines)-1]
e.cursor.x = possibleXs[len(possibleXs)-1]
e.searchIndex = len(possibleLines) - 1
return
}
// Have we tabbed beyond the final full match?
if e.searchIndex > len(possibleLines)-1 {
e.searchIndex = 0
}
// Move to the desired match
e.cursor.line = possibleLines[e.searchIndex]
e.cursor.x = possibleXs[e.searchIndex]
return
}
// There were no matches, reset so that the next search can hit the first match it finds
e.searchIndex = 0
}
func (e *Editor) fnHandleRuneSingle(r rune) func() bool {
undoDeleteHighlighted := func() bool { return false }
if len(e.highlighted) != 0 {
undoDeleteHighlighted = e.fnDeleteHighlighted()
}
e.handleRune(r)
lineNum := e.getLineNumber()
curX := e.cursor.x
return func() bool {
e.MoveCursor(lineNum, curX)
e.deletePrevious()
undoDeleteHighlighted()
return true
}
}
func (e *Editor) fnHandleRuneMulti(rs []rune) func() bool {
undoDeleteHighlighted := func() bool { return false }
if len(e.highlighted) != 0 {
undoDeleteHighlighted = e.fnDeleteHighlighted()
}
for _, r := range rs {
e.handleRune(r)
}
lineNum := e.getLineNumber()
curX := e.cursor.x
return func() bool {
e.MoveCursor(lineNum, curX)
for i := 0; i < len(rs); i++ {
e.deletePrevious()
}
undoDeleteHighlighted()
return true
}
}
func (e *Editor) handleRune(r rune) {
if e.mode == SEARCH_MODE {
e.searchTerm = append(e.searchTerm, r)
e.search()
return
}
if len(e.highlighted) != 0 {
e.resetHighlight()
}
if r == '\n' {
before := e.cursor.line
after := e.cursor.line.next
shiftedValues := make([]rune, 0)
leftBehindValues := make([]rune, 0)
shiftedValues = append(shiftedValues, e.cursor.line.values[e.cursor.x:]...)
leftBehindValues = append(leftBehindValues, e.cursor.line.values[:e.cursor.x]...)
leftBehindValues = append(leftBehindValues, '\n')
e.cursor.line.values = leftBehindValues
e.cursor.line = &editorLine{
values: shiftedValues,
prev: before,
next: after,
}
e.cursor.x = 0
if before != nil {
before.next = e.cursor.line
}
if after != nil {
after.prev = e.cursor.line
}
} else {
modifiedLine := make([]rune, 0)
modifiedLine = append(modifiedLine, e.cursor.line.values[:e.cursor.x]...)
modifiedLine = append(modifiedLine, r)
modifiedLine = append(modifiedLine, e.cursor.line.values[e.cursor.x:]...)
e.cursor.line.values = modifiedLine
e.cursor.x++
}
e.setModified()
}
// Determine if the key has just been pressed, or is repeating
func isKeyJustPressedOrRepeating(key ebiten.Key) bool {
tps := ebiten.ActualTPS()
delay_ticks := int(0.500 /*sec*/ * tps)
interval_ticks := int(0.050 /*sec*/ * tps)
// If tps is 0 or very small, provide reasonable defaults
if interval_ticks == 0 {
delay_ticks = 30
interval_ticks = 3
}
// Down for one tick? Then just pressed.
d := inpututil.KeyPressDuration(key)
if d == 1 {
return true
}
// Wait until after the delay to start repeating.
if d >= delay_ticks {
if (d-delay_ticks)%interval_ticks == 0 {
return true
}
}
return false
}
// fixPosition fixes the cursor position, and ensure the cursor is in the view.
func (e *Editor) fixPosition() {
e.cursor.FixPosition()
lineno := e.getLineNumberFromLine(e.cursor.line) - 1
switch {
case lineno < e.firstVisible:
e.firstVisible = lineno
case lineno > (e.firstVisible + e.rows - 1):
e.firstVisible = lineno - (e.rows - 1)
}
}
// Update the editor state.
func (e *Editor) Update() error {
// Update the internal image when complete.
defer e.updateImage()
// // Log key number
// for i := 0; i < int(ebiten.KeyMax); i++ {
// if inpututil.IsKeyJustPressed(ebiten.Key(i)) {
// println(i)
// return nil
// }
// }
// Modifiers
command := ebiten.IsKeyPressed(ebiten.KeyMeta) || ebiten.IsKeyPressed(ebiten.KeyControl)
shift := ebiten.IsKeyPressed(ebiten.KeyShift)
option := ebiten.IsKeyPressed(ebiten.KeyAlt)
isCommand := command && !(shift || option)
isOnly := !(command || shift || option)
// Although ebiten.AppendInputChars() would seem to be a better
// solution, it 'eats' the CONTROL meta character on Linux, and
// does not return a rune.
for _, key := range inpututil.PressedKeys() {
if !isKeyJustPressedOrRepeating(key) {
continue
}
// Get the active keyboard map name (keycap) for the US QUERTY scancode
// that was pressed.
letter := ebiten.KeyName(key)
if len(letter) == 0 && key >= ebiten.KeyA && key <= ebiten.KeyZ {
// KeyName not supported? Use a reasonable default 1:1 mapping.
letter = string([]rune{rune('a') + rune(key-ebiten.KeyA)})
}
// Command-KEY codes.
if isCommand {
switch letter {
case "f":
// Enter search mode
if e.mode == SEARCH_MODE {
e.editMode()
} else {
e.searchMode()
}
case "z":
// Undo (may repeat)
e.editMode()
e.resetHighlight()
for len(e.undoStack) > 0 {
notNoop := e.undoStack[len(e.undoStack)-1]()
e.undoStack = e.undoStack[:len(e.undoStack)-1]
if notNoop {
break
}
}
case "q":
// Quit
e.quit()
case "s":
// Save
e.Save()
case "a":
// Highlight all
e.editMode()
e.fnSelectAll()
case "v":
// Paste (may repeat)
pasteBytes := e.clipboard.ReadText()
rs := []rune{}
for _, r := range string(pasteBytes) {
rs = append(rs, r)
}
e.storeUndoAction(e.fnHandleRuneMulti(rs))
e.setModified()
case "x":
// Cut highlight
copyRunes := e.getHighlightedRunes()
if len(copyRunes) == 0 {
break
}
e.clipboard.WriteText([]byte(string(copyRunes)))
e.storeUndoAction(e.fnDeleteHighlighted())
e.resetHighlight()
e.setModified()
case "c":
// Copy highlight
if len(e.highlighted) == 0 {
break
}
copyRunes := e.getHighlightedRunes()
copyBytes := []byte(string(copyRunes))
e.clipboard.WriteText(copyBytes)
default:
// Ignored key
}
}
}
// All other keys that can be converted into runes.
// Even handles emoji input!
if !(command || option) {
// Keys which are valid input
letters := ebiten.AppendInputChars(nil)
for _, letter := range letters {
e.storeUndoAction(e.fnHandleRuneSingle(letter))
}
}
// Arrows
right := isKeyJustPressedOrRepeating(ebiten.KeyArrowRight)
left := isKeyJustPressedOrRepeating(ebiten.KeyArrowLeft)
up := isKeyJustPressedOrRepeating(ebiten.KeyArrowUp)
down := isKeyJustPressedOrRepeating(ebiten.KeyArrowDown)
pageup := isKeyJustPressedOrRepeating(ebiten.KeyPageUp)
pagedown := isKeyJustPressedOrRepeating(ebiten.KeyPageDown)
home := isKeyJustPressedOrRepeating(ebiten.KeyHome)
end := isKeyJustPressedOrRepeating(ebiten.KeyEnd)
// Exit search mode
if isOnly && inpututil.IsKeyJustPressed(ebiten.KeyEscape) {
e.editMode()
return nil
}
// Next/previous search match
if isOnly && (up || down) && e.mode == SEARCH_MODE {
if up {
if e.searchIndex > -1 {
e.searchIndex--
}
} else if down {
e.searchIndex++
}
e.search()
return nil
}
// Handle movement
if right || left || up || down || home || end || pageup || pagedown {
e.editMode()
// Clear up old highlighting
if !shift {
e.resetHighlight()
}
// Option scanning finds the next emptyType after hitting a non-emptyType
// TODO: the characters that we filter for needs improving
emptyTypes := map[rune]bool{' ': true, '.': true, ',': true}
switch {
case end:
switch {
case !option && !command:
for e.cursor.x < len(e.cursor.line.values)-1 {
if shift {
e.highlight(e.cursor.line, e.cursor.x)
}
e.cursor.x++
}
}
case home:
switch {
case !option && !command:
for e.cursor.x > 0 {
e.cursor.x--
if shift {
e.highlight(e.cursor.line, e.cursor.x)
}
}
}
case pagedown:
switch {
case !option && !command:
for rows := e.rows; e.cursor.line.next != nil && rows > 0; rows-- {
e.cursor.line = e.cursor.line.next
e.firstVisible++
}
e.fixPosition()
}
case pageup:
switch {
case !option && !command:
for rows := e.rows; e.cursor.line.prev != nil && rows > 0; rows-- {
e.cursor.line = e.cursor.line.prev
e.firstVisible--
}
e.fixPosition()
}
case right:
switch {
case option && !command:
// Find the next empty
for e.cursor.x < len(e.cursor.line.values)-2 {
if shift {
e.highlight(e.cursor.line, e.cursor.x)
}
e.cursor.x++
if ok := emptyTypes[e.cursor.line.values[e.cursor.x]]; !ok {
} else {
break
}
if shift {
e.highlight(e.cursor.line, e.cursor.x)
}