File: gui.go

package info (click to toggle)
golang-github-jesseduffield-gocui 0.4%2Bgit20250605.fc53879%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 452 kB
  • sloc: makefile: 3
file content (1673 lines) | stat: -rw-r--r-- 41,610 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
// Copyright 2014 The gocui 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 gocui

import (
	"context"
	standardErrors "errors"
	"runtime"
	"strings"
	"sync"
	"time"

	"github.com/gdamore/tcell/v2"
	"github.com/go-errors/errors"
	"github.com/mattn/go-runewidth"
)

// OutputMode represents an output mode, which determines how colors
// are used.
type OutputMode int

var (
	// ErrAlreadyBlacklisted is returned when the keybinding is already blacklisted.
	ErrAlreadyBlacklisted = standardErrors.New("keybind already blacklisted")

	// ErrBlacklisted is returned when the keybinding being parsed / used is blacklisted.
	ErrBlacklisted = standardErrors.New("keybind blacklisted")

	// ErrNotBlacklisted is returned when a keybinding being whitelisted is not blacklisted.
	ErrNotBlacklisted = standardErrors.New("keybind not blacklisted")

	// ErrNoSuchKeybind is returned when the keybinding being parsed does not exist.
	ErrNoSuchKeybind = standardErrors.New("no such keybind")

	// ErrUnknownView allows to assert if a View must be initialized.
	ErrUnknownView = standardErrors.New("unknown view")

	// ErrQuit is used to decide if the MainLoop finished successfully.
	ErrQuit = standardErrors.New("quit")

	// ErrKeybindingNotHandled is returned when a keybinding is not handled, so that the key can be dispatched further
	ErrKeybindingNotHandled = standardErrors.New("keybinding not handled")
)

const (
	// OutputNormal provides 8-colors terminal mode.
	OutputNormal OutputMode = iota

	// Output256 provides 256-colors terminal mode.
	Output256

	// Output216 provides 216 ansi color terminal mode.
	Output216

	// OutputGrayscale provides greyscale terminal mode.
	OutputGrayscale

	// OutputTrue provides 24bit color terminal mode.
	// This mode is recommended even if your terminal doesn't support
	// such mode. The colors are represented exactly as you
	// write them (no clamping or truncating). `tcell` should take care
	// of what your terminal can do.
	OutputTrue
)

type tabClickHandler func(int) error

type tabClickBinding struct {
	viewName string
	handler  tabClickHandler
}

// TODO: would be good to define inbound and outbound click handlers e.g.
// clicking on a file is an inbound thing where we don't care what context you're
// in when it happens, whereas clicking on the main view from the files view is an
// outbound click with a specific handler. But this requires more thinking about
// where handlers should live.
type ViewMouseBinding struct {
	// the view that is clicked
	ViewName string

	// the view that has focus when the click occurs.
	FocusedView string

	Handler func(ViewMouseBindingOpts) error

	Modifier Modifier

	// must be a mouse key
	Key Key
}

type ViewMouseBindingOpts struct {
	X int // i.e. origin x + cursor x
	Y int // i.e. origin y + cursor y
}

type GuiMutexes struct {
	// tickingMutex ensures we don't have two loops ticking. The point of 'ticking'
	// is to refresh the gui rapidly so that loader characters can be animated.
	tickingMutex sync.Mutex

	ViewsMutex sync.Mutex
}

type replayedEvents struct {
	Keys        chan *TcellKeyEventWrapper
	Resizes     chan *TcellResizeEventWrapper
	MouseEvents chan *TcellMouseEventWrapper
}

type RecordingConfig struct {
	Speed  float64
	Leeway int
}

// Gui represents the whole User Interface, including the views, layouts
// and keybindings.
type Gui struct {
	RecordingConfig
	// ReplayedEvents is for passing pre-recorded input events, for the purposes of testing
	ReplayedEvents replayedEvents
	playRecording  bool

	tabClickBindings  []*tabClickBinding
	viewMouseBindings []*ViewMouseBinding
	gEvents           chan GocuiEvent
	userEvents        chan userEvent
	views             []*View
	currentView       *View
	managers          []Manager
	keybindings       []*keybinding
	focusHandler      func(bool) error
	openHyperlink     func(string, string) error
	maxX, maxY        int
	outputMode        OutputMode
	stop              chan struct{}
	blacklist         []Key

	// BgColor and FgColor allow to configure the background and foreground
	// colors of the GUI.
	BgColor, FgColor, FrameColor Attribute

	// SelBgColor and SelFgColor allow to configure the background and
	// foreground colors of the frame of the current view.
	SelBgColor, SelFgColor, SelFrameColor Attribute

	// If Highlight is true, Sel{Bg,Fg}Colors will be used to draw the
	// frame of the current view.
	Highlight bool

	// If ShowListFooter is true then show list footer (i.e. the part that says we're at item 5 out of 10)
	ShowListFooter bool

	// If Cursor is true then the cursor is enabled.
	Cursor bool

	// If Mouse is true then mouse events will be enabled.
	Mouse bool

	IsPasting bool

	// If InputEsc is true, when ESC sequence is in the buffer and it doesn't
	// match any known sequence, ESC means KeyEsc.
	InputEsc bool

	// SupportOverlaps is true when we allow for view edges to overlap with other
	// view edges
	SupportOverlaps bool

	Mutexes GuiMutexes

	OnSearchEscape func() error
	// these keys must either be of type Key of rune
	SearchEscapeKey    interface{}
	NextSearchMatchKey interface{}
	PrevSearchMatchKey interface{}

	ErrorHandler func(error) error

	screen         tcell.Screen
	suspendedMutex sync.Mutex
	suspended      bool

	taskManager *TaskManager

	lastHoverView *View
}

type NewGuiOpts struct {
	OutputMode      OutputMode
	SupportOverlaps bool
	PlayRecording   bool
	Headless        bool
	// only applicable when Headless is true
	Width int
	// only applicable when Headless is true
	Height int

	RuneReplacements map[rune]string
}

