/
window.go
1354 lines (1255 loc) · 34.7 KB
/
window.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
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
// Copyright ©2021-2022 by Richard A. Wilkes. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, version 2.0. If a copy of the MPL was not distributed with
// this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// This Source Code Form is "Incompatible With Secondary Licenses", as
// defined by the Mozilla Public License, version 2.0.
package unison
import (
"fmt"
"image"
"slices"
"time"
"github.com/go-gl/gl/v3.2-core/gl"
"github.com/go-gl/glfw/v3.3/glfw"
"github.com/richardwilkes/toolbox"
"github.com/richardwilkes/toolbox/errs"
"github.com/richardwilkes/toolbox/fatal"
"github.com/richardwilkes/toolbox/xmath"
"github.com/richardwilkes/unison/enums/paintstyle"
"github.com/richardwilkes/unison/enums/pathop"
)
var _ UndoManagerProvider = &Window{}
var (
// DefaultTitleIcons are the default title icons that will be used for all newly created windows. The image closest to
// the size desired by the system will be selected and used, scaling if needed. If no images are specified, the system's
// default icon will be used.
DefaultTitleIcons []*Image
windowMap = make(map[*glfw.Window]*Window)
windowList []*Window
modalStack []*Window
glInited = false
)
// DragData holds data drag information.
type DragData struct {
Data map[string]any
Drawable Drawable
SamplingOptions *SamplingOptions
Ink Ink
Offset Point
}
// Window holds window information.
type Window struct {
InputCallbacks
// MinMaxContentSizeCallback returns the minimum and maximum size for the window content.
MinMaxContentSizeCallback func() (minimum, maximum Size)
// MovedCallback is called when the window is moved.
MovedCallback func()
// ResizedCallback is called when the window is resized.
ResizedCallback func()
// AllowCloseCallback is called when the user has requested that the window be closed. Return true to permit it,
// false to cancel the operation. Defaults to always returning true.
AllowCloseCallback func() bool
// WillCloseCallback is called just prior to the window closing.
WillCloseCallback func()
// DragIntoWindowWillStart is called just prior to a drag into the window starting.
DragIntoWindowWillStart func()
// DragIntoWindowFinished is called just after a drag into the window completes, whether a drop occurs or not.
DragIntoWindowFinished func()
title string
titleIcons []*Image
wnd *glfw.Window
surface *surface
data map[string]any
root *rootPanel
focus *Panel
cursor *Cursor
lastMouseDownPanel *Panel
lastMouseOverPanel *Panel
lastKeyDownPanel *Panel
lastTooltip *Panel
lastTooltipShownAt time.Time
lastDrawDuration time.Duration
tooltipSequence int
modalResultCode int
lastButton int
lastButtonCount int
lastButtonTime time.Time
lastContentRect Rect
firstButtonLocation Point
dragDataLocation Point
dragDataPanel *Panel
dragData *DragData
lastKeyModifiers Modifiers
valid bool
focused bool
transient bool
notResizable bool
undecorated bool
floating bool
inModal bool
inMouseDown bool
cursorHidden bool
}
// WindowOption holds an option for window creation.
type WindowOption func(*Window) error
// NotResizableWindowOption prevents the window from being resized by the user.
func NotResizableWindowOption() WindowOption {
return func(w *Window) error {
w.notResizable = true
return nil
}
}
// UndecoratedWindowOption prevents the standard window decorations (title as well as things like close buttons) from
// being shown.
func UndecoratedWindowOption() WindowOption {
return func(w *Window) error {
w.undecorated = true
return nil
}
}
// FloatingWindowOption causes the window to float in front of all other non-floating windows.
func FloatingWindowOption() WindowOption {
return func(w *Window) error {
w.floating = true
return nil
}
}
// TransientWindowOption causes the window to be marked as transient, which means it will never be considered the active
// window.
func TransientWindowOption() WindowOption {
return func(w *Window) error {
w.transient = true
return nil
}
}
// TitleIconsWindowOption sets the title icon of the window. The image closest to the size desired by the system will be
// selected and used, scaling if needed. If no images are specified, the system's default window icon will be used.
func TitleIconsWindowOption(images []*Image) WindowOption {
return func(w *Window) error {
w.titleIcons = images
return nil
}
}
// AllWindowsToFront brings all of the application's windows to the foreground.
func AllWindowsToFront() {
if len(windowList) != 0 {
list := make([]*Window, len(windowList))
copy(list, windowList)
for i := len(list) - 1; i >= 0; i-- {
list[i].Show()
if i == 0 {
list[i].wnd.Focus()
}
}
}
}
// WindowCount returns the number of windows that are open.
func WindowCount() int {
return len(windowList)
}
// Windows returns a slice containing the current set of open windows.
func Windows() []*Window {
list := make([]*Window, len(windowList))
copy(list, windowList)
return list
}
// ActiveWindow returns the window that currently has the keyboard focus, or nil if none of your application windows
// has the keyboard focus.
func ActiveWindow() *Window {
nextNonTransientIsFocus := false
for _, w := range windowList {
if nextNonTransientIsFocus && !w.transient {
return w
}
if w.focused {
if w.transient {
nextNonTransientIsFocus = true
continue
}
return w
}
}
return nil
}
// NewWindow creates a new, initially hidden, window. Call Show() or ToFront() to make it visible.
func NewWindow(title string, options ...WindowOption) (*Window, error) {
w := &Window{
title: title,
titleIcons: DefaultTitleIcons,
surface: &surface{},
}
for _, option := range options {
if err := option(w); err != nil {
return nil, err
}
}
glfw.WindowHint(glfw.Visible, glfw.False)
glfw.WindowHint(glfw.Resizable, glfwEnabled(!w.notResizable))
glfw.WindowHint(glfw.Decorated, glfwEnabled(!w.undecorated))
glfw.WindowHint(glfw.Floating, glfwEnabled(w.floating))
glfw.WindowHint(glfw.AutoIconify, glfw.False)
glfw.WindowHint(glfw.TransparentFramebuffer, glfw.False)
glfw.WindowHint(glfw.FocusOnShow, glfw.False)
glfw.WindowHint(glfw.ScaleToMonitor, glfw.False)
var err error
toolbox.CallWithHandler(func() {
w.wnd, err = glfw.CreateWindow(1, 1, title, nil, nil)
}, func(panicErr error) {
err = panicErr
})
if err != nil {
return nil, errs.Wrap(err)
}
w.wnd.SetRefreshCallback(func(_ *glfw.Window) {
delete(redrawSet, w)
w.draw()
})
w.wnd.SetPosCallback(func(_ *glfw.Window, _, _ int) {
w.moved()
})
w.wnd.SetSizeCallback(func(_ *glfw.Window, width, height int) {
if width > 0 && height > 0 {
w.resized()
}
})
w.wnd.SetCloseCallback(func(_ *glfw.Window) {
if w.okToProcess() {
w.AttemptClose()
}
})
w.wnd.SetFocusCallback(func(_ *glfw.Window, focused bool) {
if focused {
if w.okToProcess() {
w.gainedFocus()
} else {
modalStack[len(modalStack)-1].ToFront()
}
} else {
w.lostFocus()
}
})
w.wnd.SetMouseButtonCallback(w.mouseButtonCallback)
w.wnd.SetCursorPosCallback(func(_ *glfw.Window, x, y float64) {
where := w.convertMouseLocation(x, y)
if w.inMouseDown {
w.mouseDrag(where, w.lastButton, w.lastKeyModifiers)
} else {
w.mouseMove(where, w.lastKeyModifiers)
}
})
w.wnd.SetCursorEnterCallback(func(_ *glfw.Window, entered bool) {
if entered {
w.mouseEnter(w.MouseLocation(), w.lastKeyModifiers)
} else {
w.mouseExit()
}
})
w.wnd.SetScrollCallback(func(_ *glfw.Window, xoff, yoff float64) {
w.mouseWheel(w.MouseLocation(), Point{X: float32(xoff), Y: float32(yoff)}, w.lastKeyModifiers)
})
w.wnd.SetKeyCallback(w.keyCallbackForGLFW)
w.wnd.SetCharCallback(func(_ *glfw.Window, ch rune) {
if w.okToProcess() {
w.runeTyped(ch)
}
})
// Real drag & drop support can't really be added due to the way glfw has already hooked in for their primitive
// file drop capability... so we'll just live with that for now.
w.wnd.SetDropCallback(func(_ *glfw.Window, files []string) {
if w.okToProcess() {
w.fileDrop(files)
}
})
w.valid = true
windowList = append(windowList, w)
windowMap[w.wnd] = w
w.root = newRootPanel(w)
w.ValidateLayout()
w.SetTitleIcons(w.titleIcons)
return w, nil
}
func (w *Window) commonKeyCallbackForGLFW(key glfw.Key, action glfw.Action, mods glfw.ModifierKey) {
w.lastKeyModifiers = Modifiers(mods)
switch action {
case glfw.Press:
w.keyDown(KeyCode(key), Modifiers(mods), false)
case glfw.Release:
w.keyUp(KeyCode(key), Modifiers(mods))
case glfw.Repeat:
w.keyDown(KeyCode(key), Modifiers(mods), true)
}
}
// LastKeyModifiers returns the last set of key modifiers that this window has received.
func (w *Window) LastKeyModifiers() Modifiers {
return w.lastKeyModifiers
}
func glfwEnabled(enabled bool) int {
if enabled {
return glfw.True
}
return glfw.False
}
func (w *Window) mouseButtonCallback(_ *glfw.Window, button glfw.MouseButton, action glfw.Action, mods glfw.ModifierKey) {
if !w.okToProcess() {
modalStack[len(modalStack)-1].mouseButtonCallback(nil, button, action, mods)
return
}
w.lastKeyModifiers = Modifiers(mods)
where := w.MouseLocation()
if action == glfw.Press {
maxDelay, maxMouseDrift := DoubleClickParameters()
now := time.Now()
if int(button) == w.lastButton && time.Since(w.lastButtonTime) <= maxDelay &&
xmath.Abs(where.X-w.firstButtonLocation.X) <= maxMouseDrift &&
xmath.Abs(where.Y-w.firstButtonLocation.Y) <= maxMouseDrift {
w.lastButtonCount++
time.Since(w.lastButtonTime)
} else {
w.lastButtonCount = 1
w.firstButtonLocation = where
}
w.lastButton = int(button)
w.lastButtonTime = now
w.inMouseDown = true
w.mouseDown(where, w.lastButton, w.lastButtonCount, w.lastKeyModifiers)
} else if w.inMouseDown {
w.lastButton = int(button)
w.inMouseDown = false
w.mouseUp(where, w.lastButton, w.lastKeyModifiers)
}
}
func (w *Window) okToProcess() bool {
return len(modalStack) == 0 || modalStack[len(modalStack)-1] == w
}
// UndoManager returns the UndoManager for the currently focused panel in the Window. May return nil.
func (w *Window) UndoManager() *UndoManager {
if focus := w.Focus(); focus != nil {
return UndoManagerFor(focus)
}
return nil
}
func (w *Window) moved() {
w.lastContentRect = w.ContentRect()
w.root.preMoved(w)
if w.MovedCallback != nil {
toolbox.Call(w.MovedCallback)
}
}
func (w *Window) resized() {
current := w.ContentRect()
adjusted := w.adjustContentRectForMinMax(current)
if adjusted != current {
w.SetContentRect(adjusted)
}
w.ValidateLayout()
if w.ResizedCallback != nil {
toolbox.Call(func() { w.ResizedCallback() })
}
}
func (w *Window) gainedFocus() {
w.focused = true
if len(windowList) != 0 && windowList[0] != w {
w.removeFromWindowList()
windowList = append(windowList, nil)
copy(windowList[1:], windowList)
windowList[0] = w
}
w.ClearTooltip()
if w.focus == nil {
w.FocusNext()
}
if w.focus != nil {
w.focus.MarkForRedraw()
}
if w.GainedFocusCallback != nil {
w.GainedFocusCallback()
}
w.mouseEnter(w.MouseLocation(), 0)
}
func (w *Window) lostFocus() {
w.restoreHiddenCursor()
w.focused = false
w.ClearTooltip()
if w.focus != nil {
w.focus.MarkForRedraw()
}
if w.LostFocusCallback != nil {
w.LostFocusCallback()
}
if w.root.menuBar != nil {
w.root.menuBar.postLostFocus(w)
}
}
// RunModal displays and brings this window to the front, the runs a modal event loop until StopModal is called.
// Disposes the window before it returns.
func (w *Window) RunModal() int {
active := ActiveWindow()
if active != nil {
active.restoreHiddenCursor()
}
defer func() {
w.removeFromModalStack()
w.Dispose()
if active != nil && active.IsVisible() {
active.ToFront()
}
}()
w.modalResultCode = ModalResponseDiscard
w.inModal = true
modalStack = append(modalStack, w)
w.ToFront()
for w.inModal {
processEvents()
}
return w.modalResultCode
}
// StopModal stops the current modal event loop and propagates the provided code as the result to RunModal().
func (w *Window) StopModal(code int) {
w.modalResultCode = code
w.removeFromModalStack()
}
func (w *Window) removeFromModalStack() {
w.inModal = false
for i, wnd := range modalStack {
if w != wnd {
continue
}
modalStack = slices.Delete(modalStack, i, i+1)
break
}
}
// IsValid returns true if the window is still valid (i.e. hasn't been disposed).
func (w *Window) IsValid() bool {
return w != nil && w.valid
}
func (w *Window) String() string {
return fmt.Sprintf("Window[%s]", w.title)
}
// AttemptClose closes the window if permitted. Returns true on success.
func (w *Window) AttemptClose() bool {
if w.AllowCloseCallback != nil {
allow := false
toolbox.Call(func() { allow = w.AllowCloseCallback() })
if !allow {
return false
}
}
w.Dispose()
return true
}
func (w *Window) removeFromWindowList() {
for i, wnd := range windowList {
if w != wnd {
continue
}
windowList = slices.Delete(windowList, i, i+1)
break
}
}
// Dispose of the window.
func (w *Window) Dispose() {
active := ActiveWindow()
if w.WillCloseCallback != nil {
toolbox.Call(w.WillCloseCallback)
w.WillCloseCallback = nil
}
if w.inModal {
w.StopModal(ModalResponseDiscard)
}
if w.root.contentPanel != nil {
w.root.contentPanel.RemoveFromParent()
}
w.removeFromWindowList()
delete(windowMap, w.wnd)
if w.IsValid() {
w.valid = false
w.surface.dispose()
w.wnd.Destroy()
w.wnd = nil
}
if len(windowMap) == 0 && quitAfterLastWindowClosed() {
quitting()
}
if active != nil && active == w && len(windowList) != 0 {
windowList[0].ToFront()
}
}
// Title returns the title of this window.
func (w *Window) Title() string {
return w.title
}
// SetTitle sets the title of this window.
func (w *Window) SetTitle(title string) {
if w.title != title {
w.title = title
if w.IsValid() {
w.wnd.SetTitle(title)
}
}
}
// TitleIcons the title icons that were previously set, if any.
func (w *Window) TitleIcons() []*Image {
return w.titleIcons
}
// SetTitleIcons sets the title icon of the window. The image closest to the size desired by the system will be selected
// and used, scaling if needed. If no images are specified, the window reverts to its default icon.
func (w *Window) SetTitleIcons(images []*Image) {
w.titleIcons = images
imgs := make([]image.Image, 0, len(images))
for _, img := range images {
if nrgba, err := img.ToNRGBA(); err != nil {
errs.Log(err)
} else {
w.titleIcons = append(w.titleIcons, img)
imgs = append(imgs, nrgba)
}
}
if w.IsValid() {
w.wnd.SetIcon(imgs)
}
}
// Content returns the content panel for the window.
func (w *Window) Content() *Panel {
return w.root.contentPanel
}
// SetContent sets the content panel for the window.
func (w *Window) SetContent(panel Paneler) {
w.root.setContent(panel)
w.ValidateLayout()
w.MarkForRedraw()
}
// ValidateLayout performs any layout that needs to be run by this window or its children.
func (w *Window) ValidateLayout() {
rect := w.ContentRect()
rect.X = 0
rect.Y = 0
w.root.SetFrameRect(rect)
w.root.ValidateLayout()
}
// FrameRect returns the boundaries in display coordinates of the frame of this window (i.e. the area that includes both
// the content and its border and window controls).
func (w *Window) FrameRect() Rect {
fr := w.frameRect()
cr := w.ContentRect()
cr.X -= fr.X
cr.Y -= fr.Y
cr.Width += fr.Width
cr.Height += fr.Height
return cr
}
// ContentRectForFrameRect returns the content rect for the given frame rect.
func (w *Window) ContentRectForFrameRect(frame Rect) Rect {
fr := w.frameRect()
frame.X += fr.X
frame.Y += fr.Y
frame.Width -= fr.Width
frame.Height -= fr.Height
return frame
}
// FrameRectForContentRect returns the frame rect for the given content rect.
func (w *Window) FrameRectForContentRect(cr Rect) Rect {
fr := w.frameRect()
cr.X -= fr.X
cr.Y -= fr.Y
cr.Width += fr.Width
cr.Height += fr.Height
return cr
}
// SetFrameRect sets the boundaries of the frame of this window.
func (w *Window) SetFrameRect(rect Rect) {
w.SetContentRect(w.ContentRectForFrameRect(rect))
}
func (w *Window) minMaxContentSize() (minimum, maximum Size) {
if w.MinMaxContentSizeCallback != nil {
return w.MinMaxContentSizeCallback()
}
minimum, _, maximum = w.root.Sizes(Size{})
return
}
func (w *Window) adjustContentRectForMinMax(rect Rect) Rect {
minimum, maximum := w.minMaxContentSize()
if rect.Width < minimum.Width {
rect.Width = minimum.Width
} else if rect.Width > maximum.Width {
rect.Width = maximum.Width
}
if rect.Height < minimum.Height {
rect.Height = minimum.Height
} else if rect.Height > maximum.Height {
rect.Height = maximum.Height
}
w.lastContentRect = rect
return rect
}
// LocalContentRect returns the boundaries in local coordinates of the window's content area.
func (w *Window) LocalContentRect() Rect {
r := w.ContentRect()
r.Point.X = 0
r.Point.Y = 0
return r
}
// Pack sets the window's content size to match the preferred size of the root panel.
func (w *Window) Pack() {
_, pref, _ := w.root.Sizes(Size{})
rect := w.ContentRect()
rect.Size = pref
w.SetContentRect(BestDisplayForRect(rect).FitRectOnto(rect))
}
// Focused returns true if the window has the current keyboard focus.
func (w *Window) Focused() bool {
return w.focused
}
// Focus returns the panel with the keyboard focus in this window.
func (w *Window) Focus() *Panel {
if w == nil {
return nil
}
if w.focus == nil || w.focus.Window() != w {
w.FocusNext()
}
return w.focus
}
// SetFocus sets the keyboard focus to the specified target.
func (w *Window) SetFocus(target Paneler) {
var newFocus *Panel
if target != nil {
newFocus = target.AsPanel()
}
oldFocus := w.focus
if newFocus == nil {
w.removeFocus()
return
}
if newFocus.Window() == w {
if !newFocus.Focusable() {
if newFocus = newFocus.FirstFocusableChild(); newFocus == nil {
w.removeFocus()
return
}
}
if !newFocus.Is(w.focus) {
if w.focus != nil {
if oldFocus.LostFocusCallback != nil {
toolbox.Call(oldFocus.LostFocusCallback)
}
}
w.focus = newFocus
if newFocus != nil {
if newFocus.GainedFocusCallback != nil {
toolbox.Call(newFocus.GainedFocusCallback)
}
}
w.notifyOfFocusChangeInHierarchy(oldFocus, newFocus)
}
}
}
func (w *Window) removeFocus() {
oldFocus := w.focus
if oldFocus != nil {
if oldFocus.LostFocusCallback != nil {
toolbox.Call(oldFocus.LostFocusCallback)
}
w.focus = nil
w.notifyOfFocusChangeInHierarchy(oldFocus, nil)
}
}
func (w *Window) notifyOfFocusChangeInHierarchy(oldFocus, newFocus *Panel) {
for _, p := range []*Panel{oldFocus, newFocus} {
if p != nil {
p = p.Parent()
for p != nil {
if p.FocusChangeInHierarchyCallback != nil {
toolbox.Call(func() { p.FocusChangeInHierarchyCallback(oldFocus, newFocus) })
}
p = p.Parent()
}
}
}
}
// FocusNext moves the keyboard focus to the next focusable panel.
func (w *Window) FocusNext() {
if w.root.contentPanel != nil {
current := w.focus
if current == nil {
current = w.root.contentPanel
}
i, focusables := collectFocusables(w.root.contentPanel, current, nil)
if len(focusables) > 0 {
i++
if i >= len(focusables) {
i = 0
}
current = focusables[i]
}
w.SetFocus(current)
}
}
// FocusPrevious moves the keyboard focus to the previous focusable panel.
func (w *Window) FocusPrevious() {
if w.root.contentPanel != nil {
current := w.focus
if current == nil {
current = w.root.contentPanel
}
i, focusables := collectFocusables(w.root.contentPanel, current, nil)
if len(focusables) > 0 {
i--
if i < 0 {
i = len(focusables) - 1
}
current = focusables[i]
}
w.SetFocus(current)
}
}
func collectFocusables(current, target *Panel, focusables []*Panel) (match int, result []*Panel) {
match = -1
if current.Focusable() {
if current.Is(target) {
match = len(focusables)
}
focusables = append(focusables, current)
}
for _, child := range current.Children() {
var m int
m, focusables = collectFocusables(child, target, focusables)
if match == -1 && m != -1 {
match = m
}
}
return match, focusables
}
// IsVisible returns true if the window is currently being shown.
func (w *Window) IsVisible() bool {
if w.IsValid() {
return w.wnd.GetAttrib(glfw.Visible) == glfw.True
}
return false
}
// Show makes the window visible, if it was previously hidden. If the window is already visible or is in full screen
// mode, this function does nothing.
func (w *Window) Show() {
if w.IsValid() {
w.wnd.Show()
// For some reason, Linux is ignoring some window positioning calls prior to showing, so immediately reissue the
// last one we had.
w.SetContentRect(w.lastContentRect)
}
}
// Hide hides the window, if it was previously visible. If the window is already hidden or is in full screen mode, this
// function does nothing.
func (w *Window) Hide() {
if w.IsValid() {
w.wnd.Hide()
}
}
// ToFront attempts to bring the window to the foreground and give it the keyboard focus. If it is hidden, it will be
// made visible first.
func (w *Window) ToFront() {
if w.IsValid() {
w.Show()
w.focused = true // Don't wait for the focus event to set this, as Linux delays the notification too much
w.wnd.Focus()
}
}
// Minimize performs the minimize function on the window.
func (w *Window) Minimize() {
if w.IsValid() {
w.wnd.Iconify()
}
}
// Zoom performs the zoom function on the window.
func (w *Window) Zoom() {
if w.IsValid() {
w.wnd.Maximize()
}
}
// Resizable returns true if the window can be resized by the user.
func (w *Window) Resizable() bool {
return !w.notResizable
}
// MouseLocation returns the current mouse location relative to this window.
func (w *Window) MouseLocation() Point {
if w.IsValid() {
return w.convertMouseLocation(w.wnd.GetCursorPos())
}
return Point{}
}
// BackingScale returns the scale of the backing store for this window.
func (w *Window) BackingScale() (x, y float32) {
if w.IsValid() {
return w.wnd.GetContentScale()
}
return 1, 1
}
// Draw the window contents.
func (w *Window) Draw(c *Canvas) {
if w.root != nil {
toolbox.Call(func() {
w.root.ValidateLayout()
c.DrawPaint(BackgroundColor.Paint(c, w.LocalContentRect(), paintstyle.Fill))
w.root.Draw(c, w.LocalContentRect())
if w.InDrag() {
c.Save()
c.Translate(w.dragDataLocation.X+w.dragData.Offset.X, w.dragDataLocation.Y+w.dragData.Offset.Y)
r := Rect{Size: w.dragData.Drawable.LogicalSize()}
c.ClipRect(r, pathop.Intersect, false)
w.dragData.Drawable.DrawInRect(c, r, w.dragData.SamplingOptions,
w.dragData.Ink.Paint(c, r, paintstyle.Fill))
c.Restore()
}
})
}
}
func (w *Window) draw() {
RebuildDynamicColors()
if w.IsValid() {
sx, sy := w.BackingScale()
w.wnd.MakeContextCurrent()
if !glInited {
fatal.IfErr(gl.Init())
glInited = true
}
c, err := w.surface.prepareCanvas(w.ContentRect().Size, w.LocalContentRect(), sx, sy)
if err != nil {
errs.Log(err, "size", w.ContentRect().Size, "rect", w.LocalContentRect(), "scaleX", sx, "scaleY", sy)
return
}
start := time.Now()
c.Save()
w.Draw(c)
c.Restore()
c.Flush()
w.lastDrawDuration = time.Since(start)
w.wnd.SwapBuffers()
}
}
// LastDrawDuration returns the duration of the window's most recent draw.
func (w *Window) LastDrawDuration() time.Duration {
return w.lastDrawDuration
}
// MarkForRedraw marks this window for drawing at the next update.
func (w *Window) MarkForRedraw() {
if _, exists := redrawSet[w]; !exists {
redrawSet[w] = struct{}{}
if len(redrawSet) == 1 {
postEmptyEvent()
}
}
}
// FlushDrawing causes any areas marked for drawing to be drawn now.
func (w *Window) FlushDrawing() {
if _, exists := redrawSet[w]; exists {
w.draw()
}
}
// HideCursor hides the cursor.
func (w *Window) HideCursor() {
if w.IsValid() {
w.wnd.SetInputMode(glfw.CursorMode, glfw.CursorHidden)
}
}
// ShowCursor shows the cursor.
func (w *Window) ShowCursor() {
if w.IsValid() {
w.wnd.SetInputMode(glfw.CursorMode, glfw.CursorNormal)
}
}
// HideCursorUntilMouseMoves hides the cursor until the mouse is moved.
func (w *Window) HideCursorUntilMouseMoves() {
if !w.cursorHidden {
w.cursorHidden = true
w.HideCursor()
}
}
func (w *Window) restoreHiddenCursor() {
if w.cursorHidden {
w.cursorHidden = false
w.ShowCursor()
}
}
func (w *Window) updateTooltipAndCursor(target *Panel, where Point) {
w.updateCursor(target, where)
w.updateTooltip(target, where)
}
func (w *Window) updateTooltip(target *Panel, where Point) {
var avoid Rect
var tip *Panel
for target != nil {
avoid = target.RectToRoot(target.ContentRect(true))
avoid.Align()
if target.UpdateTooltipCallback != nil {
toolbox.Call(func() { avoid = target.UpdateTooltipCallback(target.PointFromRoot(where), avoid) })
}
if target.Tooltip != nil {
tip = target.Tooltip
tip.TooltipImmediate = target.TooltipImmediate
break
}
target = target.parent
}
if !w.lastTooltip.Is(tip) {
wasShowing := w.root.tooltipPanel != nil
w.ClearTooltip()
w.lastTooltip = tip
if tip != nil {
ts := &tooltipSequencer{window: w, avoid: avoid, sequence: w.tooltipSequence}
if tip.TooltipImmediate || wasShowing || time.Since(w.lastTooltipShownAt) < DefaultTooltipTheme.Dismissal {
ts.show()
} else {
InvokeTaskAfter(ts.show, DefaultTooltipTheme.Delay)
}
}
}
}
// ClearTooltip clears any existing tooltip and resets the timer.
func (w *Window) ClearTooltip() {
w.tooltipSequence++
w.lastTooltipShownAt = time.Time{}
w.root.setTooltip(nil)
}
// UpdateCursorNow causes the cursor to be updated as if the mouse had moved.
func (w *Window) UpdateCursorNow() {
where := w.MouseLocation()
target := w.root.PanelAt(where)
w.updateCursor(target, target.PointFromRoot(where))
}