forked from mmp/vice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathui.go
1246 lines (1065 loc) · 31.4 KB
/
ui.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
// ui.go
// Copyright(c) 2022 Matt Pharr, licensed under the GNU Public License, Version 3.
// SPDX: GPL-3.0-only
package main
import (
"bytes"
_ "embed"
"encoding/json"
"fmt"
"image/png"
"net/http"
"os"
"path"
"runtime/debug"
"sort"
"strings"
"time"
"unicode"
"github.com/mmp/imgui-go/v4"
"github.com/pkg/browser"
)
var (
ui struct {
font *Font
aboutFont *Font
menuBarHeight float32
showAboutDialog bool
iconTextureID uint32
sadTowerTextureID uint32
jsonSelectDialog *FileSelectDialogBox
activeModalDialogs []*ModalDialogBox
newReleaseDialogChan chan *NewReleaseModalClient
}
//go:embed icons/tower-256x256.png
iconPNG string
//go:embed icons/sad-tower-alpha-128x128.png
sadTowerPNG string
whatsNew []string = []string{
"Added EWR scenarios, including both departure and approach.",
"Added Liberty departure scenarios.",
"Improved routing of departures beyond their exit fix.",
"Fixed a bug where aircraft on RNAV arrivals wouldn't descend.",
"Each scenario has a default video map, selected automatically.",
"If an aircraft given approach clearance is later vectored, approach clearance is now canceled.",
"Improved spawn positions and hand-off locations for JFK arrivals.",
"Added F11 TRACON scenarios (KMCO, KSFB, KISM, KORL...)",
"Font sizes for UI elements can now be set in the settings window",
"Fixed a crash related to handing off aircraft",
"Added go arounds",
"Added ABE TRACON scenarios",
}
)
var UIControlColor RGB = RGB{R: 0.2754237, G: 0.2754237, B: 0.2754237}
var UICautionColor RGB = RGBFromHex(0xB7B513)
var UITextColor RGB = RGB{R: 0.85, G: 0.85, B: 0.85}
var UITextHighlightColor RGB = RGBFromHex(0xB2B338)
var UIErrorColor RGB = RGBFromHex(0xE94242)
func imguiInit() *imgui.Context {
context := imgui.CreateContext(nil)
imgui.CurrentIO().SetIniFilename("")
// General imgui styling
style := imgui.CurrentStyle()
style.SetFrameRounding(2.)
style.SetWindowRounding(4.)
style.SetPopupRounding(4.)
style.SetScrollbarSize(6.)
style.ScaleAllSizes(1.25)
return context
}
func uiInit(renderer Renderer) {
ui.font = GetFont(FontIdentifier{Name: "Roboto Regular", Size: globalConfig.UIFontSize})
ui.aboutFont = GetFont(FontIdentifier{Name: "Roboto Regular", Size: 18})
if iconImage, err := png.Decode(bytes.NewReader([]byte(iconPNG))); err != nil {
lg.Errorf("Unable to decode icon PNG: %v", err)
} else {
ui.iconTextureID = renderer.CreateTextureFromImage(iconImage)
}
if sadTowerImage, err := png.Decode(bytes.NewReader([]byte(sadTowerPNG))); err != nil {
lg.Errorf("Unable to decode sad tower PNG: %v", err)
} else {
ui.sadTowerTextureID = renderer.CreateTextureFromImage(sadTowerImage)
}
// Do this asynchronously since it involves network traffic and may
// take some time (or may even time out, etc.)
ui.newReleaseDialogChan = make(chan *NewReleaseModalClient)
go checkForNewRelease(ui.newReleaseDialogChan)
if globalConfig.WhatsNewIndex < len(whatsNew) {
uiShowModalDialog(NewModalDialogBox(&WhatsNewModalClient{}), false)
}
uiShowModalDialog(NewModalDialogBox(&ConnectModalClient{}), false)
}
func uiShowModalDialog(d *ModalDialogBox, atFront bool) {
if atFront {
ui.activeModalDialogs = append([]*ModalDialogBox{d}, ui.activeModalDialogs...)
} else {
ui.activeModalDialogs = append(ui.activeModalDialogs, d)
}
}
// If |b| is true, all following imgui elements will be disabled (and drawn
// accordingly).
func uiStartDisable(b bool) {
if b {
imgui.PushItemFlag(imgui.ItemFlagsDisabled, true)
imgui.PushStyleVarFloat(imgui.StyleVarAlpha, imgui.CurrentStyle().Alpha()*0.5)
}
}
// Each call to uiStartDisable should have a matching call to uiEndDisable,
// with the same Boolean value passed to it.
func uiEndDisable(b bool) {
if b {
imgui.PopItemFlag()
imgui.PopStyleVar()
}
}
func (c RGB) imgui() imgui.Vec4 {
return imgui.Vec4{c.R, c.G, c.B, 1}
}
func drawUI(platform Platform) {
if ui.newReleaseDialogChan != nil {
select {
case dialog, ok := <-ui.newReleaseDialogChan:
if ok {
uiShowModalDialog(NewModalDialogBox(dialog), false)
} else {
// channel was closed
ui.newReleaseDialogChan = nil
}
default:
// don't block on the chan if there's nothing there and it's still open...
}
}
imgui.PushFont(ui.font.ifont)
if imgui.BeginMainMenuBar() {
if imgui.BeginMenu("Simulation") {
if sim.Paused() {
if imgui.MenuItem("Resume") {
sim.TogglePause()
}
} else {
if imgui.MenuItem("Pause") {
sim.TogglePause()
}
}
if imgui.MenuItem("Restart...") {
uiShowModalDialog(NewModalDialogBox(&ConnectModalClient{}), false)
}
imgui.Separator()
if imgui.MenuItem("Settings...") {
sim.ActivateSettingsWindow()
}
imgui.EndMenu()
}
if imgui.BeginMenu("Help") {
if imgui.MenuItem("Documentation...") {
browser.OpenURL("https://pharr.org/vice/index.html")
}
if imgui.MenuItem("Report a bug...") {
browser.OpenURL("https://pharr.org/vice/index.html#bugs")
}
imgui.Separator()
if imgui.MenuItem("About vice...") {
ui.showAboutDialog = true
}
imgui.EndMenu()
}
t := FontAwesomeIconDiscord
width, _ := ui.font.BoundText(t, 0)
imgui.SetCursorPos(imgui.Vec2{platform.DisplaySize()[0] - float32(width+10), 0})
imgui.PushStyleColor(imgui.StyleColorButton, imgui.CurrentStyle().Color(imgui.StyleColorMenuBarBg))
if imgui.Button(t) {
browser.OpenURL("https://discord.gg/y993vgQxhY")
}
imgui.PopStyleColor()
imgui.EndMainMenuBar()
}
ui.menuBarHeight = imgui.CursorPos().Y - 1
sim.DrawSettingsWindow()
drawActiveDialogBoxes()
wmDrawUI(platform)
imgui.PopFont()
// Finalize and submit the imgui draw lists
imgui.Render()
cb := GetCommandBuffer()
defer ReturnCommandBuffer(cb)
GenerateImguiCommandBuffer(cb)
stats.renderUI = renderer.RenderCommandBuffer(cb)
}
func drawActiveDialogBoxes() {
for len(ui.activeModalDialogs) > 0 {
d := ui.activeModalDialogs[0]
if !d.closed {
d.Draw()
break
} else {
ui.activeModalDialogs = ui.activeModalDialogs[1:]
}
}
if ui.showAboutDialog {
showAboutDialog()
}
}
func setCursorForRightButtons(text []string) {
style := imgui.CurrentStyle()
width := float32(0)
for i, t := range text {
width += imgui.CalcTextSize(t, false, 100000).X + 2*style.FramePadding().X
if i > 0 {
// space between buttons
width += style.ItemSpacing().X
}
}
offset := imgui.ContentRegionAvail().X - width
imgui.SetCursorPos(imgui.Vec2{offset, imgui.CursorPosY()})
}
///////////////////////////////////////////////////////////////////////////
func drawAirportSelector(airports map[string]interface{}, title string) (map[string]interface{}, bool) {
airportsString := strings.Join(SortedMapKeys(airports), ",")
if imgui.InputTextV(title, &airportsString, imgui.InputTextFlagsCharsUppercase, nil) {
ap := strings.FieldsFunc(airportsString, func(ch rune) bool {
return unicode.IsSpace(ch) || ch == ','
})
airports = make(map[string]interface{})
for _, a := range ap {
airports[a] = nil
}
return airports, true
}
return airports, false
}
///////////////////////////////////////////////////////////////////////////
type ComboBoxState struct {
inputValues []*string
selected map[string]interface{}
lastSelected *string
}
func NewComboBoxState(nentry int) *ComboBoxState {
s := &ComboBoxState{}
for i := 0; i < nentry; i++ {
s.inputValues = append(s.inputValues, new(string))
}
s.selected = make(map[string]interface{})
s.lastSelected = new(string)
return s
}
type ComboBoxDisplayConfig struct {
ColumnHeaders []string
DrawHeaders bool
EntryNames []string
InputFlags []imgui.InputTextFlags
SelectAllColumns bool
Size imgui.Vec2
MaxDisplayed int
FixedDisplayed int
}
func DrawComboBox(state *ComboBoxState, config ComboBoxDisplayConfig,
firstColumn []string, drawColumn func(s string, col int),
inputValid func([]*string) bool, add func([]*string), deleteSelection func(map[string]interface{})) {
id := fmt.Sprintf("%p", state)
flags := imgui.TableFlagsBordersH | imgui.TableFlagsBordersOuterV | imgui.TableFlagsRowBg
sz := config.Size
if config.FixedDisplayed != 0 {
flags = flags | imgui.TableFlagsScrollY
sz.Y = float32(config.FixedDisplayed * (4 + ui.font.size))
} else if config.MaxDisplayed == 0 || len(firstColumn) < config.MaxDisplayed {
sz.Y = 0
} else {
flags = flags | imgui.TableFlagsScrollY
sz.Y = float32((1 + config.MaxDisplayed) * (6 + ui.font.size))
}
if imgui.BeginTableV("##"+id, len(config.ColumnHeaders), flags, sz, 0.0) {
for _, name := range config.ColumnHeaders {
imgui.TableSetupColumn(name)
}
if config.DrawHeaders {
imgui.TableHeadersRow()
}
io := imgui.CurrentIO()
for _, entry := range firstColumn {
imgui.TableNextRow()
imgui.TableNextColumn()
_, isSelected := state.selected[entry]
var selFlags imgui.SelectableFlags
if config.SelectAllColumns {
selFlags = imgui.SelectableFlagsSpanAllColumns
}
if imgui.SelectableV(entry, isSelected, selFlags, imgui.Vec2{}) {
if io.KeyCtrlPressed() {
// Toggle selection of this one
if isSelected {
delete(state.selected, entry)
} else {
state.selected[entry] = nil
*state.lastSelected = entry
}
} else if io.KeyShiftPressed() {
for _, e := range firstColumn {
if entry > *state.lastSelected {
if e > *state.lastSelected && e <= entry {
state.selected[e] = nil
}
} else {
if e >= entry && e <= *state.lastSelected {
state.selected[e] = nil
}
}
}
*state.lastSelected = entry
} else {
// Select only this one
for k := range state.selected {
delete(state.selected, k)
}
state.selected[entry] = nil
*state.lastSelected = entry
}
}
for i := 1; i < len(config.ColumnHeaders); i++ {
imgui.TableNextColumn()
drawColumn(entry, i)
}
}
imgui.EndTable()
}
valid := inputValid(state.inputValues)
for i, entry := range config.EntryNames {
flags := imgui.InputTextFlagsEnterReturnsTrue
if config.InputFlags != nil {
flags |= config.InputFlags[i]
}
if imgui.InputTextV(entry+"##"+id, state.inputValues[i], flags, nil) && valid {
add(state.inputValues)
for _, s := range state.inputValues {
*s = ""
}
imgui.SetKeyboardFocusHereV(-1)
}
}
uiStartDisable(!valid)
imgui.SameLine()
if imgui.Button("+##" + id) {
add(state.inputValues)
for _, s := range state.inputValues {
*s = ""
}
}
uiEndDisable(!valid)
enableDelete := len(state.selected) > 0
uiStartDisable(!enableDelete)
imgui.SameLine()
if imgui.Button(FontAwesomeIconTrash + "##" + id) {
deleteSelection(state.selected)
for k := range state.selected {
delete(state.selected, k)
}
}
uiEndDisable(!enableDelete)
}
///////////////////////////////////////////////////////////////////////////
type ModalDialogBox struct {
closed, isOpen bool
client ModalDialogClient
}
type ModalDialogButton struct {
text string
disabled bool
action func() bool
}
type ModalDialogClient interface {
Title() string
Opening()
Buttons() []ModalDialogButton
Draw() int /* returns index of equivalently-clicked button; out of range if none */
}
func NewModalDialogBox(c ModalDialogClient) *ModalDialogBox {
return &ModalDialogBox{client: c}
}
func (m *ModalDialogBox) Draw() {
if m.closed {
return
}
title := fmt.Sprintf("%s##%p", m.client.Title(), m)
if !m.isOpen {
imgui.OpenPopup(title)
}
flags := imgui.WindowFlagsNoResize | imgui.WindowFlagsAlwaysAutoResize | imgui.WindowFlagsNoSavedSettings
if imgui.BeginPopupModalV(title, nil, flags) {
if !m.isOpen {
imgui.SetKeyboardFocusHere()
m.client.Opening()
m.isOpen = true
}
selIndex := m.client.Draw()
imgui.Text("\n") // spacing
buttons := m.client.Buttons()
// First, figure out where to start drawing so the buttons end up right-justified.
// https://github.com/ocornut/imgui/discussions/3862
var allButtonText []string
for _, b := range buttons {
allButtonText = append(allButtonText, b.text)
}
setCursorForRightButtons(allButtonText)
for i, b := range buttons {
uiStartDisable(b.disabled)
if i > 0 {
imgui.SameLine()
}
if (imgui.Button(b.text) || i == selIndex) && !b.disabled {
if b.action == nil || b.action() {
imgui.CloseCurrentPopup()
m.closed = true
m.isOpen = false
}
}
uiEndDisable(b.disabled)
}
imgui.EndPopup()
}
}
type ConnectModalClient struct {
connectionType ConnectionType
err string
sim SimConnectionConfiguration
}
type ConnectionType int
const (
ConnectionTypeSimServer = iota
ConnectionTypeCount
)
func (c ConnectionType) String() string {
return [...]string{"Sim Server"}[c]
}
func (c *ConnectModalClient) Title() string { return "New Simulation" }
func (c *ConnectModalClient) Opening() {
c.connectionType = ConnectionTypeSimServer
c.err = ""
c.sim.Initialize()
}
func (c *ConnectModalClient) Buttons() []ModalDialogButton {
var b []ModalDialogButton
b = append(b, ModalDialogButton{text: "Cancel"})
ok := ModalDialogButton{text: "Ok", action: func() bool {
var err error
switch c.connectionType {
case ConnectionTypeSimServer:
err = c.sim.Connect()
default:
lg.Errorf("Unhandled connection type")
return true
}
if err == nil {
c.err = ""
} else {
c.err = err.Error()
}
return err == nil
}}
switch c.connectionType {
case ConnectionTypeSimServer:
ok.disabled = !c.sim.Valid()
default:
lg.Errorf("Unhandled connection type")
}
b = append(b, ok)
return b
}
func (c *ConnectModalClient) Draw() int {
/*
if imgui.BeginComboV("Type", c.connectionType.String(), imgui.ComboFlagsHeightLarge) {
for i := 0; i < ConnectionTypeCount; i++ {
ct := ConnectionType(i)
if imgui.SelectableV(ct.String(), ct == c.connectionType, 0, imgui.Vec2{}) {
c.connectionType = ct
}
}
imgui.EndCombo()
}
*/
var enter bool
switch c.connectionType {
case ConnectionTypeSimServer:
enter = c.sim.DrawUI()
}
if c.err != "" {
imgui.Text(c.err)
}
if enter {
return 1
} else {
return -1
}
}
type DisconnectModalClient struct{}
func (d *DisconnectModalClient) Title() string { return "Confirm Disconnection" }
func (d *DisconnectModalClient) Opening() {
}
func (c *DisconnectModalClient) Buttons() []ModalDialogButton {
var b []ModalDialogButton
b = append(b, ModalDialogButton{text: "Cancel"})
ok := ModalDialogButton{text: "Ok", action: func() bool {
sim.Disconnect()
return true
}}
b = append(b, ok)
return b
}
func (d *DisconnectModalClient) Draw() int {
imgui.Text("Are you sure you want to disconnect?")
return -1
}
type YesOrNoModalClient struct {
title, query string
ok, notok func()
}
func (yn *YesOrNoModalClient) Title() string { return yn.title }
func (yn *YesOrNoModalClient) Opening() {}
func (yn *YesOrNoModalClient) Buttons() []ModalDialogButton {
var b []ModalDialogButton
b = append(b, ModalDialogButton{text: "No", action: func() bool {
if yn.notok != nil {
yn.notok()
}
return true
}})
b = append(b, ModalDialogButton{text: "Yes", action: func() bool {
if yn.ok != nil {
yn.ok()
}
return true
}})
return b
}
func (yn *YesOrNoModalClient) Draw() int {
imgui.Text(yn.query)
return -1
}
func checkForNewRelease(newReleaseDialogChan chan *NewReleaseModalClient) {
defer close(newReleaseDialogChan)
url := "https://api.github.com/repos/mmp/vice/releases"
resp, err := http.Get(url)
if err != nil {
lg.Errorf("%s: get err: %v", url, err)
return
}
defer resp.Body.Close()
type Release struct {
TagName string `json:"tag_name"`
Created time.Time `json:"created_at"`
}
decoder := json.NewDecoder(resp.Body)
var releases []Release
if err := decoder.Decode(&releases); err != nil {
lg.Errorf("JSON decode error: %v", err)
return
}
if len(releases) == 0 {
return
}
var newestRelease *Release
for i := range releases {
if strings.HasSuffix(releases[i].TagName, "-beta") {
continue
}
if newestRelease == nil || releases[i].Created.After(newestRelease.Created) {
newestRelease = &releases[i]
}
}
if newestRelease == nil {
lg.Errorf("No vice releases found?")
return
}
lg.Printf("newest release found: %v", newestRelease)
buildTime := ""
if bi, ok := debug.ReadBuildInfo(); !ok {
lg.Errorf("unable to read build info")
return
} else {
for _, setting := range bi.Settings {
if setting.Key == "vcs.time" {
buildTime = setting.Value
break
}
}
if buildTime == "" {
lg.Errorf("build time unavailable in BuildInfo.Settings")
return
}
}
if bt, err := time.Parse(time.RFC3339, buildTime); err != nil {
lg.Errorf("error parsing build time \"%s\": %v", buildTime, err)
} else if newestRelease.Created.UTC().After(bt.UTC()) {
lg.Printf("build time %s newest release %s -> release is newer",
bt.UTC().String(), newestRelease.Created.UTC().String())
newReleaseDialogChan <- &NewReleaseModalClient{
version: newestRelease.TagName,
date: newestRelease.Created}
} else {
lg.Printf("build time %s newest release %s -> build is newer",
bt.UTC().String(), newestRelease.Created.UTC().String())
}
}
type NewReleaseModalClient struct {
version string
date time.Time
}
func (nr *NewReleaseModalClient) Title() string {
return "A new vice release is available"
}
func (nr *NewReleaseModalClient) Opening() {}
func (nr *NewReleaseModalClient) Buttons() []ModalDialogButton {
return []ModalDialogButton{
ModalDialogButton{
text: "Quit and update",
action: func() bool {
browser.OpenURL("https://pharr.org/vice/index.html#section-installation")
os.Exit(0)
return true
},
},
ModalDialogButton{text: "Update later"}}
}
func (nr *NewReleaseModalClient) Draw() int {
imgui.Text(fmt.Sprintf("vice version %s is the latest version", nr.version))
imgui.Text("Would you like to quit and open the vice downloads page?")
return -1
}
type WhatsNewModalClient struct{}
func (nr *WhatsNewModalClient) Title() string {
return "What's new in this version of vice"
}
func (nr *WhatsNewModalClient) Opening() {}
func (nr *WhatsNewModalClient) Buttons() []ModalDialogButton {
return []ModalDialogButton{
ModalDialogButton{
text: "Ok",
action: func() bool {
globalConfig.WhatsNewIndex = len(whatsNew)
return true
},
},
}
}
func (nr *WhatsNewModalClient) Draw() int {
for i := globalConfig.WhatsNewIndex; i < len(whatsNew); i++ {
imgui.Text(FontAwesomeIconSquare + " " + whatsNew[i])
}
return -1
}
///////////////////////////////////////////////////////////////////////////
// "about" dialog box
func showAboutDialog() {
flags := imgui.WindowFlagsNoResize | imgui.WindowFlagsNoSavedSettings
imgui.BeginV("About vice...", &ui.showAboutDialog, flags)
imgui.Image(imgui.TextureID(ui.iconTextureID), imgui.Vec2{256, 256})
center := func(s string) {
// https://stackoverflow.com/a/67855985
ww := imgui.WindowSize().X
tw := imgui.CalcTextSize(s, false, 0).X
imgui.SetCursorPos(imgui.Vec2{(ww - tw) * 0.5, imgui.CursorPosY()})
imgui.Text(s)
}
imgui.PushFont(ui.aboutFont.ifont)
center("vice")
center(FontAwesomeIconCopyright + "2023 Matt Pharr")
center("Licensed under the GPL, Version 3")
if imgui.IsItemHovered() && imgui.IsMouseClicked(0) {
browser.OpenURL("https://www.gnu.org/licenses/gpl-3.0.html")
}
center("Current build: " + buildVersion)
center("Source code: " + FontAwesomeIconGithub)
if imgui.IsItemHovered() && imgui.IsMouseClicked(0) {
browser.OpenURL("https://github.com/mmp/vice")
}
imgui.PopFont()
imgui.End()
}
///////////////////////////////////////////////////////////////////////////
// FileSelectDialogBox
type FileSelectDialogBox struct {
show, isOpen bool
filename string
directory string
dirEntries []DirEntry
dirEntriesLastUpdated time.Time
selectDirectory bool
title string
filter []string
callback func(string)
}
type DirEntry struct {
name string
isDir bool
}
func NewFileSelectDialogBox(title string, filter []string, filename string,
callback func(string)) *FileSelectDialogBox {
return &FileSelectDialogBox{
title: title,
directory: defaultDirectory(filename),
filter: filter,
callback: callback}
}
func NewDirectorySelectDialogBox(title string, current string,
callback func(string)) *FileSelectDialogBox {
fsd := &FileSelectDialogBox{
title: title,
selectDirectory: true,
callback: callback}
if current != "" {
fsd.directory = current
} else {
fsd.directory = defaultDirectory("")
}
return fsd
}
func defaultDirectory(filename string) string {
var dir string
if filename != "" {
dir = path.Dir(filename)
} else {
var err error
if dir, err = os.UserHomeDir(); err != nil {
lg.Errorf("Unable to get user home directory: %v", err)
dir = "."
}
}
return path.Clean(dir)
}
func (fs *FileSelectDialogBox) Activate() {
fs.show = true
fs.isOpen = false
}
func (fs *FileSelectDialogBox) Draw() {
if !fs.show {
return
}
if !fs.isOpen {
imgui.OpenPopup(fs.title)
}
flags := imgui.WindowFlagsNoResize | imgui.WindowFlagsAlwaysAutoResize | imgui.WindowFlagsNoSavedSettings
if imgui.BeginPopupModalV(fs.title, nil, flags) {
if !fs.isOpen {
imgui.SetKeyboardFocusHere()
fs.isOpen = true
}
if imgui.Button(FontAwesomeIconHome) {
var err error
fs.directory, err = os.UserHomeDir()
if err != nil {
lg.Errorf("Unable to get user home dir: %v", err)
fs.directory = "."
}
}
imgui.SameLine()
if imgui.Button(FontAwesomeIconLevelUpAlt) {
fs.directory, _ = path.Split(fs.directory)
fs.directory = path.Clean(fs.directory) // get rid of trailing slash
fs.dirEntriesLastUpdated = time.Time{}
fs.filename = ""
}
imgui.SameLine()
imgui.Text(fs.directory)
// Only rescan the directory contents once a second.
if time.Since(fs.dirEntriesLastUpdated) > 1*time.Second {
if dirEntries, err := os.ReadDir(fs.directory); err != nil {
lg.Errorf("%s: unable to read directory: %v", fs.directory, err)
} else {
fs.dirEntries = nil
for _, entry := range dirEntries {
if entry.Type()&os.ModeSymlink != 0 {
info, err := os.Stat(path.Join(fs.directory, entry.Name()))
if err == nil {
e := DirEntry{name: entry.Name(), isDir: info.IsDir()}
fs.dirEntries = append(fs.dirEntries, e)
} else {
e := DirEntry{name: entry.Name(), isDir: false}
fs.dirEntries = append(fs.dirEntries, e)
}
} else {
e := DirEntry{name: entry.Name(), isDir: entry.IsDir()}
fs.dirEntries = append(fs.dirEntries, e)
}
}
sort.Slice(fs.dirEntries, func(i, j int) bool {
return fs.dirEntries[i].name < fs.dirEntries[j].name
})
}
fs.dirEntriesLastUpdated = time.Now()
}
flags := imgui.TableFlagsScrollY | imgui.TableFlagsRowBg
fileSelected := false
// unique per-directory id maintains the scroll position in each
// directory (and starts newly visited ones at the top!)
if imgui.BeginTableV("Files##"+fs.directory, 1, flags,
imgui.Vec2{500, float32(platform.WindowSize()[1] * 3 / 4)}, 0) {
imgui.TableSetupColumn("Filename")
for _, entry := range fs.dirEntries {
icon := ""
if entry.isDir {
icon = FontAwesomeIconFolder
} else {
icon = FontAwesomeIconFile
}
canSelect := entry.isDir
if !entry.isDir {
if fs.filter == nil && !fs.selectDirectory {
canSelect = true
}
for _, f := range fs.filter {
if strings.HasSuffix(strings.ToUpper(entry.name), strings.ToUpper(f)) {
canSelect = true
break
}
}
}
uiStartDisable(!canSelect)
imgui.TableNextRow()
imgui.TableNextColumn()
selFlags := imgui.SelectableFlagsSpanAllColumns
if imgui.SelectableV(icon+" "+entry.name, entry.name == fs.filename, selFlags, imgui.Vec2{}) {
fs.filename = entry.name
}
if imgui.IsItemHovered() && imgui.IsMouseDoubleClicked(0) {
if entry.isDir {
fs.directory = path.Join(fs.directory, entry.name)
fs.filename = ""
fs.dirEntriesLastUpdated = time.Time{}
} else {
fileSelected = true
}
}
uiEndDisable(!canSelect)
}
imgui.EndTable()
}
if imgui.Button("Cancel") {
imgui.CloseCurrentPopup()
fs.show = false
fs.isOpen = false
fs.filename = ""
}
disableOk := fs.filename == "" && !fs.selectDirectory
uiStartDisable(disableOk)
imgui.SameLine()
if imgui.Button("Ok") || fileSelected {
imgui.CloseCurrentPopup()
fs.show = false
fs.isOpen = false
fs.callback(path.Join(fs.directory, fs.filename))
fs.filename = ""
}
uiEndDisable(disableOk)
imgui.EndPopup()
}
}
type ErrorModalClient struct {