// NewGui returns a new Gui object with a given output mode.
func NewGui(opts NewGuiOpts) (*Gui, error) {
	g := &Gui{}

	var err error
	if opts.Headless {
		err = g.tcellInitSimulation(opts.Width, opts.Height)
	} else {
		err = g.tcellInit(runeReplacements)
	}
	if err != nil {
		return nil, err
	}

	if opts.Headless || runtime.GOOS == "windows" {
		g.maxX, g.maxY = g.screen.Size()
	} else {
		// TODO: find out if we actually need this bespoke logic for linux
		g.maxX, g.maxY, err = g.getTermWindowSize()
		if err != nil {
			return nil, err
		}
	}

	g.outputMode = opts.OutputMode

	g.stop = make(chan struct{})

	g.gEvents = make(chan GocuiEvent, 20)
	g.userEvents = make(chan userEvent, 20)
	g.taskManager = newTaskManager()

	if opts.PlayRecording {
		g.ReplayedEvents = replayedEvents{
			Keys:        make(chan *TcellKeyEventWrapper),
			Resizes:     make(chan *TcellResizeEventWrapper),
			MouseEvents: make(chan *TcellMouseEventWrapper),
		}
	}

	g.BgColor, g.FgColor, g.FrameColor = ColorDefault, ColorDefault, ColorDefault
	g.SelBgColor, g.SelFgColor, g.SelFrameColor = ColorDefault, ColorDefault, ColorDefault

	// SupportOverlaps is true when we allow for view edges to overlap with other
	// view edges
	g.SupportOverlaps = opts.SupportOverlaps

	// default keys for when searching strings in a view
	g.SearchEscapeKey = KeyEsc
	g.NextSearchMatchKey = 'n'
	g.PrevSearchMatchKey = 'N'

	g.playRecording = opts.PlayRecording

	return g, nil
}

func (g *Gui) NewTask() *TaskImpl {
	return g.taskManager.NewTask()
}

// An idle listener listens for when the program is idle. This is useful for
// integration tests which can wait for the program to be idle before taking
// the next step in the test.
func (g *Gui) AddIdleListener(c chan struct{}) {
	g.taskManager.addIdleListener(c)
}

// Close finalizes the library. It should be called after a successful
// initialization and when gocui is not needed anymore.
func (g *Gui) Close() {
	close(g.stop)
	Screen.Fini()
}

// Size returns the terminal's size.
func (g *Gui) Size() (x, y int) {
	return g.maxX, g.maxY
}

// SetRune writes a rune at the given point, relative to the top-left
// corner of the terminal. It checks if the position is valid and applies
// the given colors.
func (g *Gui) SetRune(x, y int, ch rune, fgColor, bgColor Attribute) error {
	if x < 0 || y < 0 || x >= g.maxX || y >= g.maxY {
		// swallowing error because it's not that big of a deal
		return nil
	}
	tcellSetCell(x, y, ch, fgColor, bgColor, g.outputMode)
	return nil
}

// Rune returns the rune contained in the cell at the given position.
// It checks if the position is valid.
func (g *Gui) Rune(x, y int) (rune, error) {
	if x < 0 || y < 0 || x >= g.maxX || y >= g.maxY {
		return ' ', errors.New("invalid point")
	}
	c, _, _, _ := Screen.GetContent(x, y)
	return c, nil
}

// SetView creates a new view with its top-left corner at (x0, y0)
// and the bottom-right one at (x1, y1). If a view with the same name
// already exists, its dimensions are updated; otherwise, the error
// ErrUnknownView is returned, which allows to assert if the View must
// be initialized. It checks if the position is valid.
func (g *Gui) SetView(name string, x0, y0, x1, y1 int, overlaps byte) (*View, error) {
	if name == "" {
		return nil, errors.New("invalid name")
	}

	if v, err := g.View(name); err == nil {
		sizeChanged := v.x0 != x0 || v.x1 != x1 || v.y0 != y0 || v.y1 != y1

		v.x0 = x0
		v.y0 = y0
		v.x1 = x1
		v.y1 = y1

		if sizeChanged {
			v.clearViewLines()

			if v.Editable {
				cursorX, cursorY := v.TextArea.GetCursorXY()
				newViewCursorX, newOriginX := updatedCursorAndOrigin(0, v.InnerWidth(), cursorX)
				newViewCursorY, newOriginY := updatedCursorAndOrigin(0, v.InnerHeight(), cursorY)

				v.SetCursor(newViewCursorX, newViewCursorY)
				v.SetOrigin(newOriginX, newOriginY)
			}
		}

		return v, nil
	}

	g.Mutexes.ViewsMutex.Lock()

	v := NewView(name, x0, y0, x1, y1, g.outputMode)
	v.BgColor, v.FgColor = g.BgColor, g.FgColor
	v.SelBgColor, v.SelFgColor = g.SelBgColor, g.SelFgColor
	v.Overlaps = overlaps
	g.views = append(g.views, v)

	g.Mutexes.ViewsMutex.Unlock()

	return v, errors.Wrap(ErrUnknownView, 0)
}

// SetViewBeneath sets a view stacked beneath another view
func (g *Gui) SetViewBeneath(name string, aboveViewName string, height int) (*View, error) {
	aboveView, err := g.View(aboveViewName)
	if err != nil {
		return nil, err
	}

	viewTop := aboveView.y1 + 1
	return g.SetView(name, aboveView.x0, viewTop, aboveView.x1, viewTop+height-1, 0)
}

// SetViewOnTop sets the given view on top of the existing ones.
func (g *Gui) SetViewOnTop(name string) (*View, error) {
	g.Mutexes.ViewsMutex.Lock()
	defer g.Mutexes.ViewsMutex.Unlock()

	for i, v := range g.views {
		if v.name == name {
			s := append(g.views[:i], g.views[i+1:]...)
			g.views = append(s, v)
			return v, nil
		}
	}
	return nil, errors.Wrap(ErrUnknownView, 0)
}

// SetViewOnBottom sets the given view on bottom of the existing ones.
func (g *Gui) SetViewOnBottom(name string) (*View, error) {
	g.Mutexes.ViewsMutex.Lock()
	defer g.Mutexes.ViewsMutex.Unlock()

	for i, v := range g.views {
		if v.name == name {
			s := append(g.views[:i], g.views[i+1:]...)
			g.views = append([]*View{v}, s...)
			return v, nil
		}
	}
	return nil, errors.Wrap(ErrUnknownView, 0)
}

