widget: fix Editor panic

If you created an Editor and immediately SetCaret, it panicked because
e.lines was nil and it looked at e.lines[0].

- Add e.makeValid at the top of SetCaret.
- Add a test case for this situation.

Signed-off-by: Larry Clapp <larry@theclapp.org>
This commit is contained in:
Larry Clapp
2021-01-24 11:06:55 -05:00
parent 34273940a0
commit f88a8216e9
2 changed files with 3 additions and 0 deletions
+1
View File
@@ -1186,6 +1186,7 @@ func (e *Editor) Selection() (start, end int) {
// and end are in bytes, and represent offsets into the editor text. start and
// end must be at a rune boundary.
func (e *Editor) SetCaret(start, end int) {
e.makeValid()
// Constrain start and end to [0, e.Len()].
l := e.Len()
start = max(min(start, l), 0)
+2
View File
@@ -34,6 +34,8 @@ func TestEditor(t *testing.T) {
fontSize := unit.Px(10)
font := text.Font{}
e.SetCaret(0, 0) // shouldn't panic
assertCaret(t, e, 0, 0, 0)
e.SetText("æbc\naøå•")
e.Layout(gtx, cache, font, fontSize)
assertCaret(t, e, 0, 0, 0)