Debian Codegraph @

inputarea.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // mauview - A Go TUI library based on tcell.
2 // Copyright © 2019 Tulir Asokan
3 //
4 // This Source Code Form is subject to the terms of the Mozilla Public
5 // License, v. 2.0. If a copy of the MPL was not distributed with this
6 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
7
8 package mauview
9
10 import (
11 "strings"
12 "time"
13
14 "github.com/mattn/go-runewidth"
15 "github.com/zyedidia/clipboard"
16
•17 "github.com/gdamore/tcell/v2"
18 )
19
20 // InputArea is a multi-line user-editable text area.
21 type InputArea struct {
22 // Cursor position as the runewidth from the start of the input area text.
23 cursorOffsetW int
24 // Cursor offset from the left of the input area.
25 cursorOffsetX int
26 // Cursor offset from the top of the text.
27 cursorOffsetY int
28 // Number of lines (from top) to offset rendering.
29 viewOffsetY int
30
31 // The start of the selection as the runewidth from the start of the input area text.
32 selectionStartW int
33 // The end of the selection.
34 selectionEndW int
35
36 // The text that was entered.
37 text string
38
39 // The text split into lines. Updated each during each render.
40 lines []string
41
42 // The text to be displayed in the input area when it is empty.
43 placeholder string
44
45 // The background color of the input area.
46 fieldBackgroundColor tcell.Color
47 // The text color of the input area.
48 fieldTextColor tcell.Color
49 // The text color of the placeholder.
50 placeholderTextColor tcell.Color
51 // The text color of selected text.
52 selectionTextColor tcell.Color
53 // The background color of selected text.
54 selectionBackgroundColor tcell.Color
55
56 // Whether or not to enable vim-style keybindings.
57 vimBindings bool
58 // Whether or not text should be automatically copied to the primary clipboard when selected.
59 // Most apps on Linux work this way.
60 copySelection bool
61
62 // Whether or not the input area is focused.
63 focused bool
64
65 drawPrepared bool
66
67 // An optional function which is called when the input has changed.
68 changed func(text string)
69
70 // An optional function which is called when the user presses tab.
71 tabComplete func(text string, pos int)
72 // An optional function which is called when the user presses the down arrow at the end of the input area.
73 pressKeyDownAtEnd func()
74 // An optional function which is called when the user presses the up arrow at the beginning of the input area.
75 pressKeyUpAtStart func()
76
77 // Change history for undo/redo functionality.
78 history []*inputAreaSnapshot
79 // Current position in the history array for redo functionality.
80 historyPtr int
81 // Maximum number of history snapshots to keep.
82 historyMaxSize int
83 // Maximum delay (ms) between changes to edit the previous snapshot instead of creating a new one.
84 historyMaxEditDelay int64
85 // Maximum age (ms) of the previous snapshot to edit the previous snapshot instead of craeting a new one.
86 historyMaxSnapshotAge int64
87
88 // Timestamp of the last click used for detecting double clicks.
89 lastClick int64
90 // Position of the last click used for detecting double clicks.
91 lastClickX int
92 lastClickY int
93 // Number of clicks done within doubleClickTimeout of eachother.
94 clickStreak int
95 // Maximum delay (ms) between clicks to count as a double click.
96 doubleClickTimeout int64
97
98 // The previous word start and end X position that the mouse was dragged over when selecting words at a time.
99 // Used to detect if the mouse is still over the same word.
100 lastWordSelectionExtendXStart int
101 lastWordSelectionExtendXEnd int
102 // The position where the current selection streak started.
103 // Used to properly handle the user selecting text backwards.
104 selectionStreakStartWStart int
105 selectionStreakStartWEnd int
106 selectionStreakStartXStart int
107 selectionStreakStartY int
108 }
109
110 // NewInputArea returns a new input field.
111 func NewInputArea() *InputArea {
112 return &InputArea{
113 fieldBackgroundColor: Styles.PrimitiveBackgroundColor,
114 fieldTextColor: Styles.PrimaryTextColor,
115 placeholderTextColor: Styles.SecondaryTextColor,
116 selectionTextColor: Styles.PrimaryTextColor,
117 selectionBackgroundColor: Styles.ContrastBackgroundColor,
118
119 vimBindings: false,
120 copySelection: true,
121 focused: false,
122
123 selectionEndW: -1,
124 selectionStartW: -1,
125
126 history: []*inputAreaSnapshot{{"", 0, 0, 0, true}},
127 historyPtr: 0,
128
129 historyMaxSize: 256,
130 historyMaxEditDelay: 1 * 1000,
131 historyMaxSnapshotAge: 3 * 1000,
132
133 lastClick: 0,
134 doubleClickTimeout: 1 * 500,
135 }
136 }
137
138 // SetText sets the current text of the input field.
139 func (field *InputArea) SetText(text string) *InputArea {
140 field.text = text
141 if field.changed != nil {
142 field.changed(text)
143 }
144 field.snapshot(true)
145 return field
146 }
147
148 // SetTextAndMoveCursor sets the current text of the input field and moves the cursor with the width difference.
149 func (field *InputArea) SetTextAndMoveCursor(text string) *InputArea {
150 oldWidth := iaStringWidth(field.text)
151 field.text = text
152 newWidth := iaStringWidth(field.text)
153 if oldWidth != newWidth {
154 field.cursorOffsetW += newWidth - oldWidth
155 }
156 if field.changed != nil {
157 field.changed(field.text)
158 }
159 field.snapshot(true)
160 return field
161 }
162
163 // GetText returns the current text of the input field.
164 func (field *InputArea) GetText() string {
165 return field.text
166 }
167
168 // SetPlaceholder sets the text to be displayed when the input text is empty.
169 func (field *InputArea) SetPlaceholder(text string) *InputArea {
170 field.placeholder = text
171 return field
172 }
173
174 // SetBackgroundColor sets the background color of the input area.
175 func (field *InputArea) SetBackgroundColor(color tcell.Color) *InputArea {
176 field.fieldBackgroundColor = color
177 return field
178 }
179
180 // SetTextColor sets the text color of the input area.
181 func (field *InputArea) SetTextColor(color tcell.Color) *InputArea {
182 field.fieldTextColor = color
183 return field
184 }
185
186 // SetPlaceholderTextColor sets the text color of placeholder text.
187 func (field *InputArea) SetPlaceholderTextColor(color tcell.Color) *InputArea {
188 field.placeholderTextColor = color
189 return field
190 }
191
192 // SetChangedFunc sets a handler which is called whenever the text of the input
193 // field has changed. It receives the current text (after the change).
194 func (field *InputArea) SetChangedFunc(handler func(text string)) *InputArea {
195 field.changed = handler
196 return field
197 }
198
199 func (field *InputArea) SetTabCompleteFunc(handler func(text string, cursorOffset int)) *InputArea {
200 field.tabComplete = handler
201 return field
202 }
203
204 func (field *InputArea) SetPressKeyUpAtStartFunc(handler func()) *InputArea {
205 field.pressKeyUpAtStart = handler
206 return field
207 }
208
209 func (field *InputArea) SetPressKeyDownAtEndFunc(handler func()) *InputArea {
210 field.pressKeyDownAtEnd = handler
211 return field
212 }
213
214 // GetTextHeight returns the number of lines in the text during the previous render.
215 func (field *InputArea) GetTextHeight() int {
216 return len(field.lines)
217 }
218
219 // inputAreaSnapshot is a single history snapshot of the input area state.
220 type inputAreaSnapshot struct {
221 text string
222 cursorOffsetW int
223 origTimestamp int64
224 editTimestamp int64
225 locked bool
226 }
227
228 func millis() int64 {
229 return time.Now().UnixNano() / 1e6
230 }
231
232 // Snapshot saves the current editor state into undo history.
233 func (field *InputArea) snapshot(forceNew bool) {
234 cur := field.history[field.historyPtr]
235 now := millis()
236 if cur.locked || forceNew || now > cur.editTimestamp+field.historyMaxEditDelay || now > cur.origTimestamp+field.historyMaxSnapshotAge {
237 newSnapshot := &inputAreaSnapshot{
238 text: field.text,
239 cursorOffsetW: field.cursorOffsetW,
240 origTimestamp: now,
241 editTimestamp: now,
242 }
243 if len(field.history) >= field.historyMaxSize {
244 field.history = append(field.history[1:field.historyPtr+1], newSnapshot)
245 } else {
246 field.history = append(field.history[0:field.historyPtr+1], newSnapshot)
247 field.historyPtr++
248 }
249 } else {
250 cur.text = field.text
251 cur.cursorOffsetW = field.cursorOffsetW
252 cur.editTimestamp = now
253 }
254 }
255
256 // Redo reverses an undo.
257 func (field *InputArea) Redo() {
258 if field.historyPtr >= len(field.history)-1 {
259 return
260 }
261 field.historyPtr++
262 newCur := field.history[field.historyPtr]
263 newCur.locked = true
264 field.text = newCur.text
265 field.cursorOffsetW = newCur.cursorOffsetW
266 }
267
268 // Undo reverses the input area to the previous history snapshot.
269 func (field *InputArea) Undo() {
270 if field.historyPtr == 0 {
271 return
272 }
273 field.historyPtr--
274 newCur := field.history[field.historyPtr]
275 newCur.locked = true
276 field.text = newCur.text
277 field.cursorOffsetW = newCur.cursorOffsetW
278 }
279
280 // recalculateCursorOffset recalculates the runewidth cursor offset based on the X and Y cursor offsets.
281 func (field *InputArea) recalculateCursorOffset() {
282 cursorOffsetW := 0
283 for i, str := range field.lines {
284 ln := iaStringWidth(str)
285 if i < field.cursorOffsetY {
286 cursorOffsetW += ln
287 } else {
288 if ln == 0 {
289 break
290 } else if str[len(str)-1] == '\n' {
291 ln--
292 }
293 if field.cursorOffsetX < ln {
294 cursorOffsetW += field.cursorOffsetX
295 } else {
296 cursorOffsetW += ln
297 }
298 break
299 }
300 }
301 field.cursorOffsetW = cursorOffsetW
302 textWidth := iaStringWidth(field.text)
303 if field.cursorOffsetW > textWidth {
304 field.cursorOffsetW = textWidth
305 field.recalculateCursorPos()
306 }
307 }
308
309 // recalculateCursorPos recalculates the X and Y cursor offsets based on the runewidth cursor offset.
310 func (field *InputArea) recalculateCursorPos() {
311 cursorOffsetY := 0
312 cursorOffsetX := field.cursorOffsetW
313 for i, str := range field.lines {
314 if cursorOffsetX >= iaStringWidth(str) {
315 cursorOffsetX -= iaStringWidth(str)
316 } else {
317 cursorOffsetY = i
318 break
319 }
320 }
321 field.cursorOffsetX = cursorOffsetX
322 field.cursorOffsetY = cursorOffsetY
323 }
324
325 func matchBoundaryPattern(extract string) string {
326 matches := boundaryPattern.FindAllStringIndex(extract, -1)
327 if len(matches) > 0 {
328 if match := matches[len(matches)-1]; len(match) >= 2 {
329 if until := match[1]; until < len(extract) {
330 extract = extract[:until]
331 }
332 }
333 }
334 return extract
335 }
336
337 // prepareText splits the text into lines that fit the input area.
338 func (field *InputArea) prepareText(width int) {
339 var lines []string
340 if len(field.text) == 0 {
341 field.lines = lines
342 return
343 }
344 forcedLinebreaks := strings.Split(field.text, "\n")
345 for _, str := range forcedLinebreaks {
346 str = str + "\n"
347 // Adapted from tview/textview.go#reindexBuffer()
348 for len(str) > 0 {
349 extract := iaSubstringBefore(str, width-1)
350 if len(extract) < len(str) {
351 if spaces := spacePattern.FindStringIndex(str[len(extract):]); spaces != nil && spaces[0] == 0 {
352 extract = str[:len(extract)+spaces[1]]
353 }
354 extract = matchBoundaryPattern(extract)
355 }
356 lines = append(lines, extract)
357 str = str[len(extract):]
358 }
359 }
360 field.lines = lines
361 }
362
363 // updateViewOffset updates the view offset so that:
364 // - it is not negative
365 // - it is not unnecessarily high
366 // - the cursor is within the rendered area
367 func (field *InputArea) updateViewOffset(height int) {
368 if field.viewOffsetY < 0 {
369 field.viewOffsetY = 0
370 } else if len(field.lines) > height && field.viewOffsetY+height > len(field.lines) {
371 field.viewOffsetY = len(field.lines) - height
372 }
373 if field.cursorOffsetY-field.viewOffsetY < 0 {
374 field.viewOffsetY = field.cursorOffsetY
375 } else if field.cursorOffsetY >= field.viewOffsetY+height {
376 field.viewOffsetY = field.cursorOffsetY - height + 1
377 }
378 }
379
380 // drawText draws the text and the cursor.
381 func (field *InputArea) drawText(screen Screen) {
382 width, height := screen.Size()
383 if len(field.lines) == 0 {
384 if len(field.placeholder) > 0 {
385 Print(screen, field.placeholder, 0, 0, width, AlignLeft, field.placeholderTextColor)
386 }
387 return
388 }
389 defaultStyle := tcell.StyleDefault.Foreground(field.fieldTextColor).Background(field.fieldBackgroundColor)
390 highlightStyle := defaultStyle.Foreground(field.selectionTextColor).Background(field.selectionBackgroundColor)
391 rwOffset := 0
392 for y := 0; y <= field.viewOffsetY+height && y < len(field.lines); y++ {
393 if y < field.viewOffsetY {
394 rwOffset += iaStringWidth(field.lines[y])
395 continue
396 }
397 x := 0
398 for _, ch := range []rune(field.lines[y]) {
399 w := iaRuneWidth(ch)
400 var style tcell.Style
401 if rwOffset >= field.selectionStartW && rwOffset < field.selectionEndW {
402 style = highlightStyle
403 } else {
404 style = defaultStyle
405 }
406 rwOffset += w
407 for w > 0 {
408 screen.SetContent(x, y-field.viewOffsetY, ch, nil, style)
409 x++
410 w--
411 }
412 }
413 }
414 }
415
416 func (field *InputArea) PrepareDraw(width int) {
417 field.prepareText(width)
418 field.recalculateCursorPos()
419 }
420
421 // Draw draws this primitive onto the screen.
422 func (field *InputArea) Draw(screen Screen) {
423 width, height := screen.Size()
424 if height < 1 || width < 1 {
425 return
426 }
427
428 if !field.drawPrepared {
429 field.PrepareDraw(width)
430 }
431 field.updateViewOffset(height)
432 screen.SetStyle(tcell.StyleDefault.Background(field.fieldBackgroundColor))
433 screen.Clear()
434 field.drawText(screen)
435 if field.focused && field.selectionEndW == -1 {
436 screen.ShowCursor(field.cursorOffsetX, field.cursorOffsetY-field.viewOffsetY)
437 }
438 field.drawPrepared = false
439 }
440
441 func iaRuneWidth(ch rune) int {
442 if ch == '\n' {
443 return 1
444 }
445 return runewidth.RuneWidth(ch)
446 }
447
448 func iaStringWidth(s string) (width int) {
449 w := runewidth.StringWidth(s)
450 for _, ch := range s {
451 if ch == '\n' {
452 w++
453 }
454 }
455 return w
456 }
457
458 func iaSubstringBefore(s string, w int) string {
459 if iaStringWidth(s) <= w {
460 return s
461 }
462 r := []rune(s)
463 //tw := iaStringWidth(tail)
464 //w -= tw
465 width := 0
466 i := 0
467 for ; i < len(r); i++ {
468 cw := iaRuneWidth(r[i])
469 if width+cw > w {
470 break
471 }
472 width += cw
473 }
474 return string(r[0:i]) // + tail
475 }
476
477 // TypeRune inserts the given rune at the current cursor position.
478 func (field *InputArea) TypeRune(ch rune) {
479 var left, right string
480 if field.selectionEndW != -1 {
481 left = iaSubstringBefore(field.text, field.selectionStartW)
482 rightLeft := iaSubstringBefore(field.text, field.selectionEndW)
483 right = field.text[len(rightLeft):]
484 field.cursorOffsetW = field.selectionStartW
485 } else {
486 left = iaSubstringBefore(field.text, field.cursorOffsetW)
487 right = field.text[len(left):]
488 }
489 field.text = left + string(ch) + right
490 field.cursorOffsetW += iaRuneWidth(ch)
491 field.selectionEndW = -1
492 field.selectionStartW = -1
493 }
494
495 // MoveCursorLeft moves the cursor left.
496 //
497 // If moveWord is true, the cursor moves a whole word to the left.
498 //
499 // If extendSelection is true, the selection is either extended to the left if the cursor is on the left side of the
500 // selection or retracted from the right if the cursor is on the right side. If there is no existing selection, the
501 // selection will be created towards the left of the cursor.
502 func (field *InputArea) MoveCursorLeft(moveWord, extendSelection bool) {
503 before := iaSubstringBefore(field.text, field.cursorOffsetW)
504 var diff int
505 if moveWord {
506 diff = -iaStringWidth(lastWord.FindString(before))
507 } else if len(before) > 0 {
508 beforeRunes := []rune(before)
509 char := beforeRunes[len(beforeRunes)-1]
510 diff = -iaRuneWidth(char)
511 }
512 if extendSelection {
513 field.extendSelection(diff)
514 } else {
515 field.moveCursor(diff)
516 }
517 }
518
519 // MoveCursorRight moves the cursor right.
520 //
521 // If moveWord is true, the cursor moves a whole word to the right.
522 //
523 // If extendSelection is true, the selection is either extended to the right if the cursor is on the right side of the
524 // selection or retracted from the left if the cursor is on the left side. If there is no existing selection, the
525 // selection will be created towards the right of the cursor.
526 func (field *InputArea) MoveCursorRight(moveWord, extendSelection bool) {
527 before := iaSubstringBefore(field.text, field.cursorOffsetW)
528 after := field.text[len(before):]
529 var diff int
530 if moveWord {
531 diff = +iaStringWidth(firstWord.FindString(after))
532 } else if len(after) > 0 {
533 char := []rune(after)[0]
534 diff = +iaRuneWidth(char)
535 }
536 if extendSelection {
537 field.extendSelection(diff)
538 } else {
539 field.moveCursor(diff)
540 }
541 }
542
543 func (field *InputArea) MoveCursorHome(extendSelection bool) {
544 if extendSelection {
545 field.extendSelection(-iaStringWidth(iaSubstringBefore(field.text, field.cursorOffsetW)))
546 } else {
547 field.selectionEndW = -1
548 field.selectionStartW = -1
549 field.cursorOffsetW = 0
550 }
551 }
552
553 func (field *InputArea) MoveCursorEnd(extendSelection bool) {
554 if extendSelection {
555 after := field.text[len(iaSubstringBefore(field.text, field.cursorOffsetW)):]
556 field.extendSelection(iaStringWidth(after))
557 } else {
558 field.selectionEndW = -1
559 field.selectionStartW = -1
560 field.cursorOffsetW = iaStringWidth(field.text)
561 }
562 }
563
564 // moveCursor resets the selection and adjusts the runewidth cursor offset.
565 func (field *InputArea) moveCursor(diff int) {
566 field.selectionEndW = -1
567 field.selectionStartW = -1
568 field.cursorOffsetW += diff
569 }
570
571 // extendSelection adjusts the selection or creates a selection. Negative values make the selection go left and
572 // positive values make the selection go right.
573 // "Go" in context of a selection means retracting or extending depending on which side the cursor is on.
574 func (field *InputArea) extendSelection(diff int) {
575 if field.selectionEndW == -1 {
576 field.selectionStartW = field.cursorOffsetW
577 field.selectionEndW = field.selectionStartW + diff
578 } else if field.cursorOffsetW == field.selectionEndW {
579 field.selectionEndW += diff
580 } else if field.cursorOffsetW == field.selectionStartW {
581 field.selectionStartW += diff
582 }
583 field.cursorOffsetW += diff
584 if field.selectionStartW > field.selectionEndW {
585 field.selectionStartW, field.selectionEndW = field.selectionEndW, field.selectionStartW
586 }
587 field.copy("primary", false)
588 }
589
590 // MoveCursorUp moves the cursor up one line.
591 //
592 // If extendSelection is true, the selection is either extended up if the cursor is at the beginning of the selection or
593 // retracted from the bottom if the cursor is at the end of the selection.
594 func (field *InputArea) MoveCursorUp(extendSelection bool) {
595 pX, pY := field.cursorOffsetX, field.cursorOffsetY
596 if field.cursorOffsetY > 0 {
597 field.cursorOffsetY--
598 lineWidth := iaStringWidth(field.lines[field.cursorOffsetY])
599 if lineWidth < field.cursorOffsetX {
600 field.cursorOffsetX = lineWidth
601 }
602 } else {
603 field.cursorOffsetX = 0
604 }
605 if extendSelection && len(field.lines) > 0 {
606 prevLineBefore := iaSubstringBefore(field.lines[pY], pX)
607 curLineBefore := iaSubstringBefore(field.lines[field.cursorOffsetY], field.cursorOffsetX)
608 curLineAfter := field.lines[field.cursorOffsetY][len(curLineBefore):]
609 field.extendSelection(-iaStringWidth(curLineAfter + prevLineBefore))
610 } else {
611 field.selectionStartW = -1
612 field.selectionEndW = -1
613 }
614 prevOffsetW := field.cursorOffsetW
615 field.recalculateCursorOffset()
616 if field.cursorOffsetW == prevOffsetW && field.pressKeyUpAtStart != nil {
617 field.pressKeyUpAtStart()
618 }
619 }
620
621 // MoveCursorDown moves the cursor down one line.
622 //
623 // If extendSelection is true, the selection is either extended down if the cursor is at the end of the selection or
624 // retracted from the top if the cursor is at the beginning of the selection.
625 func (field *InputArea) MoveCursorDown(extendSelection bool) {
626 pX, pY := field.cursorOffsetX, field.cursorOffsetY
627 if field.cursorOffsetY < len(field.lines)-1 {
628 field.cursorOffsetY++
629 lineWidth := iaStringWidth(field.lines[field.cursorOffsetY])
630 if lineWidth < field.cursorOffsetX {
631 field.cursorOffsetX = lineWidth
632 }
633 } else if field.cursorOffsetY == len(field.lines)-1 {
634 lineWidth := iaStringWidth(field.lines[field.cursorOffsetY])
635 field.cursorOffsetX = lineWidth
636 }
637 if extendSelection && len(field.lines) > 0 {
638 prevLineBefore := iaSubstringBefore(field.lines[pY], pX)
639 prevLineAfter := field.lines[pY][len(prevLineBefore):]
640 curLineBefore := iaSubstringBefore(field.lines[field.cursorOffsetY], field.cursorOffsetX)
641 field.extendSelection(iaStringWidth(prevLineAfter + curLineBefore))
642 } else {
643 field.selectionStartW = -1
644 field.selectionEndW = -1
645 }
646 prevOffsetW := field.cursorOffsetW
647 field.recalculateCursorOffset()
648 if field.cursorOffsetW == prevOffsetW && field.pressKeyDownAtEnd != nil {
649 field.pressKeyDownAtEnd()
650 }
651 }
652
653 // SetCursorPos sets the X and Y cursor offsets.
654 func (field *InputArea) SetCursorPos(x, y int) {
655 field.cursorOffsetX = x
656 field.cursorOffsetY = y
657 field.selectionStartW = -1
658 field.selectionEndW = -1
659 if field.cursorOffsetY > len(field.lines) {
660 field.cursorOffsetY = len(field.lines) - 1
661 }
662 field.recalculateCursorOffset()
663 }
664
665 func (field *InputArea) GetCursorPos() (int, int) {
666 return field.cursorOffsetX, field.cursorOffsetY
667 }
668
669 // SetCursorOffset sets the runewidth cursor offset.
670 func (field *InputArea) SetCursorOffset(offset int) {
671 if offset < 0 {
672 offset = iaStringWidth(field.text) - (offset + 1)
673 }
674 field.cursorOffsetW = offset
675 field.selectionStartW = -1
676 field.selectionEndW = -1
677 }
678
679 func (field *InputArea) GetCursorOffset() int {
680 return field.cursorOffsetW
681 }
682
683 func (field *InputArea) SetSelection(start, end int) {
684 field.selectionStartW = start
685 field.selectionEndW = end
686 }
687
688 func (field *InputArea) GetSelectedText() string {
689 leftLeft := iaSubstringBefore(field.text, field.selectionStartW)
690 rightLeft := iaSubstringBefore(field.text, field.selectionEndW)
691 return rightLeft[len(leftLeft):]
692 }
693
694 func (field *InputArea) GetSelection() (int, int) {
695 return field.selectionStartW, field.selectionEndW
696 }
697
698 func (field *InputArea) ClearSelection() {
699 field.selectionStartW = -1
700 field.selectionEndW = -1
701 }
702
703 // findWordAt finds the word around the given runewidth offset in the given string.
704 //
705 // Returns the start and end index of the word.
706 func findWordAt(line string, x int) (beforePos, afterPos int) {
707 before := iaSubstringBefore(line, x)
708 after := line[len(before):]
709 afterBound := boundaryPattern.FindStringIndex(after)
710 if afterBound != nil {
711 afterPos = afterBound[0]
712 } else {
713 afterPos = len(after)
714 }
715 afterPos += len(before)
716 beforeBounds := boundaryPattern.FindAllStringIndex(before, -1)
717 if len(beforeBounds) > 0 {
718 beforeBound := beforeBounds[len(beforeBounds)-1]
719 beforePos = beforeBound[1]
720 } else {
721 beforePos = 0
722 }
723 return
724 }
725
726 // startSelectionStreak selects the current word or line for double and triple clicks (respectively).
727 func (field *InputArea) startSelectionStreak(x, y int) {
728 field.cursorOffsetY = y
729 if field.cursorOffsetY > len(field.lines) {
730 field.cursorOffsetY = len(field.lines) - 1
731 } else if len(field.lines) == 0 {
732 return
733 }
734 line := field.lines[field.cursorOffsetY]
735 fullLine := (field.clickStreak-2)%2 == 1
736 if fullLine {
737 field.cursorOffsetX = iaStringWidth(line)
738
739 field.recalculateCursorOffset()
740
741 field.selectionStartW = field.cursorOffsetW - field.cursorOffsetX
742 field.selectionEndW = field.cursorOffsetW
743 } else {
744 beforePos, afterPos := findWordAt(line, x)
745 field.cursorOffsetX = iaStringWidth(line[:afterPos])
746
747 field.recalculateCursorOffset()
748
749 wordWidth := iaStringWidth(line[beforePos:afterPos])
750 field.selectionStartW = field.cursorOffsetW - wordWidth
751 field.selectionEndW = field.cursorOffsetW
752
753 field.selectionStreakStartWStart = field.selectionStartW
754 field.selectionStreakStartWEnd = field.selectionEndW
755 field.selectionStreakStartXStart = field.cursorOffsetX - wordWidth
756 }
757
758 field.selectionStreakStartY = field.cursorOffsetY
759 field.copy("primary", false)
760 }
761
762 // ExtendSelection extends the selection as if the user dragged their mouse to the given coordinates.
763 func (field *InputArea) ExtendSelection(x, y int) {
764 field.cursorOffsetY = y
765 if field.cursorOffsetY > len(field.lines) {
766 field.cursorOffsetY = len(field.lines) - 1
767 }
768 if field.clickStreak <= 1 {
769 field.cursorOffsetX = x
770 } else if (field.clickStreak-2)%2 == 0 {
771 if field.lastClickY == y && x >= field.lastWordSelectionExtendXStart && x <= field.lastWordSelectionExtendXEnd {
772 return
773 }
774 line := field.lines[field.cursorOffsetY]
775 beforePos, afterPos := findWordAt(line, x)
776 field.lastWordSelectionExtendXStart = beforePos
777 field.lastWordSelectionExtendXEnd = afterPos
778 if y < field.selectionStreakStartY || (y == field.selectionStreakStartY && x < field.selectionStreakStartXStart) {
779 field.cursorOffsetW = field.selectionStartW
780 field.selectionEndW = field.selectionStreakStartWEnd
781 field.cursorOffsetX = iaStringWidth(line[:beforePos])
782 } else {
783 field.cursorOffsetW = field.selectionEndW
784 field.selectionStartW = field.selectionStreakStartWStart
785 field.cursorOffsetX = iaStringWidth(line[:afterPos])
786 }
787 } else {
788 if field.lastClickY == y {
789 return
790 }
791 if field.cursorOffsetY == field.selectionStreakStartY {
792 // Special case to not mess up stuff when dragging mouse over selection streak start.
793 line := field.lines[field.cursorOffsetY]
794 field.cursorOffsetX = iaStringWidth(line)
795 field.recalculateCursorOffset()
796 field.selectionStartW = field.cursorOffsetW - field.cursorOffsetX
797 field.selectionEndW = field.cursorOffsetW
798 return
799 } else if field.cursorOffsetY < field.selectionStreakStartY {
800 field.cursorOffsetW = field.selectionStartW
801 field.cursorOffsetX = 0
802 } else {
803 field.cursorOffsetW = field.selectionEndW
804 line := field.lines[field.cursorOffsetY]
805 field.cursorOffsetX = iaStringWidth(line)
806 }
807 }
808 prevOffset := field.cursorOffsetW
809 field.recalculateCursorOffset()
810 if field.selectionEndW == -1 {
811 field.selectionStartW = prevOffset
812 field.selectionEndW = field.cursorOffsetW
813 } else if prevOffset == field.selectionEndW {
814 field.selectionEndW = field.cursorOffsetW
815 } else {
816 field.selectionStartW = field.cursorOffsetW
817 }
818 if field.selectionStartW > field.selectionEndW {
819 field.selectionStartW, field.selectionEndW = field.selectionEndW, field.selectionStartW
820 }
821 field.copy("primary", false)
822 }
823
824 // RemoveNextCharacter removes the character after the cursor.
825 func (field *InputArea) RemoveNextCharacter() {
826 if field.selectionEndW > 0 {
827 field.RemoveSelection()
828 return
829 } else if field.cursorOffsetW >= iaStringWidth(field.text) {
830 return
831 }
832 left := iaSubstringBefore(field.text, field.cursorOffsetW)
833 // Take everything after the left part minus the first character.
834 right := string([]rune(field.text[len(left):])[1:])
835
836 field.text = left + right
837 }
838
839 // RemovePreviousWord removes the word before the cursor.
840 func (field *InputArea) RemovePreviousWord() {
841 if field.selectionEndW > 0 {
842 field.RemoveSelection()
843 return
844 }
845 left := iaSubstringBefore(field.text, field.cursorOffsetW)
846 replacement := lastWord.ReplaceAllString(left, "")
847 field.text = replacement + field.text[len(left):]
848 field.cursorOffsetW = iaStringWidth(replacement)
849 }
850
851 // RemoveSelection removes the selected content.
852 func (field *InputArea) RemoveSelection() {
853 leftLeft := iaSubstringBefore(field.text, field.selectionStartW)
854 rightLeft := iaSubstringBefore(field.text, field.selectionEndW)
855 rightRight := field.text[len(rightLeft):]
856 field.text = leftLeft + rightRight
857 if field.cursorOffsetW == field.selectionEndW {
858 field.cursorOffsetW -= iaStringWidth(rightLeft[len(leftLeft):])
859 }
860 field.selectionEndW = -1
861 field.selectionStartW = -1
862 }
863
864 // RemovePreviousCharacter removes the character before the cursor.
865 func (field *InputArea) RemovePreviousCharacter() {
866 if field.selectionEndW > 0 {
867 field.RemoveSelection()
868 return
869 } else if field.cursorOffsetW == 0 {
870 return
871 }
872 left := iaSubstringBefore(field.text, field.cursorOffsetW)
873 right := field.text[len(left):]
874
875 // Take everything before the right part minus the last character.
876 leftRunes := []rune(left)
877 leftRunes = leftRunes[0 : len(leftRunes)-1]
878 left = string(leftRunes)
879
880 // Figure out what character was removed to correctly decrease cursorOffset.
881 removedChar := field.text[len(left) : len(field.text)-len(right)]
882 field.text = left + right
883 field.cursorOffsetW -= iaStringWidth(removedChar)
884 }
885
886 // Clear clears the input area.
887 func (field *InputArea) Clear() {
888 field.text = ""
889 field.cursorOffsetW = 0
890 field.cursorOffsetX = 0
891 field.cursorOffsetY = 0
892 field.selectionEndW = -1
893 field.selectionStartW = -1
894 field.viewOffsetY = 0
895 }
896
897 // SelectAll extends the selection to cover all text in the input area.
898 func (field *InputArea) SelectAll() {
899 field.selectionStartW = 0
900 field.selectionEndW = iaStringWidth(field.text)
901 field.cursorOffsetW = field.selectionEndW
902 field.copy("primary", false)
903 }
904
905 // handleInputChanges calls the text change handler and makes sure
906 // offsets are valid after a change in the text of the input area.
907 func (field *InputArea) handleInputChanges(originalText string) {
908 // Trigger changed events.
909 if field.text != originalText && field.changed != nil {
910 field.changed(field.text)
911 }
912
913 // Make sure cursor offset is valid
914 if field.cursorOffsetW < 0 {
915 field.cursorOffsetW = 0
916 }
917 textWidth := iaStringWidth(field.text)
918 if field.cursorOffsetW > textWidth {
919 field.cursorOffsetW = textWidth
920 }
921 if field.selectionEndW > textWidth {
922 field.selectionEndW = textWidth
923 }
924 if field.selectionEndW <= field.selectionStartW {
925 field.selectionStartW = -1
926 field.selectionEndW = -1
927 }
928 }
929
930 // OnPasteEvent handles a terminal bracketed paste event.
931 func (field *InputArea) OnPasteEvent(event PasteEvent) bool {
932 var left, right string
933 if field.selectionEndW != -1 {
934 left = iaSubstringBefore(field.text, field.selectionStartW)
935 rightLeft := iaSubstringBefore(field.text, field.selectionEndW)
936 right = field.text[len(rightLeft):]
937 field.cursorOffsetW = field.selectionStartW
938 } else {
939 left = iaSubstringBefore(field.text, field.cursorOffsetW)
940 right = field.text[len(left):]
941 }
942 oldText := field.text
943 field.text = left + event.Text() + right
944 field.cursorOffsetW += iaStringWidth(event.Text())
945 field.handleInputChanges(oldText)
946 field.selectionEndW = -1
947 field.selectionStartW = -1
948 field.snapshot(true)
949 return true
950 }
951
952 // Paste reads the clipboard and inserts the content at the cursor position.
953 func (field *InputArea) Paste() {
954 text, _ := clipboard.ReadAll("clipboard")
955 field.OnPasteEvent(customPasteEvent{nil, text})
956 }
957
958 // Copy copies the currently selected content onto the clipboard.
959 func (field *InputArea) Copy() {
960 field.copy("clipboard", false)
961 }
962
963 func (field *InputArea) Cut() {
964 field.copy("clipboard", true)
965 }
966
967 func (field *InputArea) copy(selection string, cut bool) {
968 if !field.copySelection && selection == "primary" {
969 return
970 } else if field.selectionEndW == -1 {
971 return
972 }
973 left := iaSubstringBefore(field.text, field.selectionStartW)
974 rightLeft := iaSubstringBefore(field.text, field.selectionEndW)
975 text := rightLeft[len(left):]
976 _ = clipboard.WriteAll(text, selection)
977 if cut {
978 field.text = left + field.text[len(rightLeft):]
979 field.cursorOffsetW = field.selectionStartW
980 field.selectionStartW = -1
981 field.selectionEndW = -1
982 }
983 }
984
985 // OnKeyEvent handles a terminal key press event.
986 func (field *InputArea) OnKeyEvent(event KeyEvent) bool {
987 hasMod := func(mod tcell.ModMask) bool {
988 return event.Modifiers()&mod != 0
989 }
990 oldText := field.text
991
992 doSnapshot := false
993 forceNewSnapshot := false
994 // Process key event.
995 switch event.Key() {
996 case tcell.KeyRune:
997 field.TypeRune(event.Rune())
998 doSnapshot = true
999 forceNewSnapshot = event.Rune() == ' '
1000 case tcell.KeyEnter:
1001 field.TypeRune('\n')
1002 doSnapshot = true
1003 forceNewSnapshot = true
1004 case tcell.KeyLeft:
1005 field.MoveCursorLeft(hasMod(tcell.ModCtrl), hasMod(tcell.ModShift))
1006 case tcell.KeyRight:
1007 field.MoveCursorRight(hasMod(tcell.ModCtrl), hasMod(tcell.ModShift))
1008 case tcell.KeyUp:
1009 field.MoveCursorUp(hasMod(tcell.ModShift))
1010 case tcell.KeyDown:
1011 field.MoveCursorDown(hasMod(tcell.ModShift))
1012 case tcell.KeyHome:
1013 field.MoveCursorHome(hasMod(tcell.ModShift))
1014 case tcell.KeyEnd:
1015 field.MoveCursorEnd(hasMod(tcell.ModShift))
1016 case tcell.KeyDelete:
1017 field.RemoveNextCharacter()
1018 doSnapshot = true
1019 case tcell.KeyBackspace:
1020 if Backspace1RemovesWord {
1021 field.RemovePreviousWord()
1022 } else {
1023 field.RemovePreviousCharacter()
1024 }
1025 doSnapshot = true
1026 forceNewSnapshot = true
1027 case tcell.KeyBackspace2:
1028 forceNewSnapshot = field.selectionEndW > 0
1029 if Backspace2RemovesWord {
1030 field.RemovePreviousWord()
1031 } else {
1032 field.RemovePreviousCharacter()
1033 }
1034 doSnapshot = true
1035 case tcell.KeyTab:
1036 if field.tabComplete != nil {
1037 field.tabComplete(field.text, field.cursorOffsetW)
1038 }
1039 default:
1040 if field.vimBindings {
1041 switch event.Key() {
1042 case tcell.KeyCtrlU:
1043 field.Clear()
1044 doSnapshot = true
1045 forceNewSnapshot = true
1046 case tcell.KeyCtrlW:
1047 field.RemovePreviousWord()
1048 doSnapshot = true
1049 forceNewSnapshot = true
1050 default:
1051 return false
1052 }
1053 } else {
1054 switch event.Key() {
1055 case tcell.KeyCtrlA:
1056 field.SelectAll()
1057 case tcell.KeyCtrlZ:
1058 field.Undo()
1059 case tcell.KeyCtrlY:
1060 field.Redo()
1061 case tcell.KeyCtrlC:
1062 field.Copy()
1063 case tcell.KeyCtrlV:
1064 field.Paste()
1065 return true
1066 case tcell.KeyCtrlX:
1067 field.Cut()
1068 default:
1069 return false
1070 }
1071 }
1072 }
1073 field.handleInputChanges(oldText)
1074 if doSnapshot {
1075 field.snapshot(forceNewSnapshot)
1076 }
1077 return true
1078 }
1079
1080 // Focus marks the input area as focused.
1081 func (field *InputArea) Focus() {
1082 field.focused = true
1083 }
1084
1085 // Blur marks the input area as not focused.
1086 func (field *InputArea) Blur() {
1087 field.focused = false
1088 }
1089
1090 // OnMouseEvent handles a terminal mouse event.
1091 func (field *InputArea) OnMouseEvent(event MouseEvent) bool {
1092 switch event.Buttons() {
1093 case tcell.Button1:
1094 cursorX, cursorY := event.Position()
1095 cursorY += field.viewOffsetY
1096 now := millis()
1097 sameCell := field.lastClickX == cursorX && field.lastClickY == cursorY
1098 if !event.HasMotion() {
1099 withinTimeout := now < field.lastClick+field.doubleClickTimeout
1100 if field.clickStreak > 0 && sameCell && withinTimeout {
1101 field.clickStreak++
1102 } else {
1103 field.clickStreak = 1
1104 }
1105 if field.clickStreak <= 1 {
1106 field.SetCursorPos(cursorX, cursorY)
1107 } else {
1108 field.startSelectionStreak(cursorX, cursorY)
1109 }
1110 field.lastClick = now
1111 field.lastClickX = cursorX
1112 field.lastClickY = cursorY
1113 } else {
1114 if sameCell {
1115 return false
1116 }
1117 field.ExtendSelection(cursorX, cursorY)
1118 }
1119 case tcell.WheelDown:
1120 field.viewOffsetY += 3
1121 field.cursorOffsetY += 3
1122 field.recalculateCursorOffset()
1123 case tcell.WheelUp:
1124 field.viewOffsetY -= 3
1125 field.cursorOffsetY -= 3
1126 field.recalculateCursorOffset()
1127 default:
1128 return false
1129 }
1130 return true
1131 }