func (g *Gui) SetViewOnTopOf(toMove string, other string) error {
	g.Mutexes.ViewsMutex.Lock()
	defer g.Mutexes.ViewsMutex.Unlock()

	if toMove == other {
		return nil
	}

	// need to find the two current positions and then move toMove before other in the list.
	toMoveIndex := -1
	otherIndex := -1

	for i, v := range g.views {
		if v.name == toMove {
			toMoveIndex = i
		}

		if v.name == other {
			otherIndex = i
		}
	}

	if toMoveIndex == -1 || otherIndex == -1 {
		return errors.Wrap(ErrUnknownView, 0)
	}

	// already on top
	if toMoveIndex > otherIndex {
		return nil
	}

	// need to actually do it the other way around. Last is highest
	viewToMove := g.views[toMoveIndex]

	g.views = append(g.views[:toMoveIndex], g.views[toMoveIndex+1:]...)
	g.views = append(g.views[:otherIndex], append([]*View{viewToMove}, g.views[otherIndex:]...)...)
	return nil
}

// replaces the content in toView with the content in fromView
func (g *Gui) CopyContent(fromView *View, toView *View) {
	g.Mutexes.ViewsMutex.Lock()
	defer g.Mutexes.ViewsMutex.Unlock()

	toView.CopyContent(fromView)
}

// Views returns all the views in the GUI.
func (g *Gui) Views() []*View {
	return g.views
}

// View returns a pointer to the view with the given name, or error
// ErrUnknownView if a view with that name does not exist.
func (g *Gui) View(name string) (*View, error) {
	g.Mutexes.ViewsMutex.Lock()
	defer g.Mutexes.ViewsMutex.Unlock()

	for _, v := range g.views {
		if v.name == name {
			return v, nil
		}
	}
	return nil, errors.Wrap(ErrUnknownView, 0)
}

// VisibleViewByPosition returns a pointer to a view matching the given position, or
// error ErrUnknownView if a view in that position does not exist.
func (g *Gui) VisibleViewByPosition(x, y int) (*View, error) {
	g.Mutexes.ViewsMutex.Lock()
	defer g.Mutexes.ViewsMutex.Unlock()

	// traverse views in reverse order checking top views first
	for i := len(g.views); i > 0; i-- {
		v := g.views[i-1]

		if !v.Visible {
			continue
		}

		frameOffset := 0
		if v.Frame {
			frameOffset = 1
		}
		if x > v.x0-frameOffset && x < v.x1+frameOffset && y > v.y0-frameOffset && y < v.y1+frameOffset {
			return v, nil
		}
	}
	return nil, errors.Wrap(ErrUnknownView, 0)
}

// ViewPosition returns the coordinates of the view with the given name, or
// error ErrUnknownView if a view with that name does not exist.
func (g *Gui) ViewPosition(name string) (x0, y0, x1, y1 int, err error) {
	g.Mutexes.ViewsMutex.Lock()
	defer g.Mutexes.ViewsMutex.Unlock()

	for _, v := range g.views {
		if v.name == name {
			return v.x0, v.y0, v.x1, v.y1, nil
		}
	}
	return 0, 0, 0, 0, errors.Wrap(ErrUnknownView, 0)
}

// DeleteView deletes a view by name.
func (g *Gui) DeleteView(name string) error {
	g.Mutexes.ViewsMutex.Lock()
	defer g.Mutexes.ViewsMutex.Unlock()

	for i, v := range g.views {
		if v.name == name {
			g.views = append(g.views[:i], g.views[i+1:]...)
			return nil
		}
	}
	return errors.Wrap(ErrUnknownView, 0)
}

// SetCurrentView gives the focus to a given view.
func (g *Gui) SetCurrentView(name string) (*View, error) {
	g.Mutexes.ViewsMutex.Lock()
	defer g.Mutexes.ViewsMutex.Unlock()

	for _, v := range g.views {
		if v.name == name {
			g.currentView = v
			return v, nil
		}
	}
	return nil, errors.Wrap(ErrUnknownView, 0)
}

// CurrentView returns the currently focused view, or nil if no view
// owns the focus.
func (g *Gui) CurrentView() *View {
	return g.currentView
}

// SetKeybinding creates a new keybinding. If viewname equals to ""
// (empty string) then the keybinding will apply to all views. key must
// be a rune or a Key.
//
// When mouse keys are used (MouseLeft, MouseRight, ...), modifier might not work correctly.
// It behaves differently on different platforms. Somewhere it doesn't register Alt key press,
// on others it might report Ctrl as Alt. It's not consistent and therefore it's not recommended
// to use with mouse keys.
func (g *Gui) SetKeybinding(viewname string, key interface{}, mod Modifier, handler func(*Gui, *View) error) error {
	var kb *keybinding

	k, ch, err := getKey(key)
	if err != nil {
		return err
	}

	if g.isBlacklisted(k) {
		return ErrBlacklisted
	}

	kb = newKeybinding(viewname, k, ch, mod, handler)
	g.keybindings = append(g.keybindings, kb)
	return nil
}

// DeleteKeybinding deletes a keybinding.
func (g *Gui) DeleteKeybinding(viewname string, key interface{}, mod Modifier) error {
	k, ch, err := getKey(key)
	if err != nil {
		return err
	}

	for i, kb := range g.keybindings {
		if kb.viewName == viewname && kb.ch == ch && kb.key == k && kb.mod == mod {
			g.keybindings = append(g.keybindings[:i], g.keybindings[i+1:]...)
			return nil
		}
	}
	return errors.New("keybinding not found")
}

// DeleteKeybindings deletes all keybindings of view.
func (g *Gui) DeleteAllKeybindings() {
	g.keybindings = []*keybinding{}
	g.tabClickBindings = []*tabClickBinding{}
	g.viewMouseBindings = []*ViewMouseBinding{}
}

// DeleteKeybindings deletes all keybindings of view.
func (g *Gui) DeleteViewKeybindings(viewname string) {
	var s []*keybinding
	for _, kb := range g.keybindings {
		if kb.viewName != viewname {
			s = append(s, kb)
		}
	}
	g.keybindings = s
}

