-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathui.go
2021 lines (1743 loc) · 68.6 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-2024 vice contributors, licensed under the GNU Public License, Version 3.
// SPDX: GPL-3.0-only
package main
import (
"bytes"
_ "embed"
"encoding/json"
"fmt"
"image/png"
"log/slog"
"net/http"
"os"
"runtime"
"runtime/debug"
"slices"
"strconv"
"strings"
"time"
av "github.com/mmp/vice/pkg/aviation"
"github.com/mmp/vice/pkg/log"
"github.com/mmp/vice/pkg/math"
"github.com/mmp/vice/pkg/panes"
"github.com/mmp/vice/pkg/platform"
"github.com/mmp/vice/pkg/renderer"
"github.com/mmp/vice/pkg/sim"
"github.com/mmp/vice/pkg/util"
"github.com/mmp/imgui-go/v4"
"github.com/pkg/browser"
)
var (
ui struct {
font *renderer.Font
aboutFont *renderer.Font
aboutFontSmall *renderer.Font
eventsSubscription *sim.EventsSubscription
menuBarHeight float32
showAboutDialog bool
iconTextureID uint32
sadTowerTextureID uint32
activeModalDialogs []*ModalDialogBox
newReleaseDialogChan chan *NewReleaseModalClient
launchControlWindow *LaunchControlWindow
missingPrimaryDialog *ModalDialogBox
// Scenario routes to draw on the scope
showSettings bool
showScenarioInfo bool
showLaunchControl bool
}
//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",
"Added scenarios for KJAX",
"Updated PHL scenarios for recent arrival changes",
"Fixed bug with localizer intercept that made aircraft hang in the air",
"Fixed a few bugs in the KJAX scenario",
"Added ISP and HVN departures and arrivals to the JFK_APP scenario",
"Added LGA departure and arrival scenarios",
"Vice now remembers the active aircraft when you quit and restores the simulation when you launch it again",
"When vice is paused, hovering the mouse on a radar track shows the directions it has been given",
"Fixed a bug where the STARS window wouldn't display anything",
"All new flight modeling engine supports procedure turns and more accurate turns to intercept",
"Updated approaches to include procedure turns, where appropriate",
"Fixed very small fonts on Windows systems with high-DPI displays",
"Added \"depart fix at heading\" and \"cross fix at altitude/speed\" commands",
"Added \"cancel speed restrictions\" and \"fly present heading\" commands",
"Handed-off departures don't start to climb until they are clicked post-handoff",
"Improved wind modeling",
"Fixed a bug that would cause arrivals to fly faster than the aircraft is capable of",
"Fixed bugs with arrivals not obeying crossing restrictions",
"Improved navigation model to better make crossing restrictions at fixes",
"Fixed *T in the STARS scope: the line is drawn starting with the first click",
"For facility engineers: an error is issued for any unused items in the scenario JSON files",
"Added support for multi-controller simulations(!!)",
"Added manual launch control option",
"Many new scenarios added, including C90, CLE, and CLT",
"Replaced the font used in the STARS radar scope",
"Fixed a few graphics bugs in the STARS radar scope",
"Fixed a rare crash with incorrect command input to the STARS scope",
"New scenarios covering the A80 (ATL) and A90 (BOS) TRACONS",
"Fixed a bug with drawing *P cones",
"Many improvements to the STARS DCB implementation",
"STARS now supports quick-look",
"Fixed a rare crash when manually adjusting launch rates",
"Numerous minor improvements to the STARS UI and functionality (including adding dwell mode)",
"Small fixes to the JAX and CLT scenario files",
"Added support for STARS FUSED mode (choose \"FUSED\" in the \"SITE\" menu in the DCB)",
"New commands: EC/ED: expedite climb/descent",
"New command: I: intercept the localizer",
"New commands: SMIN/SMAX: maintain slowest practical / maximum forward speed",
"New command: AFIX/CAPP: at FIX cleared APP approach",
"Altitude crossing restrictions are more flexible: CFIX/A100-, CFIX/A80+, CFIX/A140-160, etc.",
"Fixed a bug where arrivals would disappear with some scenarios",
"Various updates to the JAX, C90, and F11 scenarios",
"Added D01, KSAV, and KSDF scenarios",
"Allow altitude and speed instructions to be either simultaneous or consecutive",
"Added a new KAAC/KJKE scenario",
"Various minor bugfixes and STARS simulation improvements",
"Many improvements to the accuracy of the KAAC scenario",
"Fixed a bug where arrivals would sometimes climb after being cleared for the approach",
"Fixed a bug in the Windows installer that caused new scenarios (AAC, SAV, SDF) to not be installed locally",
"Added the ability to draw active departure, arrival, and approach routes on the radar scope",
"Added the D01 (Denver TRACON) scenario to single-user vice (the installer was missing it)",
"Added support for updating your Discord activity based on your vice activities (thanks, Samuel Valencia!)",
"Clicking the " + renderer.FontAwesomeIconKeyboard + " icon on the menubar gives a summary of vice's keyboard commands",
"Fixed bug with aircraft descending too early when flying procedure turns",
"Fixed bug with some departures trying to re-fly their initial departure route",
"Fixed multiple bugs with the handling of \"at or above\" altitude constraints",
"Fixed bug with the default DCB brightness being set to 0",
"Added DCA scenario",
"There is now a short delay before aircraft start to follow heading assignments",
"Added \"ID\" command for ident",
"Aircraft can now also be issued control commands by entering their callsign before the commands",
"Fixed bugs with endless go-arounds and with departures not obeying altitude restrictions",
"Fixed a bug that caused vice to sometimes crash after aircraft were given approach clearance",
"Fixed a bug where descending aircraft would stop descending when given approach clearance",
"Small fixes to the DCA scenario",
"Polished up handling of early hand-offs of departures in the STARS scope",
"Added L30 (Las Vegas) scenarios and a combined N90 (JFK+LGA+EWR) scenario",
"Important readbacks from pilots are now highlighted in red",
"Improved STARS *T to allow entering fix names and to show ETA",
"Added support for charted visual approaches",
"STARS allows control-shift click to initiate track (CRC style)",
"Secondary scratchpads are now supported",
"Fixed various navigation bugs",
"STARS: fixed a bug where RBL lines for *T that included aircraft weren't drawn",
"Added an option to hide the flight strips (Settings window, Flight Strips section)",
"Fixed a bug where inbound handoffs wouldn't send a radio contact message",
"Sped up loading of video maps so that vice launches more quickly",
"Added multiple new scenarios: S46, BHM, GSP (Aaron Flett), AUS (Jace Martin), P50 (Mike K)",
"Multi-controller servers can now be password-protected",
"Added \"TO\" command for \"contact tower\"",
"Various bugfixes with handoffs and approach navigation",
"Match real-world STARS alert sounds",
"Added new scenarios: D10 (Mike K), CYS, ASE, COS (Jud Lopez)",
"Fixed multiple bugs with handling of altitude and speed restrictions in departure routes",
"Increased acceleration and climb rate of departures to be more realistic",
"Fixed multiple bugs with point outs",
"Fixed bug in the STARS scope that required secondary scratchpads to be three characters",
"(Re-)added optional sound effect for accepted handoffs",
"Airspace warnings are inhibited for aircraft flying approaches",
"STARS: allow control-left-click in place of the third mouse button to highlight aircraft",
"STARS: actually use the LDB brightness setting for limited/partial datablocks",
"STARS: fix incorrect error message after issuing \"at fix, cleared approach\"",
"Added new scenarios: TPA (Connor Allen), SAN, SCT-BUR (Justin Nguyen), SCT (Eli Thompson), NCT, GJT (Jud Lopez)",
"Smaller scenario updates: D10 and JAX (Mike K), AUS (Jace Martin), LGA, JFK, COS, CLE, ASE, DCA, F11",
"Arc routes between fixes can now be accurately specified",
"STARS: more accurate simulation of STARS weather radar display",
"Added new syntax for issuing left/right turn in degrees: T10L, T20R, etc.",
"STARS: allow middle-click highlight of aircraft regardless of having their track",
"STARS: fixed bug with airport weather list flickering",
"Added new scenarios: SCT LAX (Jud Lopez), IND (Samuel Valencia), MKE (Yahya Nazimuddin), MIA (Mike K)",
"Scenario updates/bugfixes: TPA (Connor Allen), SCT ONT/SNA (Eli Thompson), A80, L30 (Michael Trokel)",
"STARS: added automated terminal proximity alert (ATPA) support",
"STARS: consolidated wake turbulence (CWT) categories are now shown in datablocks and used for ATPA in-trail requirements",
"Live weather can now be used in sims",
"STARS: fixed various small bugs related to when the FDB should be displayed",
"New scenarios: BDL (MerryArbitrary), D21 (Jackson Verdoorn), M98 (Jace Martin), P80 (Ethan Malimon)",
"Scenario updates: EWR (aq86_), LGA (Yi Zheng), MIA (Connor Allen), Y90 (MerryArbitrary, Nelson T)",
`Aircraft control commands (like "C80" for "climb and maintain 8,000") must now start with a comma`,
`Related: the scratchpad can now be set by entering text and slewing an aircraft`,
"Redirected handoffs are now supported and inter- and intra-facility handoffs are now handled more accurately",
`Added support for "force quicklook" to push a quicklook to another controller`,
`Added support for minimum safe altitude warnings (MSAW) for aircraft that are below the MVA`,
`CWT category updates and bugfixes`,
`Added support for global leader lines`,
`Limited datablocks are now supported (and used when appropriate)`,
`Handle various cases where the FDB should be displayed by default`,
`Fixed a bug where go-arounds would sometimes not contact departure`,
`Fixed a bug where live weather would occasionally cause vice to crash`,
`Fixed a bug where aircraft TAS would be too high at high altitudes`,
`Added support for ATC chat (prefix chat messages a '/' in the command prompt)`,
`Allow entering values for STARS DCB spinner using the keyboard`,
`Scenario Updates: D01 and COS (Andrew S), Y90 (Merry Arbitrary), C90 (Jud Lopez, Yahya Nazimuddin)`,
`Added "FC" command to tell aircraft to change to the next controller's frequency`,
`STARS: Add support for displaying requested altitude in FDB`,
`Fixed a bug where aircraft callsign numbers could start with 0`,
`STARS: use realistic fonts for the STARS display`,
`Improved sequencing of departures`,
`Added I90 scenario (Jace Martin)`,
`Added full-screen mode`,
`Updated command entry so keyboard focus returns to STARS after issuing a control command`,
`New scenarios: PIT (Gavin V), AVL, AGS, and GSO (Giovanni), ACK, BNA, BOS, CHS, MHT, OKC, RDU (Michael K)`,
`Updates to BUF, CLE, D21 (Gavin), BHM (Giovanni), JAX and F11 (Michael K), D01 (Jud Lopez, Andrew S)`,
`Even more scenario updates: C90 (Jud Lopez, Yahya Nazimuddin), A90 (Michael K)`,
`STARS: more realistic video map handling (per controller maps, map id #s)`,
`Fixed a bug where vice would crash on launch if it was exited while minimized`,
`STARS: multiple improvements to drawing aircraft tracks`,
`Added a short pause before aircraft ident`,
`Aircraft can now be sent 'direct' to their destination airport`,
`Fixed a bug where vice would sometimes crash at startup or when MAPS was clicked`,
`New scenario: SCT (Jud Lopez)`,
`Scenario updates: AVL (Giovanni), A90 and BOS (Michael K)`,
`Fixed "ID" flashing when aircraft ident`,
`New scenarios: MCI (Brody Carty), P31 (Josh Lambert)`,
`Scenario updates: F11, JAX (Michael Knight), Y90 (Merry Aribrary)`,
`Added "say altitude" (SA) and "say heading" commands (SH) (Michael Knight)`,
`Aircraft delete ("X") is now a CLI command, not a STARS command (Michael Knight)`,
`"Paste" is now supported in the messages pane (Michael Trokel)`,
`The "\" key can be used in place of END to activate the STARS minimum separation tool`,
`Fixed a bug where runway-specific routes in STARs would be followed too early`,
`Fixed a bug where handoffs from virtual controllers would sometimes not be made`,
`Anti-aliasing is disabled by default (but can be re-enabled via the "settings" menu)`,
`Multiple fixes to improve accuracy of drawing in STARS`,
`New scenarios: R90 (Logan S, Jackson Verdoorn), BOI (Jonah Lefkoff)`,
`Scenario updates (1): M98 (Logan S, Jackson Verdoorn), MCI, N90 (Jud Lopez), D21, CLE (Gavin V)`,
`Scenario updates (2): SAN (Justin Nguyen), D01 (Andrew S), MHT, ACK, A90 (Michael Knight), AAC`,
`Added an underlying simulation of the NAS and STARS/ERAM computers`,
`Multiple improvements to the realism of the STARS display and sounds`,
`"Beaconator" added to STARS (F1)`,
`Added "SQ" command to issue a beacon code to an aircraft`,
`Fixed a crash when setting scratchpads`,
`Fixed bugs in the "launch control window" that would prevent it from refreshing`,
`New scenarios: CPR (Andrew S), CID (Tyler Temerowski)`,
`Scenario updates (1): ASE, COS, CYS, D01 (Andrew S), N90 (Kayden Lambert), P50, A80 (radarcontacto)`,
`Scenario updates (2): CDW (Mike LeGall), TPA, MIA (Connor Allen), F11 (Michael Knight), Y90 (Merry Arbitrary)`,
`Fixed a crash on Windows systems with high-DPI displays`,
`Fixed some cases where a procedure turn would be flown even after aircraft passed a "no pt" fix`,
`STARS weather radar rendering is much closer to real-world`,
`STARS: many small fixes to how datablocks and tracks / track ids are drawn`,
`STARS: fixed some bugs where valid scratchpad entries were rejected`,
`Fixed a crash when handing off to a different facility`,
`Fixed a crash with corrupt Sim saves`,
`Added airspace awareness information to the scenario information window`,
`STARS: fixed colors for WX buttons in the DCB when WX is available`,
`STARS: minor improvements to the rendering of tracks and position symbols`,
`Fixed a crash loading saved scenarios from the last release`,
`vice's documentation is substantially expanded and now discusses all currently-available functionality`,
`STARS sign-on list is more realistic. The list of signed-on controllers can now be found in the "scenario info" window`,
`STARS: multiple improvements to data block and radar track drawing accuracy`,
`STARS: added support for inverted numpads on keyboards`,
`STARS: fixed a number of bugs in "quicklook" and in MAPS and PREF management`,
`Scenario updates: D10 (Austin Jenkins), EWR (Mike LeGall), CID (Tyler T), D01, COS (Andrew S), AAC`,
`Massive update to the aircraft performance database (EkimWasHere)`,
`The virtual local controllers sequence departures much better, including handling wake turbulence separation`,
`Multiple improvements to the aircraft flight model`,
`STARS: added support for coordination lists (used for "hold for release")`,
`STARS: improved handling of preference sets: a separate one is stored for each TRACON`,
`Multiple improvements to the accuracy of flight strips`,
`New scenario: SGF (Tyler T)`,
`Updated how aircraft control instructions are entered: press ; to enable "target generation" mode in STARS`,
`New scenario: LGA HAARP (Tyler T)`,
`Scenario updates: CHS, F11 (Michael Knight), SCT, C90, MKE (Jud Lopez)`,
`Fixed a bug where aircraft that went around after being handed off to tower wouldn't contact tower the next time`,
`Fixed a few bugs related to the 250kts speed limit at 10,000'`,
`Added more compact "hold for release" interface for airports that don't use STARS coordination lists`,
`STARS: added OJTI mode, where an instructor can sign in and issue commands to all aircraft`,
`STARS: added support for restriction areas`,
`STARS: multiple improvements to video map handling, including supporting multiple colors and map categories`,
`STARS: CA and MSAW alerts are no longer generated for unassociated tracks`,
`New scenarios: MDT (Darius L), PVD (radarcontacto)`,
`Scenario updates: DCA (radarcontacto), SCT (Aiden), JFK airspace (Mike LeGall), Y90 (Merry), L30, NCT, P80, SCT, SDF (Ketan K)`,
`Airspace boundaries are now displayed using the scenario information window`,
`Improve fetching of airport weather (Makoto Sakaguchi)`,
`Fixed a bug that was causing vice to crash when loading saved sims`,
`Fixed a bug where departures would climb beyond upcoming altitude constraints in SIDs`,
`Fixed a bug where aircraft would incorrectly descend along an approach they weren't yet cleared for`,
`Fixed multiple bugs with the launch control window`,
`Removed text input from the messages pane: it's back to just printing radio calls and messages`,
`Updated handoffs so that there is a delay of 5-10 seconds before aircraft call in after the track is accepted`,
`STARS: continue to display the id for external facility handoffs in datablocks for a few seconds`,
`STARS: improved the accuracy of the mapping of precipitation to WX levels`,
`STARS: a partial callsign is given to specify an aircraft to be given an instruction, it must be a unique suffix of a callsign`,
`STARS: OJTI mode now available where an instructor can issue aircraft control commands (Michael Trokel)`,
}
)
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(r renderer.Renderer, p platform.Platform, config *Config, es *sim.EventStream, lg *log.Logger) {
if runtime.GOOS == "windows" {
imgui.CurrentStyle().ScaleAllSizes(p.DPIScale())
}
ui.font = renderer.GetFont(renderer.FontIdentifier{Name: "Roboto Regular", Size: config.UIFontSize})
ui.aboutFont = renderer.GetFont(renderer.FontIdentifier{Name: "Roboto Regular", Size: 18})
ui.aboutFontSmall = renderer.GetFont(renderer.FontIdentifier{Name: "Roboto Regular", Size: 14})
ui.eventsSubscription = es.Subscribe()
if iconImage, err := png.Decode(bytes.NewReader([]byte(iconPNG))); err != nil {
lg.Errorf("Unable to decode icon PNG: %v", err)
} else {
ui.iconTextureID = r.CreateTextureFromImage(iconImage, false)
}
if sadTowerImage, err := png.Decode(bytes.NewReader([]byte(sadTowerPNG))); err != nil {
lg.Errorf("Unable to decode sad tower PNG: %v", err)
} else {
ui.sadTowerTextureID = r.CreateTextureFromImage(sadTowerImage, false)
}
// 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, config, lg)
if config.WhatsNewIndex < len(whatsNew) {
uiShowModalDialog(NewModalDialogBox(&WhatsNewModalClient{config: config}, p), false)
}
if !config.AskedDiscordOptIn {
uiShowDiscordOptInDialog(p, config)
}
if !config.NotifiedTargetGenMode {
uiShowTargetGenCommandModeDialog(p, config)
}
}
func uiShowModalDialog(d *ModalDialogBox, atFront bool) {
if atFront {
ui.activeModalDialogs = append([]*ModalDialogBox{d}, ui.activeModalDialogs...)
} else {
ui.activeModalDialogs = append(ui.activeModalDialogs, d)
}
}
func uiCloseModalDialog(d *ModalDialogBox) {
ui.activeModalDialogs = util.FilterSlice(ui.activeModalDialogs,
func(m *ModalDialogBox) bool { return m != d })
}
func uiShowConnectDialog(mgr *sim.ConnectionManager, allowCancel bool, config *Config, p platform.Platform, lg *log.Logger) {
client := &ConnectModalClient{
mgr: mgr,
lg: lg,
allowCancel: allowCancel,
platform: p,
config: config,
}
uiShowModalDialog(NewModalDialogBox(client, p), false)
}
func uiShowDiscordOptInDialog(p platform.Platform, config *Config) {
uiShowModalDialog(NewModalDialogBox(&DiscordOptInModalClient{config: config}, p), true)
}
func uiShowTargetGenCommandModeDialog(p platform.Platform, config *Config) {
client := &NotifyTargetGenModalClient{notifiedNew: &config.NotifiedTargetGenMode}
uiShowModalDialog(NewModalDialogBox(client, p), true)
}
// 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 uiDraw(mgr *sim.ConnectionManager, config *Config, p platform.Platform, r renderer.Renderer,
controlClient *sim.ControlClient, eventStream *sim.EventStream, lg *log.Logger) renderer.RendererStats {
if ui.newReleaseDialogChan != nil {
select {
case dialog, ok := <-ui.newReleaseDialogChan:
if ok {
uiShowModalDialog(NewModalDialogBox(dialog, p), 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() {
imgui.PushStyleColor(imgui.StyleColorButton, imgui.CurrentStyle().Color(imgui.StyleColorMenuBarBg))
if controlClient != nil && controlClient.Connected() {
if controlClient.SimIsPaused {
if imgui.Button(renderer.FontAwesomeIconPlayCircle) {
controlClient.ToggleSimPause()
}
if imgui.IsItemHovered() {
imgui.SetTooltip("Resume simulation")
}
} else {
if imgui.Button(renderer.FontAwesomeIconPauseCircle) {
controlClient.ToggleSimPause()
}
if imgui.IsItemHovered() {
imgui.SetTooltip("Pause simulation")
}
}
}
if imgui.Button(renderer.FontAwesomeIconRedo) {
uiShowConnectDialog(mgr, true, config, p, lg)
}
if imgui.IsItemHovered() {
imgui.SetTooltip("Start new simulation")
}
if controlClient != nil && controlClient.Connected() {
if imgui.Button(renderer.FontAwesomeIconCog) {
ui.showSettings = !ui.showSettings
}
if imgui.IsItemHovered() {
imgui.SetTooltip("Open settings window")
}
if imgui.Button(renderer.FontAwesomeIconQuestionCircle) {
ui.showScenarioInfo = !ui.showScenarioInfo
}
if imgui.IsItemHovered() {
imgui.SetTooltip("Show departures, arrivals, approaches, overflights, and airspace awareness")
}
}
if imgui.Button(renderer.FontAwesomeIconKeyboard) {
uiToggleShowKeyboardWindow()
}
if imgui.IsItemHovered() {
imgui.SetTooltip("Show summary of keyboard commands")
}
flashDep := controlClient != nil && !ui.showLaunchControl &&
len(controlClient.State.GetRegularReleaseDepartures()) > 0 && (time.Now().UnixMilli()/500)&1 == 1
if flashDep {
imgui.PushStyleColor(imgui.StyleColorText, imgui.Vec4{0, .8, 0, 1})
}
if imgui.Button(renderer.FontAwesomeIconPlaneDeparture) {
ui.showLaunchControl = !ui.showLaunchControl
}
if flashDep {
imgui.PopStyleColor()
}
if imgui.IsItemHovered() {
imgui.SetTooltip("Control spawning new aircraft and grant departure releases")
}
if imgui.Button(renderer.FontAwesomeIconBook) {
browser.OpenURL("https://pharr.org/vice/index.html")
}
if imgui.IsItemHovered() {
imgui.SetTooltip("Display online vice documentation")
}
width, _ := ui.font.BoundText(renderer.FontAwesomeIconInfoCircle, 0)
imgui.SetCursorPos(imgui.Vec2{p.DisplaySize()[0] - float32(6*width+15), 0})
if imgui.Button(renderer.FontAwesomeIconInfoCircle) {
ui.showAboutDialog = !ui.showAboutDialog
}
if imgui.IsItemHovered() {
imgui.SetTooltip("Display information about vice")
}
if imgui.Button(renderer.FontAwesomeIconDiscord) {
browser.OpenURL("https://discord.gg/y993vgQxhY")
}
if imgui.Button(util.Select(p.IsFullScreen(), renderer.FontAwesomeIconCompressAlt, renderer.FontAwesomeIconExpandAlt)) {
p.EnableFullScreen(!p.IsFullScreen())
}
if imgui.IsItemHovered() {
imgui.SetTooltip(util.Select(p.IsFullScreen(), "Exit", "Enter") + " full-screen mode")
}
imgui.PopStyleColor()
imgui.EndMainMenuBar()
}
ui.menuBarHeight = imgui.CursorPos().Y - 1
if controlClient != nil {
uiDrawSettingsWindow(controlClient, config, p)
if ui.showScenarioInfo {
ui.showScenarioInfo = controlClient.DrawScenarioInfoWindow(lg)
}
uiDrawMissingPrimaryDialog(mgr, controlClient, p)
if ui.showLaunchControl {
if ui.launchControlWindow == nil {
ui.launchControlWindow = MakeLaunchControlWindow(controlClient, lg)
}
ui.launchControlWindow.Draw(eventStream, p)
}
}
for _, event := range ui.eventsSubscription.Get() {
if event.Type == sim.ServerBroadcastMessageEvent {
uiShowModalDialog(NewModalDialogBox(&BroadcastModalDialog{Message: event.Message}, p), false)
}
}
drawActiveDialogBoxes()
uiDrawKeyboardWindow(controlClient, config)
imgui.PopFont()
// Finalize and submit the imgui draw lists
imgui.Render()
cb := renderer.GetCommandBuffer()
defer renderer.ReturnCommandBuffer(cb)
renderer.GenerateImguiCommandBuffer(cb, p.DisplaySize(), p.FramebufferSize(), lg)
return r.RenderCommandBuffer(cb)
}
func uiResetControlClient(c *sim.ControlClient) {
ui.launchControlWindow = nil
}
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()})
}
///////////////////////////////////////////////////////////////////////////
type ModalDialogBox struct {
closed, isOpen bool
client ModalDialogClient
platform platform.Platform
}
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, p platform.Platform) *ModalDialogBox {
return &ModalDialogBox{client: c, platform: p}
}
func (m *ModalDialogBox) Draw() {
if m.closed {
return
}
title := fmt.Sprintf("%s##%p", m.client.Title(), m)
imgui.OpenPopup(title)
flags := imgui.WindowFlagsNoResize | imgui.WindowFlagsAlwaysAutoResize | imgui.WindowFlagsNoSavedSettings
imgui.SetNextWindowSizeConstraints(imgui.Vec2{300, 100}, imgui.Vec2{-1, float32(m.platform.WindowSize()[1]) * 19 / 20})
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 {
mgr *sim.ConnectionManager
lg *log.Logger
simConfig *sim.NewSimConfiguration
allowCancel bool
platform platform.Platform
config *Config
}
func (c *ConnectModalClient) Title() string { return "New Simulation" }
func (c *ConnectModalClient) Opening() {
if c.simConfig == nil {
c.simConfig = sim.MakeNewSimConfiguration(c.mgr, &c.config.LastTRACON, &c.config.TFRCache, c.lg)
}
}
func (c *ConnectModalClient) Buttons() []ModalDialogButton {
var b []ModalDialogButton
if c.allowCancel {
b = append(b, ModalDialogButton{text: "Cancel"})
}
next := ModalDialogButton{
text: c.simConfig.UIButtonText(),
disabled: c.simConfig.OkDisabled(),
action: func() bool {
if c.simConfig.ShowRatesWindow() {
client := &RatesModalClient{
lg: c.lg,
connectClient: c,
platform: c.platform,
}
uiShowModalDialog(NewModalDialogBox(client, c.platform), false)
return true
} else {
c.simConfig.DisplayError = c.simConfig.Start()
return c.simConfig.DisplayError == nil
}
},
}
return append(b, next)
}
func (c *ConnectModalClient) Draw() int {
if enter := c.simConfig.DrawUI(c.platform); enter {
return 1
} else {
return -1
}
}
type RatesModalClient struct {
lg *log.Logger
// Hold on to the connect client both to pick up various parameters
// from it but also so we can go back to it when "Previous" is pressed.
connectClient *ConnectModalClient
platform platform.Platform
}
func (r *RatesModalClient) Title() string { return "Arrival / Departure Rates" }
func (r *RatesModalClient) Opening() {}
func (r *RatesModalClient) Buttons() []ModalDialogButton {
var b []ModalDialogButton
prev := ModalDialogButton{
text: "Previous",
action: func() bool {
uiShowModalDialog(NewModalDialogBox(r.connectClient, r.platform), false)
return true
},
}
b = append(b, prev)
if r.connectClient.allowCancel {
b = append(b, ModalDialogButton{text: "Cancel"})
}
ok := ModalDialogButton{
text: "Create",
disabled: r.connectClient.simConfig.OkDisabled(),
action: func() bool {
r.connectClient.simConfig.DisplayError = r.connectClient.simConfig.Start()
return r.connectClient.simConfig.DisplayError == nil
},
}
return append(b, ok)
}
func (r *RatesModalClient) Draw() int {
if enter := r.connectClient.simConfig.DrawRatesUI(r.platform); enter {
return 1
} else {
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, config *Config, lg *log.Logger) {
defer close(newReleaseDialogChan)
url := "https://api.github.com/repos/mmp/vice/releases"
resp, err := http.Get(url)
if err != nil {
lg.Warn("new release GET error", slog.String("url", url), slog.Any("error", 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.Warnf("No vice releases found?")
return
}
lg.Infof("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.Infof("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.Infof("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 {
config *Config
}
func (wn *WhatsNewModalClient) Title() string {
return "What's new in this version of vice"
}
func (wn *WhatsNewModalClient) Opening() {}
func (wn *WhatsNewModalClient) Buttons() []ModalDialogButton {
return []ModalDialogButton{
ModalDialogButton{
text: "View Release Notes",
action: func() bool {
browser.OpenURL("https://pharr.org/vice/index.html#releases")
return false
},
},
ModalDialogButton{
text: "Ok",
action: func() bool {
wn.config.WhatsNewIndex = len(whatsNew)
return true
},
},
}
}
func (wn *WhatsNewModalClient) Draw() int {
for i := wn.config.WhatsNewIndex; i < len(whatsNew); i++ {
imgui.Text(renderer.FontAwesomeIconSquare + " " + whatsNew[i])
}
return -1
}
type BroadcastModalDialog struct {
Message string
}
func (b *BroadcastModalDialog) Title() string {
return "Server Broadcast Message"
}
func (b *BroadcastModalDialog) Opening() {}
func (b *BroadcastModalDialog) Buttons() []ModalDialogButton {
return []ModalDialogButton{
ModalDialogButton{
text: "Ok",
action: func() bool {
return true
},
},
}
}
func (b *BroadcastModalDialog) Draw() int {
imgui.Text(b.Message)
return -1
}
type DiscordOptInModalClient struct {
config *Config
}
func (d *DiscordOptInModalClient) Title() string {
return "Discord Activity Updates"
}
func (d *DiscordOptInModalClient) Opening() {}
func (d *DiscordOptInModalClient) Buttons() []ModalDialogButton {
return []ModalDialogButton{
ModalDialogButton{
text: "Ok",
action: func() bool {
d.config.AskedDiscordOptIn = true
return true
},
},
}
}
func (d *DiscordOptInModalClient) Draw() int {
style := imgui.CurrentStyle()
spc := style.ItemSpacing()
spc.Y -= 4
imgui.PushStyleVarVec2(imgui.StyleVarItemSpacing, spc)
imgui.Text("By default, vice will automatically update your Discord Activity to say")
imgui.Text("that you are running vice, using information about your current session.")
imgui.Text("If you do not want it to do this, you can disable this feature using the")
imgui.Text("checkbox below. You can also change this setting any time in the future")
imgui.Text("in the settings window " + renderer.FontAwesomeIconCog + " via the menu bar.")
imgui.PopStyleVar()
imgui.Text("")
update := !d.config.InhibitDiscordActivity.Load()