-
Notifications
You must be signed in to change notification settings - Fork 0
/
editor.go
534 lines (449 loc) · 15.5 KB
/
editor.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
// Copyright (c) 2023, The Goki Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package texteditor
//go:generate goki generate
import (
"image"
"sync"
"goki.dev/colors"
"goki.dev/cursors"
"goki.dev/enums"
"goki.dev/gi/v2/gi"
"goki.dev/gi/v2/texteditor/histyle"
"goki.dev/gi/v2/texteditor/textbuf"
"goki.dev/girl/abilities"
"goki.dev/girl/paint"
"goki.dev/girl/states"
"goki.dev/girl/styles"
"goki.dev/girl/units"
"goki.dev/ki/v2"
"goki.dev/mat32/v2"
"goki.dev/pi/v2/lex"
)
// Editor is a widget for editing multiple lines of text (as compared to
// [gi.TextField] for a single line). The Editor is driven by a [Buf]
// buffer which contains all the text, and manages all the edits,
// sending update signals out to the views.
//
// Use SetNeedsRender to drive an render update for any change that does
// not change the line-level layout of the text.
// Use SetNeedsLayout whenever there are changes across lines that require
// re-layout of the text. This sets the Widget NeedsRender flag and triggers
// layout during that render.
//
// Multiple views can be attached to a given buffer. All updating in the
// Editor should be within a single goroutine, as it would require
// extensive protections throughout code otherwise.
type Editor struct { //goki:embedder
gi.Layout
// the text buffer that we're editing
Buf *Buf `set:"-" json:"-" xml:"-"`
// text that is displayed when the field is empty, in a lower-contrast manner
Placeholder string `json:"-" xml:"placeholder"`
// width of cursor -- set from cursor-width property (inherited)
CursorWidth units.Value `xml:"cursor-width"`
// the color used for the side bar containing the line numbers; this should be set in Stylers like all other style properties
LineNumberColor image.Image
// the color used for the user text selection background color; this should be set in Stylers like all other style properties
SelectColor image.Image
// the color used for the text highlight background color (like in find); this should be set in Stylers like all other style properties
HighlightColor image.Image
// the color used for the text field cursor (caret); this should be set in Stylers like all other style properties
CursorColor image.Image
// number of lines in the view -- sync'd with the Buf after edits, but always reflects storage size of Renders etc
NLines int `set:"-" view:"-" json:"-" xml:"-"`
// renders of the text lines, with one render per line (each line could visibly wrap-around, so these are logical lines, not display lines)
Renders []paint.Text `set:"-" json:"-" xml:"-"`
// starting render offsets for top of each line
Offs []float32 `set:"-" view:"-" json:"-" xml:"-"`
// number of line number digits needed
LineNoDigs int `set:"-" view:"-" json:"-" xml:"-"`
// horizontal offset for start of text after line numbers
LineNoOff float32 `set:"-" view:"-" json:"-" xml:"-"`
// render for line numbers
LineNoRender paint.Text `set:"-" view:"-" json:"-" xml:"-"`
// current cursor position
CursorPos lex.Pos `set:"-" edit:"-" json:"-" xml:"-"`
// target cursor position for externally-set targets: ensures that it is visible
CursorTarg lex.Pos `set:"-" edit:"-" json:"-" xml:"-"`
// desired cursor column -- where the cursor was last when moved using left / right arrows -- used when doing up / down to not always go to short line columns
CursorCol int `set:"-" edit:"-" json:"-" xml:"-"`
// current index within PosHistory
PosHistIdx int `set:"-" edit:"-" json:"-" xml:"-"`
// starting point for selection -- will either be the start or end of selected region depending on subsequent selection.
SelectStart lex.Pos `set:"-" edit:"-" json:"-" xml:"-"`
// current selection region
SelectReg textbuf.Region `set:"-" edit:"-" json:"-" xml:"-"`
// previous selection region, that was actually rendered -- needed to update render
PrevSelectReg textbuf.Region `set:"-" edit:"-" json:"-" xml:"-"`
// highlighted regions, e.g., for search results
Highlights []textbuf.Region `set:"-" edit:"-" json:"-" xml:"-"`
// highlighted regions, specific to scope markers
Scopelights []textbuf.Region `set:"-" edit:"-" json:"-" xml:"-"`
// if true, select text as cursor moves
SelectMode bool `set:"-" edit:"-" json:"-" xml:"-"`
// if true, complete regardless of any disqualifying reasons
ForceComplete bool `set:"-" edit:"-" json:"-" xml:"-"`
// interactive search data
ISearch ISearch `set:"-" edit:"-" json:"-" xml:"-"`
// query replace data
QReplace QReplace `set:"-" edit:"-" json:"-" xml:"-"`
// font height, cached during styling
FontHeight float32 `set:"-" edit:"-" json:"-" xml:"-"`
// line height, cached during styling
LineHeight float32 `set:"-" edit:"-" json:"-" xml:"-"`
// font ascent, cached during styling
FontAscent float32 `set:"-" edit:"-" json:"-" xml:"-"`
// font descent, cached during styling
FontDescent float32 `set:"-" edit:"-" json:"-" xml:"-"`
// height in lines and width in chars of the visible area
NLinesChars image.Point `set:"-" edit:"-" json:"-" xml:"-"`
// total size of all lines as rendered
LinesSize mat32.Vec2 `set:"-" edit:"-" json:"-" xml:"-"`
// TotalSize = LinesSize plus extra space and line numbers etc
TotalSize mat32.Vec2 `set:"-" edit:"-" json:"-" xml:"-"`
// LineLayoutSize is Geom.Size.Actual.Total subtracting
// extra space and line numbers -- this is what
// LayoutStdLR sees for laying out each line
LineLayoutSize mat32.Vec2 `set:"-" edit:"-" json:"-" xml:"-"`
// oscillates between on and off for blinking
BlinkOn bool `set:"-" edit:"-" json:"-" xml:"-"`
// mutex protecting cursor rendering -- shared between blink and main code
CursorMu sync.Mutex `set:"-" json:"-" xml:"-" view:"-"`
// at least one of the renders has links -- determines if we set the cursor for hand movements
HasLinks bool `set:"-" edit:"-" json:"-" xml:"-"`
// handles link clicks -- if nil, they are sent to the standard web URL handler
LinkHandler func(tl *paint.TextLink)
lastRecenter int `set:"-"`
lastAutoInsert rune `set:"-"`
lastFilename gi.FileName `set:"-"`
}
func (ed *Editor) FlagType() enums.BitFlagSetter {
return (*EditorFlags)(&ed.Flags)
}
// NewViewLayout adds a new layout with text editor
// to given parent node, with given name. Layout adds "-lay" suffix.
// Texediew should always have a parent Layout to manage
// the scrollbars.
func NewViewLayout(parent ki.Ki, name string) (*Editor, *gi.Layout) {
ly := parent.NewChild(gi.LayoutType, name+"-lay").(*gi.Layout)
ed := NewEditor(ly, name)
return ed, ly
}
func (ed *Editor) OnInit() {
ed.WidgetBase.OnInit()
ed.HandleEvents()
ed.SetStyles()
}
func (ed *Editor) SetStyles() {
ed.Style(func(s *styles.Style) {
s.SetAbilities(true, abilities.Activatable, abilities.Focusable, abilities.Hoverable, abilities.Slideable)
ed.CursorWidth.Dp(2)
ed.LineNumberColor = colors.C(colors.Scheme.SurfaceContainer)
ed.SelectColor = colors.C(colors.Scheme.Select.Container)
ed.HighlightColor = colors.C(colors.Scheme.Warn.Container)
ed.CursorColor = colors.C(colors.Scheme.Primary.Base)
s.Cursor = cursors.Text
if gi.Prefs.Editor.WordWrap {
s.Text.WhiteSpace = styles.WhiteSpacePreWrap
} else {
s.Text.WhiteSpace = styles.WhiteSpacePre
}
s.Font.Family = string(gi.Prefs.MonoFont)
s.Grow.Set(1, 1)
s.Overflow.Set(styles.OverflowAuto) // absorbs all
s.Border.Style.Set(styles.BorderNone) // don't render our own border
s.Border.Radius = styles.BorderRadiusLarge
s.Margin.Zero()
s.Padding.Set(units.Dp(4))
s.Align.Content = styles.Start
s.Align.Items = styles.Start
s.Text.Align = styles.Start
s.Text.TabSize = gi.Prefs.Editor.TabSize
s.Color = colors.Scheme.OnSurface
if s.State.Is(states.Focused) {
s.Background = colors.C(colors.Scheme.Surface)
} else {
s.Background = colors.C(colors.Scheme.SurfaceContainerHigh)
}
})
}
// EditorFlags extend WidgetFlags to hold [Editor] state
type EditorFlags gi.WidgetFlags //enums:bitflag -trim-prefix View
const (
// EditorHasLineNos indicates that this editor has line numbers (per Buf option)
EditorHasLineNos EditorFlags = EditorFlags(gi.WidgetFlagsN) + iota
// EditorNeedsLayout is set by SetNeedsLayout: Editor does significant
// internal layout in LayoutAllLines, and its layout is simply based
// on what it gets allocated, so it does not affect the rest
// of the Scene.
EditorNeedsLayout
// EditorLastWasTabAI indicates that last key was a Tab auto-indent
EditorLastWasTabAI
// EditorLastWasUndo indicates that last key was an undo
EditorLastWasUndo
// EditorTargetSet indicates that the CursorTarget is set
EditorTargetSet
)
// EditDone completes editing and copies the active edited text to the text --
// called when the return key is pressed or goes out of focus
func (ed *Editor) EditDone() {
if ed.Buf != nil {
ed.Buf.EditDone()
}
ed.ClearSelected()
}
// Remarkup triggers a complete re-markup of the entire text --
// can do this when needed if the markup gets off due to multi-line
// formatting issues -- via Recenter key
func (ed *Editor) ReMarkup() {
if ed.Buf == nil {
return
}
ed.Buf.ReMarkup()
}
// IsChanged returns true if buffer was changed (edited) since last EditDone
func (ed *Editor) IsChanged() bool {
if ed.Buf != nil && ed.Buf.IsChanged() {
return true
}
return false
}
// IsNotSaved returns true if buffer was changed (edited) since last Save
func (ed *Editor) IsNotSaved() bool {
if ed.Buf != nil && ed.Buf.IsNotSaved() {
return true
}
return false
}
// HasLineNos returns true if view is showing line numbers (per textbuf option, cached here)
func (ed *Editor) HasLineNos() bool {
return ed.Is(EditorHasLineNos)
}
// Clear resets all the text in the buffer for this view
func (ed *Editor) Clear() {
if ed.Buf == nil {
return
}
ed.Buf.NewBuf(0)
}
///////////////////////////////////////////////////////////////////////////////
// Buffer communication
// ResetState resets all the random state variables, when opening a new buffer etc
func (ed *Editor) ResetState() {
ed.SelectReset()
ed.Highlights = nil
ed.ISearch.On = false
ed.QReplace.On = false
if ed.Buf == nil || ed.lastFilename != ed.Buf.Filename { // don't reset if reopening..
ed.CursorPos = lex.Pos{}
}
if ed.Buf != nil {
ed.Buf.SetReadOnly(ed.IsReadOnly())
}
}
// SetBuf sets the Buf that this is a view of, and interconnects their signals
func (ed *Editor) SetBuf(buf *Buf) *Editor {
if buf != nil && ed.Buf == buf {
return ed
}
// had := false
if ed.Buf != nil {
// had = true
ed.Buf.DeleteView(ed)
}
ed.Buf = buf
ed.ResetState()
if buf != nil {
buf.AddView(ed)
bhl := len(buf.PosHistory)
if bhl > 0 {
cp := buf.PosHistory[bhl-1]
ed.PosHistIdx = bhl - 1
ed.SetCursorShow(cp)
} else {
ed.SetCursorShow(lex.Pos{})
}
}
ed.LayoutAllLines()
ed.SetNeedsLayout(true)
return ed
}
// LinesInserted inserts new lines of text and reformats them
func (ed *Editor) LinesInserted(tbe *textbuf.Edit) {
stln := tbe.Reg.Start.Ln + 1
nsz := (tbe.Reg.End.Ln - tbe.Reg.Start.Ln)
if stln > len(ed.Renders) { // invalid
return
}
// Renders
tmprn := make([]paint.Text, nsz)
nrn := append(ed.Renders, tmprn...)
copy(nrn[stln+nsz:], nrn[stln:])
copy(nrn[stln:], tmprn)
ed.Renders = nrn
// Offs
tmpof := make([]float32, nsz)
ov := float32(0)
if stln < len(ed.Offs) {
ov = ed.Offs[stln]
} else {
ov = ed.Offs[len(ed.Offs)-1]
}
for i := range tmpof {
tmpof[i] = ov
}
nof := append(ed.Offs, tmpof...)
copy(nof[stln+nsz:], nof[stln:])
copy(nof[stln:], tmpof)
ed.Offs = nof
ed.NLines += nsz
ed.SetNeedsLayout(true)
}
// LinesDeleted deletes lines of text and reformats remaining one
func (ed *Editor) LinesDeleted(tbe *textbuf.Edit) {
stln := tbe.Reg.Start.Ln
edln := tbe.Reg.End.Ln
dsz := edln - stln
ed.Renders = append(ed.Renders[:stln], ed.Renders[edln:]...)
ed.Offs = append(ed.Offs[:stln], ed.Offs[edln:]...)
ed.NLines -= dsz
ed.SetNeedsLayout(true)
}
// BufSignal receives a signal from the Buf when underlying text
// is changed.
func (ed *Editor) BufSignal(sig BufSignals, tbe *textbuf.Edit) {
switch sig {
case BufDone:
case BufNew:
ed.ResetState()
ed.SetCursorShow(ed.CursorPos)
ed.SetNeedsLayout(true)
case BufMods:
ed.SetNeedsLayout(true)
case BufInsert:
if ed == nil || ed.This() == nil || !ed.This().(gi.Widget).IsVisible() {
return
}
ndup := ed.Renders == nil
// fmt.Printf("ed %v got %v\n", ed.Nm, tbe.Reg.Start)
if tbe.Reg.Start.Ln != tbe.Reg.End.Ln {
// fmt.Printf("ed %v lines insert %v - %v\n", ed.Nm, tbe.Reg.Start, tbe.Reg.End)
ed.LinesInserted(tbe) // triggers full layout
} else {
ed.LayoutLine(tbe.Reg.Start.Ln) // triggers layout if line width exceeds
}
if ndup {
ed.Update()
}
case BufDelete:
if ed == nil || ed.This() == nil || !ed.This().(gi.Widget).IsVisible() {
return
}
ndup := ed.Renders == nil
if tbe.Reg.Start.Ln != tbe.Reg.End.Ln {
ed.LinesDeleted(tbe) // triggers full layout
} else {
ed.LayoutLine(tbe.Reg.Start.Ln)
}
if ndup {
ed.Update()
}
case BufMarkUpdt:
ed.SetNeedsLayout(true) // comes from another goroutine
case BufClosed:
ed.SetBuf(nil)
}
}
///////////////////////////////////////////////////////////////////////////////
// Undo / Redo
// Undo undoes previous action
func (ed *Editor) Undo() {
updt := ed.UpdateStart()
defer ed.UpdateEndRender(updt)
tbe := ed.Buf.Undo()
if tbe != nil {
if tbe.Delete { // now an insert
ed.SetCursorShow(tbe.Reg.End)
} else {
ed.SetCursorShow(tbe.Reg.Start)
}
} else {
ed.CursorMovedSig() // updates status..
ed.ScrollCursorToCenterIfHidden()
}
ed.SavePosHistory(ed.CursorPos)
}
// Redo redoes previously undone action
func (ed *Editor) Redo() {
updt := ed.UpdateStart()
defer ed.UpdateEndRender(updt)
tbe := ed.Buf.Redo()
if tbe != nil {
if tbe.Delete {
ed.SetCursorShow(tbe.Reg.Start)
} else {
ed.SetCursorShow(tbe.Reg.End)
}
} else {
ed.ScrollCursorToCenterIfHidden()
}
ed.SavePosHistory(ed.CursorPos)
}
////////////////////////////////////////////////////
// Widget Interface
func (ed *Editor) ConfigWidget() {
ed.SetNeedsLayout(true)
}
// StyleView sets the style of widget
func (ed *Editor) StyleView() {
ed.StyMu.Lock()
defer ed.StyMu.Unlock()
if ed.NeedsRebuild() {
if ed.Buf != nil {
ed.Buf.SetHiStyle(histyle.StyleDefault)
}
}
ed.ApplyStyleWidget()
ed.CursorWidth.ToDots(&ed.Styles.UnContext)
}
// ApplyStyle calls StyleView and sets the style
func (ed *Editor) ApplyStyle() {
// ed.SetFlag(true, gi.CanFocus) // always focusable
ed.StyleView()
ed.StyleSizes()
}
// todo: virtual keyboard stuff
// FocusChanged appropriate actions for various types of focus changes
// func (ed *View) FocusChanged(change gi.FocusChanges) {
// switch change {
// case gi.FocusLost:
// ed.SetFlag(false, ViewFocusActive))
// // ed.EditDone()
// ed.StopCursor() // make sure no cursor
// ed.SetNeedsRender()
// goosi.TheApp.HideVirtualKeyboard()
// // fmt.Printf("lost focus: %v\n", ed.Nm)
// case gi.FocusGot:
// ed.SetFlag(true, ViewFocusActive))
// ed.EmitFocusedSignal()
// ed.SetNeedsRender()
// goosi.TheApp.ShowVirtualKeyboard(goosi.DefaultKeyboard)
// // fmt.Printf("got focus: %v\n", ed.Nm)
// case gi.FocusInactive:
// ed.SetFlag(false, ViewFocusActive))
// ed.StopCursor()
// // ed.EditDone()
// // ed.SetNeedsRender()
// goosi.TheApp.HideVirtualKeyboard()
// // fmt.Printf("focus inactive: %v\n", ed.Nm)
// case gi.FocusActive:
// // fmt.Printf("focus active: %v\n", ed.Nm)
// ed.SetFlag(true, ViewFocusActive))
// // ed.SetNeedsRender()
// // todo: see about cursor
// ed.StartCursor()
// goosi.TheApp.ShowVirtualKeyboard(goosi.DefaultKeyboard)
// }
// }