// SetTabClickBinding sets a binding for a tab click event
func (g *Gui) SetTabClickBinding(viewName string, handler tabClickHandler) error {
	g.tabClickBindings = append(g.tabClickBindings, &tabClickBinding{
		viewName: viewName,
		handler:  handler,
	})

	return nil
}

func (g *Gui) SetViewClickBinding(binding *ViewMouseBinding) error {
	g.viewMouseBindings = append(g.viewMouseBindings, binding)

	return nil
}

// BlackListKeybinding adds a keybinding to the blacklist
func (g *Gui) BlacklistKeybinding(k Key) error {
	for _, j := range g.blacklist {
		if j == k {
			return ErrAlreadyBlacklisted
		}
	}
	g.blacklist = append(g.blacklist, k)
	return nil
}

// WhiteListKeybinding removes a keybinding from the blacklist
func (g *Gui) WhitelistKeybinding(k Key) error {
	for i, j := range g.blacklist {
		if j == k {
			g.blacklist = append(g.blacklist[:i], g.blacklist[i+1:]...)
			return nil
		}
	}
	return ErrNotBlacklisted
}

func (g *Gui) SetFocusHandler(handler func(bool) error) {
	g.focusHandler = handler
}

func (g *Gui) SetOpenHyperlinkFunc(openHyperlinkFunc func(string, string) error) {
	g.openHyperlink = openHyperlinkFunc
}

// getKey takes an empty interface with a key and returns the corresponding
// typed Key or rune.
func getKey(key interface{}) (Key, rune, error) {
	switch t := key.(type) {
	case nil: // Ignore keybinding if `nil`
		return 0, 0, nil
	case Key:
		return t, 0, nil
	case rune:
		return 0, t, nil
	default:
		return 0, 0, errors.New("unknown type")
	}
}

// userEvent represents an event triggered by the user.
type userEvent struct {
	f    func(*Gui) error
	task Task
}

// Update executes the passed function. This method can be called safely from a
// goroutine in order to update the GUI. It is important to note that the
// passed function won't be executed immediately, instead it will be added to
// the user events queue. Given that Update spawns a goroutine, the order in
// which the user events will be handled is not guaranteed.
func (g *Gui) Update(f func(*Gui) error) {
	task := g.NewTask()

	go g.updateAsyncAux(f, task)
}

// UpdateAsync is a version of Update that does not spawn a go routine, it can
// be a bit more efficient in cases where Update is called many times like when
// tailing a file.  In general you should use Update()
func (g *Gui) UpdateAsync(f func(*Gui) error) {
	task := g.NewTask()

	g.updateAsyncAux(f, task)
}

func (g *Gui) updateAsyncAux(f func(*Gui) error, task Task) {
	g.userEvents <- userEvent{f: f, task: task}
}

// Calls a function in a goroutine. Handles panics gracefully and tracks
// number of background tasks.
// Always use this when you want to spawn a goroutine and you want lazygit to
// consider itself 'busy` as it runs the code. Don't use for long-running
// background goroutines where you wouldn't want lazygit to be considered busy
// (i.e. when you wouldn't want a loader to be shown to the user)
func (g *Gui) OnWorker(f func(Task) error) {
	task := g.NewTask()
	go func() {
		g.onWorkerAux(f, task)
		task.Done()
	}()
}

func (g *Gui) onWorkerAux(f func(Task) error, task Task) {
	panicking := true
	defer func() {
		if panicking && Screen != nil {
			Screen.Fini()
		}
	}()

	err := f(task)

	panicking = false

	if err != nil {
		g.Update(func(g *Gui) error {
			return err
		})
	}
}

// A Manager is in charge of GUI's layout and can be used to build widgets.
type Manager interface {
	// Layout is called every time the GUI is redrawn, it must contain the
	// base views and its initializations.
	Layout(*Gui) error
}

// The ManagerFunc type is an adapter to allow the use of ordinary functions as
// Managers. If f is a function with the appropriate signature, ManagerFunc(f)
// is an Manager object that calls f.
type ManagerFunc func(*Gui) error

// Layout calls f(g)
func (f ManagerFunc) Layout(g *Gui) error {
	return f(g)
}

// SetManager sets the given GUI managers. It deletes all views and
// keybindings.
func (g *Gui) SetManager(managers ...Manager) {
	g.managers = managers
	g.currentView = nil
	g.views = nil
	g.keybindings = nil
	g.tabClickBindings = nil

	go func() { g.gEvents <- GocuiEvent{Type: eventResize} }()
}

// SetManagerFunc sets the given manager function. It deletes all views and
// keybindings.
func (g *Gui) SetManagerFunc(manager func(*Gui) error) {
	g.SetManager(ManagerFunc(manager))
}

// MainLoop runs the main loop until an error is returned. A successful
// finish should return ErrQuit.
func (g *Gui) MainLoop() error {
	go func() {
		for {
			select {
			case <-g.stop:
				return
			default:
				g.gEvents <- g.pollEvent()
			}
		}
	}()

	Screen.EnableFocus()
	Screen.EnablePaste()

	previousEnableMouse := false
	for {
		if g.Mouse != previousEnableMouse {
			if g.Mouse {
				Screen.EnableMouse()
			} else {
				Screen.DisableMouse()
			}

			previousEnableMouse = g.Mouse
		}

		err := g.processEvent()
		if err != nil {
			return err
		}
	}
}

func (g *Gui) handleError(err error) error {
	if err != nil && !standardErrors.Is(err, ErrQuit) && g.ErrorHandler != nil {
		return g.ErrorHandler(err)
	}

	return err
}

func (g *Gui) processEvent() error {
	select {
	case ev := <-g.gEvents:
		task := g.NewTask()
		defer func() { task.Done() }()

		if err := g.handleError(g.handleEvent(&ev)); err != nil {
			return err
		}
	case ev := <-g.userEvents:
		defer func() { ev.task.Done() }()

		if err := g.handleError(ev.f(g)); err != nil {
			return err
		}
	}

	if err := g.processRemainingEvents(); err != nil {
		return err
	}
	if err := g.flush(); err != nil {
		return err
	}

	return nil
}

// processRemainingEvents handles the remaining events in the events pool.
func (g *Gui) processRemainingEvents() error {
	for {
		select {
		case ev := <-g.gEvents:
			if err := g.handleError(g.handleEvent(&ev)); err != nil {
				return err
			}
		case ev := <-g.userEvents:
			err := g.handleError(ev.f(g))
			ev.task.Done()
			if err != nil {
				return err
			}
		default:
			return nil
		}
	}
}

// handleEvent handles an event, based on its type (key-press, error,
// etc.)
func (g *Gui) handleEvent(ev *GocuiEvent) error {
	switch ev.Type {
	case eventKey, eventMouse, eventMouseMove:
		return g.onKey(ev)
	case eventError:
		return ev.Err
	case eventResize:
		g.onResize()
		return nil
	case eventFocus:
		return g.onFocus(ev)
	case eventPaste:
		g.IsPasting = ev.Start
		return nil
	default:
		return nil
	}
}

func (g *Gui) onResize() {
	// not sure if we actually need this
	// g.screen.Sync()
}

// drawFrameEdges draws the horizontal and vertical edges of a view.
func (g *Gui) drawFrameEdges(v *View, fgColor, bgColor Attribute) error {
	runeH, runeV := '─', '│'
	if len(v.FrameRunes) >= 2 {
		runeH, runeV = v.FrameRunes[0], v.FrameRunes[1]
	}

	for x := v.x0 + 1; x < v.x1 && x < g.maxX; x++ {
		if x < 0 {
			continue
		}
		if v.y0 > -1 && v.y0 < g.maxY {
			if err := g.SetRune(x, v.y0, runeH, fgColor, bgColor); err != nil {
				return err
			}
		}
		if v.y1 > -1 && v.y1 < g.maxY {
			if err := g.SetRune(x, v.y1, runeH, fgColor, bgColor); err != nil {
				return err
			}
		}
	}

	showScrollbar, realScrollbarStart, realScrollbarEnd := calcRealScrollbarStartEnd(v)
	for y := v.y0 + 1; y < v.y1 && y < g.maxY; y++ {
		if y < 0 {
			continue
		}
		if v.x0 > -1 && v.x0 < g.maxX {
			if err := g.SetRune(v.x0, y, runeV, fgColor, bgColor); err != nil {
				return err
			}
		}
		if v.x1 > -1 && v.x1 < g.maxX {
			runeToPrint := calcScrollbarRune(showScrollbar, realScrollbarStart, realScrollbarEnd, y, runeV)

			if err := g.SetRune(v.x1, y, runeToPrint, fgColor, bgColor); err != nil {
				return err
			}
		}
	}
	return nil
}

func calcScrollbarRune(
	showScrollbar bool, scrollbarStart int, scrollbarEnd int, position int, runeV rune,
) rune {
	if showScrollbar && (position >= scrollbarStart && position <= scrollbarEnd) {
		return '▐'
	} else {
		return runeV
	}
}

func calcRealScrollbarStartEnd(v *View) (bool, int, int) {
	height := v.InnerHeight()
	fullHeight := v.ViewLinesHeight() - v.scrollMargin()

	if v.CanScrollPastBottom {
		fullHeight += height
	}

	if height < 2 || height >= fullHeight {
		return false, 0, 0
	}

	originY := v.OriginY()
	scrollbarStart, scrollbarHeight := calcScrollbar(fullHeight, height, originY, height-1)
	top := v.y0 + 1
	realScrollbarStart := top + scrollbarStart
	realScrollbarEnd := realScrollbarStart + scrollbarHeight

	return true, realScrollbarStart, realScrollbarEnd
}

func cornerRune(index byte) rune {
	return []rune{' ', '│', '│', '│', '─', '┘', '┐', '┤', '─', '└', '┌', '├', '├', '┴', '┬', '┼'}[index]
}

// cornerCustomRune returns rune from `v.FrameRunes` slice. If the length of slice is less than 11
// all the missing runes will be translated to the default `cornerRune()`
func cornerCustomRune(v *View, index byte) rune {
	// Translate `cornerRune()` index
	//  0    1    2    3    4    5    6    7    8    9    10   11   12   13   14   15
	// ' ', '│', '│', '│', '─', '┘', '┐', '┤', '─', '└', '┌', '├', '├', '┴', '┬', '┼'
	// into `FrameRunes` index
	//  0    1    2    3    4    5    6    7    8    9    10
	// '─', '│', '┌', '┐', '└', '┘', '├', '┤', '┬', '┴', '┼'
	switch index {
	case 1, 2, 3:
		return v.FrameRunes[1]
	case 4, 8:
		return v.FrameRunes[0]
	case 5:
		return v.FrameRunes[5]
	case 6:
		return v.FrameRunes[3]
	case 7:
		if len(v.FrameRunes) < 8 {
			break
		}
		return v.FrameRunes[7]
	case 9:
		return v.FrameRunes[4]
	case 10:
		return v.FrameRunes[2]
	case 11, 12:
		if len(v.FrameRunes) < 7 {
			break
		}
		return v.FrameRunes[6]
	case 13:
		if len(v.FrameRunes) < 10 {
			break
		}
		return v.FrameRunes[9]
	case 14:
		if len(v.FrameRunes) < 9 {
			break
		}
		return v.FrameRunes[8]
	case 15:
		if len(v.FrameRunes) < 11 {
			break
		}
		return v.FrameRunes[10]
	default:
		return ' ' // cornerRune(0)
	}
	return cornerRune(index)
}

func corner(v *View, directions byte) rune {
	index := v.Overlaps | directions
	if len(v.FrameRunes) >= 6 {
		return cornerCustomRune(v, index)
	}
	return cornerRune(index)
}

// drawFrameCorners draws the corners of the view.
func (g *Gui) drawFrameCorners(v *View, fgColor, bgColor Attribute) error {
	if v.y0 == v.y1 {
		if !g.SupportOverlaps && v.x0 >= 0 && v.x1 >= 0 && v.y0 >= 0 && v.x0 < g.maxX && v.x1 < g.maxX && v.y0 < g.maxY {
			if err := g.SetRune(v.x0, v.y0, '╶', fgColor, bgColor); err != nil {
				return err
			}
			if err := g.SetRune(v.x1, v.y0, '╴', fgColor, bgColor); err != nil {
				return err
			}
		}
		return nil
	}

	runeTL, runeTR, runeBL, runeBR := '┌', '┐', '└', '┘'
	if len(v.FrameRunes) >= 6 {
		runeTL, runeTR, runeBL, runeBR = v.FrameRunes[2], v.FrameRunes[3], v.FrameRunes[4], v.FrameRunes[5]
	}
	if g.SupportOverlaps {
		runeTL = corner(v, BOTTOM|RIGHT)
		runeTR = corner(v, BOTTOM|LEFT)
		runeBL = corner(v, TOP|RIGHT)
		runeBR = corner(v, TOP|LEFT)
	}

	corners := []struct {
		x, y int
		ch   rune
	}{{v.x0, v.y0, runeTL}, {v.x1, v.y0, runeTR}, {v.x0, v.y1, runeBL}, {v.x1, v.y1, runeBR}}

	for _, c := range corners {
		if c.x >= 0 && c.y >= 0 && c.x < g.maxX && c.y < g.maxY {
			if err := g.SetRune(c.x, c.y, c.ch, fgColor, bgColor); err != nil {
				return err
			}
		}
	}
	return nil
}

// drawTitle draws the title of the view.
func (g *Gui) drawTitle(v *View, fgColor, bgColor Attribute) error {
	if v.y0 < 0 || v.y0 >= g.maxY {
		return nil
	}

	tabs := v.Tabs
	prefix := v.TitlePrefix
	if prefix != "" {
		if len(v.FrameRunes) > 0 {
			prefix += string(v.FrameRunes[0])
		} else {
			prefix += "─"
		}
	}
	separator := " - "
	charIndex := 0
	currentTabStart := -1
	currentTabEnd := -1
	if len(tabs) == 0 {
		tabs = []string{v.Title}
	} else {
		for i, tab := range tabs {
			if i == v.TabIndex {
				currentTabStart = charIndex
				currentTabEnd = charIndex + len(tab)
				break
			}
			charIndex += len(tab)
			if i < len(tabs)-1 {
				charIndex += len(separator)
			}
		}
	}

	str := strings.Join(tabs, separator)

	x := v.x0 + 2
	for _, ch := range prefix {
		if err := g.SetRune(x, v.y0, ch, fgColor, bgColor); err != nil {
			return err
		}
		x += runewidth.RuneWidth(ch)
	}
	for i, ch := range str {
		if x < 0 {
			continue
		} else if x > v.x1-2 || x >= g.maxX {
			break
		}
		currentFgColor := fgColor
		currentBgColor := bgColor
		// if you are the current view and you have multiple tabs, de-highlight the non-selected tabs
		if v == g.currentView && len(v.Tabs) > 0 {
			currentFgColor = v.FgColor
			currentBgColor = v.BgColor
		}

		if i >= currentTabStart && i <= currentTabEnd {
			currentFgColor = v.SelFgColor
			if v != g.currentView {
				currentFgColor &= ^AttrBold
			}
		}
		if err := g.SetRune(x, v.y0, ch, currentFgColor, currentBgColor); err != nil {
			return err
		}
		x += runewidth.RuneWidth(ch)
	}
	return nil
}

// drawSubtitle draws the subtitle of the view.
func (g *Gui) drawSubtitle(v *View, fgColor, bgColor Attribute) error {
	if v.y0 < 0 || v.y0 >= g.maxY {
		return nil
	}

	start := v.x1 - 5 - runewidth.StringWidth(v.Subtitle)
	if start < v.x0 {
		return nil
	}
	x := start
	for _, ch := range v.Subtitle {
		if x >= v.x1 {
			break
		}
		if err := g.SetRune(x, v.y0, ch, fgColor, bgColor); err != nil {
			return err
		}
		x += runewidth.RuneWidth(ch)
	}
	return nil
}

// drawListFooter draws the footer of a list view, showing something like '1 of 10'
func (g *Gui) drawListFooter(v *View, fgColor, bgColor Attribute) error {
	if len(v.lines) == 0 {
		return nil
	}

	message := v.Footer

	if v.y1 < 0 || v.y1 >= g.maxY {
		return nil
	}

	start := v.x1 - 1 - runewidth.StringWidth(message)
	if start < v.x0 {
		return nil
	}
	x := start
	for _, ch := range message {
		if x >= v.x1 {
			break
		}
		if err := g.SetRune(x, v.y1, ch, fgColor, bgColor); err != nil {
			return err
		}
		x += runewidth.RuneWidth(ch)
	}
	return nil
}

// flush updates the gui, re-drawing frames and buffers.
func (g *Gui) flush() error {
	// pretty sure we don't need this, but keeping it here in case we get weird visual artifacts
	// g.clear(g.FgColor, g.BgColor)

	maxX, maxY := Screen.Size()
	// if GUI's size has changed, we need to redraw all views
	if maxX != g.maxX || maxY != g.maxY {
		for _, v := range g.views {
			v.clearViewLines()
		}
	}
	g.maxX, g.maxY = maxX, maxY

	for _, m := range g.managers {
		if err := m.Layout(g); err != nil {
			return err
		}
	}
	for _, v := range g.views {
		if err := g.draw(v); err != nil {
			return err
		}
	}

	Screen.Show()
	return nil
}

func (g *Gui) ForceLayoutAndRedraw() error {
	return g.flush()
}

// force redrawing one or more views outside of the normal main loop. Useful during longer
// operations that block the main thread, to update a spinner in a status view.
func (g *Gui) ForceRedrawViews(views ...*View) error {
	for _, m := range g.managers {
		if err := m.Layout(g); err != nil {
			return err
		}
	}

	for _, v := range views {
		v.draw()
	}

	Screen.Show()
	return nil
}

// draw manages the cursor and calls the draw function of a view.
func (g *Gui) draw(v *View) error {
	if g.suspended {
		return nil
	}

	if !v.Visible || v.y1 < v.y0 || v.x1 < v.x0 {
		return nil
	}

	if g.Cursor {
		if curview := g.currentView; curview != nil {
			vMaxX, vMaxY := curview.InnerSize()
			if curview.cx >= 0 && curview.cx < vMaxX && curview.cy >= 0 && curview.cy < vMaxY {
				cx, cy := curview.x0+curview.cx+1, curview.y0+curview.cy+1
				Screen.ShowCursor(cx, cy)
			} else {
				Screen.HideCursor()
			}
		}
	} else {
		Screen.HideCursor()
	}

	v.draw()

	if v.Frame {
		var fgColor, bgColor, frameColor Attribute
		if g.Highlight && v == g.currentView {
			fgColor = g.SelFgColor
			bgColor = g.SelBgColor
			frameColor = g.SelFrameColor
		} else {
			bgColor = g.BgColor
			if v.TitleColor != ColorDefault {
				fgColor = v.TitleColor
			} else {
				fgColor = g.FgColor
			}
			if v.FrameColor != ColorDefault {
				frameColor = v.FrameColor
			} else {
				frameColor = g.FrameColor
			}
		}

		if err := g.drawFrameEdges(v, frameColor, bgColor); err != nil {
			return err
		}
		if err := g.drawFrameCorners(v, frameColor, bgColor); err != nil {
			return err
		}
		if v.Title != "" || len(v.Tabs) > 0 {
			if err := g.drawTitle(v, fgColor, bgColor); err != nil {
				return err
			}
		}
		if v.Subtitle != "" {
			if err := g.drawSubtitle(v, fgColor, bgColor); err != nil {
				return err
			}
		}
		if v.Footer != "" && g.ShowListFooter {
			if err := g.drawListFooter(v, fgColor, bgColor); err != nil {
				return err
			}
		}
	}

	return nil
}

// onKey manages key-press events. A keybinding handler is called when
// a key-press or mouse event satisfies a configured keybinding. Furthermore,
// currentView's internal buffer is modified if currentView.Editable is true.
func (g *Gui) onKey(ev *GocuiEvent) error {
	switch ev.Type {
	case eventKey:

		// When pasting text in Ghostty, it sends us '\r' instead of '\n' for
		// newlines. I actually don't quite understand why, because from reading
		// Ghostty's source code (e.g.
		// https://github.com/ghostty-org/ghostty/commit/010338354a0) it does
		// this conversion only for non-bracketed paste mode, but I'm seeing it
		// in bracketed paste mode. Whatever I'm missing here, converting '\r'
		// back to '\n' fixes pasting multi-line text from Ghostty, and doesn't
		// seem harmful for other terminal emulators.
		//
		// KeyCtrlJ (int value 10) is '\r', and KeyCtrlM (int value 13) is '\n'.
		if g.IsPasting && ev.Key == KeyCtrlJ {
			ev.Key = KeyCtrlM
		}

		err := g.execKeybindings(g.currentView, ev)
		if err != nil {
			return err
		}

	case eventMouse:
		mx, my := ev.MouseX, ev.MouseY
		v, err := g.VisibleViewByPosition(mx, my)
		if err != nil {
			break
		}
		if v.Frame && my == v.y0 {
			if len(v.Tabs) > 0 {
				tabIndex := v.GetClickedTabIndex(mx - v.x0)

				if tabIndex >= 0 {
					for _, binding := range g.tabClickBindings {
						if binding.viewName == v.Name() {
							return binding.handler(tabIndex)
						}
					}
				}
			}
		}

		// newCx and newCy are relative to the view port, i.e. to the visible area of the view
		newCx := mx - v.x0 - 1
		newCy := my - v.y0 - 1
		// newX and newY are relative to the view's content, independent of its scroll position
		newX := newCx + v.ox
		newY := newCy + v.oy
		// if view is editable don't go further than the furthest character for that line
		if v.Editable {
			if newY < 0 {
				newY = 0
				newCy = -v.oy
			} else if newY >= len(v.lines) {
				newY = len(v.lines) - 1
				newCy = newY - v.oy
			}

			lastCharForLine := len(v.lines[newY])
			for lastCharForLine > 0 && v.lines[newY][lastCharForLine-1].chr == 0 {
				lastCharForLine--
			}
			if lastCharForLine < newX {
				newX = lastCharForLine
				newCx = lastCharForLine - v.ox
			}
		}
		if !IsMouseScrollKey(ev.Key) {
			v.SetCursor(newCx, newCy)
			if v.Editable {
				v.TextArea.SetCursor2D(newX, newY)

				// SetCursor2D might have adjusted the text area's cursor to the
				// left to move left from a soft line break, so we need to
				// update the view's cursor to match the text area's cursor.
				cX, _ := v.TextArea.GetCursorXY()
				v.SetCursorX(cX)
			}
		}

		if ev.Key == MouseLeft && !v.Editable && g.openHyperlink != nil {
			if newY >= 0 && newY <= len(v.viewLines)-1 && newX >= 0 && newX <= len(v.viewLines[newY].line)-1 {
				if link := v.viewLines[newY].line[newX].hyperlink; link != "" {
					return g.openHyperlink(link, v.name)
				}
			}
		}

		if IsMouseKey(ev.Key) {
			opts := ViewMouseBindingOpts{X: newX, Y: newY}
			matched, err := g.execMouseKeybindings(v, ev, opts)
			if err != nil {
				return err
			}
			if matched {
				return nil
			}
		}

		if err := g.execKeybindings(v, ev); err != nil {
			return err
		}

	case eventMouseMove:
		mx, my := ev.MouseX, ev.MouseY
		v, err := g.VisibleViewByPosition(mx, my)
		if err != nil {
			break
		}
		if g.lastHoverView != nil && g.lastHoverView != v {
			g.lastHoverView.lastHoverPosition = nil
			g.lastHoverView.hoveredHyperlink = nil
		}
		g.lastHoverView = v
		v.onMouseMove(mx, my)

	default:
	}

	return nil
}

func (g *Gui) execMouseKeybindings(view *View, ev *GocuiEvent, opts ViewMouseBindingOpts) (bool, error) {
	isMatch := func(binding *ViewMouseBinding) bool {
		return binding.ViewName == view.Name() &&
			ev.Key == binding.Key &&
			ev.Mod == binding.Modifier
	}

	// first pass looks for ones that match the focused view
	for _, binding := range g.viewMouseBindings {
		if isMatch(binding) && binding.FocusedView != "" && binding.FocusedView == g.currentView.Name() {
			return true, binding.Handler(opts)
		}
	}

	for _, binding := range g.viewMouseBindings {
		if isMatch(binding) && binding.FocusedView == "" {
			return true, binding.Handler(opts)
		}
	}

	return false, nil
}

func IsMouseKey(key interface{}) bool {
	switch key {
	case
		MouseLeft,
		MouseRight,
		MouseMiddle,
		MouseRelease,
		MouseWheelUp,
		MouseWheelDown,
		MouseWheelLeft,
		MouseWheelRight:
		return true
	default:
		return false
	}
}

func IsMouseScrollKey(key interface{}) bool {
	switch key {
	case
		MouseWheelUp,
		MouseWheelDown,
		MouseWheelLeft,
		MouseWheelRight:
		return true
	default:
		return false
	}
}

// execKeybindings executes the keybinding handlers that match the passed view
// and event.
func (g *Gui) execKeybindings(v *View, ev *GocuiEvent) error {
	var globalKb *keybinding
	var matchingParentViewKb *keybinding

	if g.IsPasting && v != nil && !v.Editable {
		return nil
	}

	// if we're searching, and we've hit n/N/Esc, we ignore the default keybinding
	if v != nil && v.IsSearching() && ev.Mod == ModNone {
		if eventMatchesKey(ev, g.NextSearchMatchKey) {
			return v.gotoNextMatch()
		} else if eventMatchesKey(ev, g.PrevSearchMatchKey) {
			return v.gotoPreviousMatch()
		} else if eventMatchesKey(ev, g.SearchEscapeKey) {
			v.searcher.clearSearch()
			if g.OnSearchEscape != nil {
				if err := g.OnSearchEscape(); err != nil {
					return err
				}
			}
			return nil
		}
	}

	var err error

	for _, kb := range g.keybindings {
		if kb.handler == nil {
			continue
		}
		if !kb.matchKeypress(ev.Key, ev.Ch, ev.Mod) {
			continue
		}
		if g.matchView(v, kb) {
			err = g.execKeybinding(v, kb)
			if !errors.Is(err, ErrKeybindingNotHandled) {
				return err
			}

			matchingParentViewKb = nil
			break
		}
		if v != nil && g.matchView(v.ParentView, kb) {
			matchingParentViewKb = kb
		}
		if globalKb == nil && kb.viewName == "" && ((v != nil && !v.Editable) || (kb.ch == 0 && kb.key != KeyCtrlU && kb.key != KeyCtrlA && kb.key != KeyCtrlE)) {
			globalKb = kb
		}
	}
	if matchingParentViewKb != nil {
		err = g.execKeybinding(v.ParentView, matchingParentViewKb)
		if !errors.Is(err, ErrKeybindingNotHandled) {
			return err
		}
	}

	if g.currentView != nil && g.currentView.Editable && g.currentView.Editor != nil {
		matched := g.currentView.Editor.Edit(g.currentView, ev.Key, ev.Ch, ev.Mod)
		if matched {
			return nil
		}
	}

	if globalKb != nil {
		err = g.execKeybinding(v, globalKb)
	}
	return err
}

// execKeybinding executes a given keybinding
func (g *Gui) execKeybinding(v *View, kb *keybinding) error {
	if g.isBlacklisted(kb.key) {
		return nil
	}

	if err := kb.handler(g, v); err != nil {
		return err
	}
	return nil
}

func (g *Gui) onFocus(ev *GocuiEvent) error {
	if g.focusHandler != nil {
		return g.focusHandler(ev.Focused)
	}

	return nil
}

func (g *Gui) StartTicking(ctx context.Context) {
	go func() {
		g.Mutexes.tickingMutex.Lock()
		defer g.Mutexes.tickingMutex.Unlock()
		ticker := time.NewTicker(time.Millisecond * 50)
		defer ticker.Stop()
	outer:
		for {
			select {
			case <-ticker.C:
				// I'm okay with having a data race here: there's no harm in letting one of these updates through
				if g.suspended {
					continue outer
				}

				for _, view := range g.Views() {
					if view.HasLoader {
						g.UpdateAsync(func(g *Gui) error { return nil })
						continue outer
					}
				}
				return
			case <-ctx.Done():
				return
			case <-g.stop:
				return
			}
		}
	}()
}

// isBlacklisted reports whether the key is blacklisted
func (g *Gui) isBlacklisted(k Key) bool {
	for _, j := range g.blacklist {
		if j == k {
			return true
		}
	}
	return false
}

func (g *Gui) Suspend() error {
	g.suspendedMutex.Lock()
	defer g.suspendedMutex.Unlock()

	if g.suspended {
		return errors.New("Already suspended")
	}

	g.suspended = true

	return g.screen.Suspend()
}

func (g *Gui) Resume() error {
	g.suspendedMutex.Lock()
	defer g.suspendedMutex.Unlock()

	if !g.suspended {
		return errors.New("Cannot resume because we are not suspended")
	}

	g.suspended = false

	return g.screen.Resume()
}

// matchView returns if the keybinding matches the current view (and the view's context)
func (g *Gui) matchView(v *View, kb *keybinding) bool {
	// if the user is typing in a field, ignore char keys
	if v == nil {
		return false
	}
	if v.Editable && kb.ch != 0 {
		return false
	}
	if kb.viewName != v.name {
		return false
	}
	return true
}

// returns a string representation of the current state of the gui, character-for-character
func (g *Gui) Snapshot() string {
	if g.screen == nil {
		return "<no screen rendered>"
	}

	width, height := g.screen.Size()

	builder := &strings.Builder{}

	for y := 0; y < height; y++ {
		for x := 0; x < width; x++ {
			char, _, _, charWidth := g.screen.GetContent(x, y)
			if charWidth == 0 {
				continue
			}
			builder.WriteRune(char)
			if charWidth > 1 {
				x += charWidth - 1
			}
		}
		builder.WriteRune('\n')
	}

	return builder.String()
}