/
app_view.clj
2670 lines (2426 loc) · 131 KB
/
app_view.clj
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 2020-2024 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 Ragnar Svensson, Christian Murray
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.app-view
(:require [cljfx.fx.hyperlink :as fx.hyperlink]
[cljfx.fx.image-view :as fx.image-view]
[cljfx.fx.text :as fx.text]
[cljfx.fx.text-flow :as fx.text-flow]
[cljfx.fx.tooltip :as fx.tooltip]
[cljfx.fx.v-box :as fx.v-box]
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.string :as string]
[dynamo.graph :as g]
[editor.adb :as adb]
[editor.build :as build]
[editor.build-errors-view :as build-errors-view]
[editor.bundle-dialog :as bundle-dialog]
[editor.changes-view :as changes-view]
[editor.code.data :as data :refer [CursorRange->line-number]]
[editor.console :as console]
[editor.debug-view :as debug-view]
[editor.defold-project :as project]
[editor.dialogs :as dialogs]
[editor.disk :as disk]
[editor.disk-availability :as disk-availability]
[editor.editor-extensions :as extensions]
[editor.engine :as engine]
[editor.engine.build-errors :as engine-build-errors]
[editor.engine.native-extensions :as native-extensions]
[editor.error-reporting :as error-reporting]
[editor.fs :as fs]
[editor.fxui :as fxui]
[editor.game-project :as game-project]
[editor.github :as github]
[editor.graph-util :as gu]
[editor.handler :as handler]
[editor.hot-reload :as hot-reload]
[editor.icons :as icons]
[editor.ios-deploy :as ios-deploy]
[editor.keymap :as keymap]
[editor.live-update-settings :as live-update-settings]
[editor.lsp :as lsp]
[editor.lua :as lua]
[editor.pipeline :as pipeline]
[editor.pipeline.bob :as bob]
[editor.placeholder-resource :as placeholder-resource]
[editor.prefs :as prefs]
[editor.prefs-dialog :as prefs-dialog]
[editor.process :as process]
[editor.progress :as progress]
[editor.recent-files :as recent-files]
[editor.resource :as resource]
[editor.resource-dialog :as resource-dialog]
[editor.resource-node :as resource-node]
[editor.scene :as scene]
[editor.scene-cache :as scene-cache]
[editor.scene-visibility :as scene-visibility]
[editor.search-results-view :as search-results-view]
[editor.shared-editor-settings :as shared-editor-settings]
[editor.sync :as sync]
[editor.system :as system]
[editor.targets :as targets]
[editor.types :as types]
[editor.ui :as ui]
[editor.url :as url]
[editor.util :as util]
[editor.view :as view]
[editor.workspace :as workspace]
[internal.graph.types :as gt]
[internal.util :refer [first-where]]
[service.log :as log]
[service.smoke-log :as slog]
[util.http-server :as http-server]
[util.profiler :as profiler]
[util.thread-util :as thread-util])
(:import [clojure.lang ExceptionInfo]
[com.defold.editor Editor]
[com.defold.editor UIUtil]
[com.dynamo.bob Platform]
[com.sun.javafx PlatformUtil]
[com.sun.javafx.scene NodeHelper]
[java.io BufferedReader File IOException OutputStream PipedInputStream PipedOutputStream PrintWriter]
[java.net URL]
[java.nio.charset StandardCharsets]
[java.util Collection List]
[javafx.beans.value ChangeListener]
[javafx.collections ListChangeListener ObservableList]
[javafx.event Event]
[javafx.geometry HPos Orientation Pos]
[javafx.scene Parent Scene]
[javafx.scene.control Label MenuBar SplitPane Tab TabPane TabPane$TabClosingPolicy TabPane$TabDragPolicy Tooltip]
[javafx.scene.image Image ImageView]
[javafx.scene.input Clipboard ClipboardContent]
[javafx.scene.layout AnchorPane GridPane HBox Region StackPane]
[javafx.scene.paint Color]
[javafx.scene.shape Ellipse SVGPath]
[javafx.scene.text Font]
[javafx.stage Screen Stage WindowEvent]))
(set! *warn-on-reflection* true)
(def ^:private split-info-by-pane-kw
{:left {:index 0
:pane-id "left-pane"
:split-id "main-split"}
:right {:index 1
:pane-id "right-pane"
:split-id "workbench-split"}
:bottom {:index 1
:pane-id "bottom-pane"
:split-id "center-split"}})
(defn- pane-visible? [^Scene main-scene pane-kw]
(let [{:keys [pane-id split-id]} (split-info-by-pane-kw pane-kw)]
(some? (.lookup main-scene (str "#" split-id " #" pane-id)))))
(defn- split-pane-length
^double [^SplitPane split-pane]
(condp = (.getOrientation split-pane)
Orientation/HORIZONTAL (.getWidth split-pane)
Orientation/VERTICAL (.getHeight split-pane)))
(defn- set-pane-visible! [^Scene main-scene pane-kw visible?]
(let [{:keys [index pane-id split-id]} (split-info-by-pane-kw pane-kw)
^SplitPane split (.lookup main-scene (str "#" split-id))
^Parent pane (.lookup split (str "#" pane-id))]
(cond
(and (nil? pane) visible?)
(let [user-data-key (keyword "hidden-pane" pane-id)
{:keys [pane size]} (ui/user-data split user-data-key)
divider-index (max 0 (dec index))
divider-position (max 0.0
(min (if (zero? index)
(/ size (split-pane-length split))
(- 1.0 (/ size (split-pane-length split))))
1.0))]
(ui/user-data! split user-data-key nil)
(.add (.getItems split) index pane)
(.setDividerPosition split divider-index divider-position)
(.layout split))
(and (some? pane) (not visible?))
(let [user-data-key (keyword "hidden-pane" pane-id)
divider-index (max 0 (dec index))
divider-position (get (.getDividerPositions split) divider-index)
size (if (zero? index)
(Math/floor (* divider-position (split-pane-length split)))
(Math/ceil (* (- 1.0 divider-position) (split-pane-length split))))
removing-focus-owner? (some? (when-some [focus-owner (.getFocusOwner main-scene)]
(ui/closest-node-where
(partial identical? pane)
focus-owner)))]
(ui/user-data! split user-data-key {:pane pane :size size})
(.remove (.getItems split) pane)
(.layout split)
;; If this action causes the focus owner to be removed from the scene,
;; move focus to the SplitPane. This ensures we have a valid UI context
;; when refreshing the menus.
(when removing-focus-owner?
(.requestFocus split))))
nil))
(defn- select-tool-tab! [tab-id ^Scene main-scene ^TabPane tool-tab-pane]
(let [tabs (.getTabs tool-tab-pane)
tab-index (first (keep-indexed (fn [i ^Tab tab] (when (= tab-id (.getId tab)) i)) tabs))]
(set-pane-visible! main-scene :bottom true)
(if (some? tab-index)
(.select (.getSelectionModel tool-tab-pane) ^long tab-index)
(throw (ex-info (str "Tab id not found: " tab-id)
{:tab-id tab-id
:tab-ids (mapv #(.getId ^Tab %) tabs)})))))
(def show-console! (partial select-tool-tab! "console-tab"))
(def show-curve-editor! (partial select-tool-tab! "curve-editor-tab"))
(def show-build-errors! (partial select-tool-tab! "build-errors-tab"))
(def show-search-results! (partial select-tool-tab! "search-results-tab"))
(defn show-asset-browser! [main-scene]
(set-pane-visible! main-scene :left true))
(defn- show-debugger! [main-scene tool-tab-pane]
;; In addition to the controls in the console pane,
;; the right pane is used to display locals.
(set-pane-visible! main-scene :right true)
(show-console! main-scene tool-tab-pane))
(defn debugger-state-changed! [main-scene tool-tab-pane attention?]
(ui/invalidate-menubar-item! ::debug-view/debug)
(ui/user-data! main-scene ::ui/refresh-requested? true)
(when attention?
(show-debugger! main-scene tool-tab-pane)))
(defn- fire-tab-closed-event! [^Tab tab]
;; TODO: Workaround as there's currently no API to close tabs programatically with identical semantics to close manually
;; See http://stackoverflow.com/questions/17047000/javafx-closing-a-tab-in-tabpane-dynamically
(Event/fireEvent tab (Event. Tab/CLOSED_EVENT)))
(defn- remove-tab! [^TabPane tab-pane ^Tab tab]
(fire-tab-closed-event! tab)
(.remove (.getTabs tab-pane) tab))
(defn remove-invalid-tabs! [tab-panes open-views]
(let [invalid-tab? (fn [tab] (nil? (get open-views (ui/user-data tab ::view))))
closed-tabs-by-tab-pane (into []
(keep (fn [^TabPane tab-pane]
(when-some [closed-tabs (not-empty (filterv invalid-tab? (.getTabs tab-pane)))]
[tab-pane closed-tabs])))
tab-panes)]
;; We must remove all invalid tabs from a TabPane in one go to ensure
;; the selected tab change event does not trigger onto an invalid tab.
(when (seq closed-tabs-by-tab-pane)
(doseq [[^TabPane tab-pane ^Collection closed-tabs] closed-tabs-by-tab-pane]
(doseq [tab closed-tabs]
(fire-tab-closed-event! tab))
(.removeAll (.getTabs tab-pane) closed-tabs)))))
(defn- tab-title
^String [resource is-dirty]
;; Lone underscores are treated as mnemonic letter signifiers in the overflow
;; dropdown menu, and we cannot disable mnemonic parsing for it since the
;; control is internal. We also cannot replace them with double underscores to
;; escape them, as they will show up in the Tab labels and there appears to be
;; no way to enable mnemonic parsing for them. Attempts were made to call
;; setMnemonicParsing on the parent Labelled as the Tab graphic was added to
;; the DOM, but this only worked on macOS. As a workaround, we instead replace
;; underscores with the a unicode character that looks somewhat similar.
(let [resource-name (resource/resource-name resource)
escaped-resource-name (string/replace resource-name "_" "\u02CD")]
(if is-dirty
(str "*" escaped-resource-name)
escaped-resource-name)))
(defn- is-macos [] (PlatformUtil/isMac))
(defn- create-key-info [label key-combo]
(let [cmd (if (is-macos) "⌘" "Cmd")
ctrl (if (is-macos) "⌃" "Ctrl")
alt (if (is-macos) "⌥" "Alt")
shift (if (is-macos) "⇧" "Shift")
keys (into []
(remove nil?)
(list
(when (:meta-down? key-combo) cmd)
(when (:control-down? key-combo) ctrl)
(when (:alt-down? key-combo) alt)
(when (:shift-down? key-combo) shift)
(str (:key key-combo))))]
{:label label :keys keys}))
(defn- update-quick-help-pane [^SplitPane editor-tabs-split keymap]
(let [tab-panes (.getItems editor-tabs-split)
is-empty (not-any? #(-> ^TabPane % .getTabs count pos?) tab-panes)
parent (.getParent editor-tabs-split)
quick-help-box (.lookup parent "#quick-help-box")
^GridPane box-items (.lookup parent "#quick-help-items")]
;; Only make quick help visible when there is no-tabs.
(.setVisible quick-help-box is-empty)
(when is-empty
(let [command->key-combo
(into {}
(mapcat (fn [[key-combo command-infos]]
(map (fn [command-info] [(:command command-info) key-combo]) command-infos)))
keymap)
items (keep (fn [[command label]]
(when-some [key-combo (command->key-combo command)]
(create-key-info label key-combo)))
[[:open-asset "Open Asset"]
[:reopen-recent-file "Re-Open Closed File"]
[:search-in-files "Search in Files"]
[:build "Build and Run Project"]
[:start-debugger "Start or Attach Debugger"]])]
(-> box-items .getChildren .clear)
(doseq [[row-index item] (map-indexed vector items)]
(let [space-character (if (is-macos) "" "+")
space (if (is-macos) 5 10)
label-font (Font. "Dejavu Sans Mono" 13)
key-font (Font. "" 13)
color (Color. 1.0 1.0 0.59765625 0.6)
label (:label item)
keys (:keys item)]
;; Add label in the first column
(let [label-ui (Label. label)]
(.setFont label-ui label-font)
(.setTextFill label-ui color)
(GridPane/setHalignment label-ui (HPos/RIGHT))
(-> box-items (.add label-ui 0 row-index)))
;; Add keys (in the hbox) in the second column
(let [hbox (HBox.)]
(.setAlignment hbox (Pos/CENTER_LEFT))
(let [spacer (Region.)]
(.setPrefWidth spacer 10)
(-> hbox .getChildren (.add spacer)))
(doseq [[index key] (map-indexed vector keys)]
(when (pos? index)
(let [plus-ui (Label. space-character)]
(.setPrefWidth plus-ui space)
(.setAlignment plus-ui (Pos/CENTER))
(-> hbox .getChildren (.add plus-ui))))
(let [key-ui (Label. key)]
(.setFont key-ui key-font)
(.setAlignment key-ui (Pos/CENTER))
(.setTextFill key-ui color)
(-> key-ui .getStyleClass (.add "key-button"))
(-> hbox .getChildren (.add key-ui))))
(-> box-items (.add hbox 1 row-index)))))))))
(g/defnode AppView
(property stage Stage)
(property scene Scene)
(property editor-tabs-split SplitPane)
(property active-tab-pane TabPane)
(property active-tab Tab)
(property tool-tab-pane TabPane)
(property auto-pulls g/Any)
(property active-tool g/Keyword)
(property manip-space g/Keyword)
(property keymap-config g/Any)
(input open-views g/Any :array)
(input open-dirty-views g/Any :array)
(input scene-view-ids g/Any :array)
(input hidden-renderable-tags types/RenderableTags)
(input hidden-node-outline-key-paths types/NodeOutlineKeyPaths)
(input active-outline g/Any)
(input active-scene g/Any)
(input project-id g/NodeID)
(input selected-node-ids-by-resource-node g/Any)
(input selected-node-properties-by-resource-node g/Any)
(input sub-selections-by-resource-node g/Any)
(input debugger-execution-locations g/Any)
(output open-views g/Any :cached (g/fnk [open-views] (into {} open-views)))
(output open-dirty-views g/Any :cached (g/fnk [open-dirty-views] (into #{} (keep #(when (second %) (first %))) open-dirty-views)))
(output hidden-renderable-tags types/RenderableTags (gu/passthrough hidden-renderable-tags))
(output hidden-node-outline-key-paths types/NodeOutlineKeyPaths (gu/passthrough hidden-node-outline-key-paths))
(output active-outline g/Any (gu/passthrough active-outline))
(output active-scene g/Any (gu/passthrough active-scene))
(output active-view g/NodeID (g/fnk [^Tab active-tab]
(when active-tab
(ui/user-data active-tab ::view))))
(output active-view-info g/Any (g/fnk [^Tab active-tab]
(when active-tab
{:view-id (ui/user-data active-tab ::view)
:view-type (ui/user-data active-tab ::view-type)})))
(output active-resource-node g/NodeID :cached (g/fnk [active-view open-views] (:resource-node (get open-views active-view))))
(output active-resource-node+type g/Any :cached
(g/fnk [active-view open-views]
(when-let [{:keys [resource-node resource-node-type]} (get open-views active-view)]
[resource-node resource-node-type])))
(output active-resource resource/Resource :cached (g/fnk [active-view open-views] (:resource (get open-views active-view))))
(output open-resource-nodes g/Any :cached (g/fnk [open-views] (->> open-views vals (map :resource-node))))
(output selected-node-ids g/Any (g/fnk [selected-node-ids-by-resource-node active-resource-node]
(get selected-node-ids-by-resource-node active-resource-node)))
(output selected-node-properties g/Any (g/fnk [selected-node-properties-by-resource-node active-resource-node]
(get selected-node-properties-by-resource-node active-resource-node)))
(output sub-selection g/Any (g/fnk [sub-selections-by-resource-node active-resource-node]
(get sub-selections-by-resource-node active-resource-node)))
(output refresh-tab-panes g/Any :cached (g/fnk [^SplitPane editor-tabs-split open-views open-dirty-views keymap]
(let [tab-panes (.getItems editor-tabs-split)]
(update-quick-help-pane editor-tabs-split keymap)
(doseq [^TabPane tab-pane tab-panes
^Tab tab (.getTabs tab-pane)
:let [view (ui/user-data tab ::view)
resource (:resource (get open-views view))
is-dirty (contains? open-dirty-views view)
title (tab-title resource is-dirty)]]
(ui/text! tab title)))))
(output keymap g/Any :cached (g/fnk [keymap-config]
(keymap/make-keymap keymap-config {:valid-command? (set (handler/available-commands))})))
(output debugger-execution-locations g/Any (gu/passthrough debugger-execution-locations)))
(defn- selection->openable-resources [selection]
(when-let [resources (handler/adapt-every selection resource/Resource)]
(filterv resource/openable-resource? resources)))
(defn- selection->single-openable-resource [selection]
(when-let [r (handler/adapt-single selection resource/Resource)]
(when (resource/openable-resource? r)
r)))
(defn- selection->single-resource [selection]
(handler/adapt-single selection resource/Resource))
(defn- context-resource-file
([app-view selection]
(g/with-auto-evaluation-context evaluation-context
(context-resource-file app-view selection evaluation-context)))
([app-view selection evaluation-context]
(or (selection->single-openable-resource selection)
(g/node-value app-view :active-resource evaluation-context))))
(defn- context-resource
([app-view selection]
(g/with-auto-evaluation-context evaluation-context
(context-resource app-view selection evaluation-context)))
([app-view selection evaluation-context]
(or (selection->single-resource selection)
(g/node-value app-view :active-resource evaluation-context))))
(defn- disconnect-sources [target-node target-label]
(for [[source-node source-label] (g/sources-of target-node target-label)]
(g/disconnect source-node source-label target-node target-label)))
(defn- replace-connection [source-node source-label target-node target-label]
(concat
(disconnect-sources target-node target-label)
(if (and source-node (contains? (-> source-node g/node-type* g/output-labels) source-label))
(g/connect source-node source-label target-node target-label)
[])))
(defn- on-selected-tab-changed! [app-view app-scene tab resource-node view-type]
(g/transact
(concat
(replace-connection resource-node :node-outline app-view :active-outline)
(if (= :scene view-type)
(replace-connection resource-node :scene app-view :active-scene)
(disconnect-sources app-view :active-scene))
(g/set-property app-view :active-tab tab)))
(ui/user-data! app-scene ::ui/refresh-requested? true))
(handler/defhandler :move-tool :workbench
(enabled? [app-view] true)
(run [app-view] (g/transact (g/set-property app-view :active-tool :move)))
(state [app-view] (= (g/node-value app-view :active-tool) :move)))
(handler/defhandler :scale-tool :workbench
(enabled? [app-view] true)
(run [app-view] (g/transact (g/set-property app-view :active-tool :scale)))
(state [app-view] (= (g/node-value app-view :active-tool) :scale)))
(handler/defhandler :rotate-tool :workbench
(enabled? [app-view] true)
(run [app-view] (g/transact (g/set-property app-view :active-tool :rotate)))
(state [app-view] (= (g/node-value app-view :active-tool) :rotate)))
(handler/defhandler :show-visibility-settings :workbench
(run [app-view scene-visibility]
(when-let [btn (some-> ^TabPane (g/node-value app-view :active-tab-pane)
(ui/selected-tab)
(.. getContent (lookup "#show-visibility-settings")))]
(scene-visibility/show-visibility-settings! btn scene-visibility)))
(state [app-view scene-visibility]
(when-let [btn (some-> ^TabPane (g/node-value app-view :active-tab-pane)
(ui/selected-tab)
(.. getContent (lookup "#show-visibility-settings")))]
;; TODO: We have no mechanism for updating the style nor icon on
;; on the toolbar button. For now we piggyback on the state
;; update polling to set a style when the filters are active.
(if (scene-visibility/filters-appear-active? scene-visibility)
(ui/add-style! btn "filters-active")
(ui/remove-style! btn "filters-active"))
(scene-visibility/settings-visible? btn))))
(def ^:private eye-icon-svg-path
(ui/load-svg-path "scene/images/eye_icon_eye_arrow.svg"))
(def ^:private perspective-icon-svg-path
(ui/load-svg-path "scene/images/perspective_icon.svg"))
(defn make-svg-icon-graphic
^SVGPath [^SVGPath icon-template]
(doto (SVGPath.)
(.setContent (.getContent icon-template))))
(defn- make-visibility-settings-graphic []
(doto (StackPane.)
(ui/children! [(doto (make-svg-icon-graphic eye-icon-svg-path)
(.setId "eye-icon"))
(doto (Ellipse. 3.0 3.0)
(.setId "active-indicator"))])))
(handler/register-menu! :toolbar
[{:id :select
:icon "icons/45/Icons_T_01_Select.png"
:command :select-tool}
{:id :move
:icon "icons/45/Icons_T_02_Move.png"
:command :move-tool}
{:id :rotate
:icon "icons/45/Icons_T_03_Rotate.png"
:command :rotate-tool}
{:id :scale
:icon "icons/45/Icons_T_04_Scale.png"
:command :scale-tool}
{:id :perspective-camera
:graphic-fn (partial make-svg-icon-graphic perspective-icon-svg-path)
:command :toggle-perspective-camera}
{:id :visibility-settings
:graphic-fn make-visibility-settings-graphic
:command :show-visibility-settings}])
(def ^:const prefs-window-dimensions "window-dimensions")
(def ^:const prefs-split-positions "split-positions")
(def ^:const prefs-hidden-panes "hidden-panes")
(handler/defhandler :quit :global
(enabled? [] true)
(run []
(let [^Stage main-stage (ui/main-stage)]
(.fireEvent main-stage (WindowEvent. main-stage WindowEvent/WINDOW_CLOSE_REQUEST)))))
(defn store-window-dimensions [^Stage stage prefs]
(let [dims {:x (.getX stage)
:y (.getY stage)
:width (.getWidth stage)
:height (.getHeight stage)
:maximized (.isMaximized stage)
:full-screen (.isFullScreen stage)}]
(prefs/set-prefs prefs prefs-window-dimensions dims)))
(defn restore-window-dimensions [^Stage stage prefs]
(when-let [dims (prefs/get-prefs prefs prefs-window-dimensions nil)]
(let [{:keys [x y width height maximized full-screen]} dims
maximized (and maximized (not system/mac?))] ; Maximized is not really a thing on macOS, and if set, cannot become false.
(when (and (number? x) (number? y) (number? width) (number? height))
(when-let [_ (seq (Screen/getScreensForRectangle x y width height))]
(doto stage
(.setX x)
(.setY y))
;; Maximized and setWidth/setHeight in combination triggers a bug on macOS where the window becomes invisible
(when (and (not maximized) (not full-screen))
(doto stage
(.setWidth width)
(.setHeight height)))))
(when maximized
(.setMaximized stage true))
(when full-screen
(.setFullScreen stage true)))))
(def ^:private legacy-split-ids ["main-split"
"center-split"
"right-split"
"assets-split"])
(def ^:private split-ids ["main-split"
"workbench-split"
"center-split"
"right-split"
"assets-split"])
(defn- existing-split-panes [^Scene scene]
(into {}
(keep (fn [split-id]
(when-some [control (.lookup scene (str "#" split-id))]
[(keyword split-id) control])))
split-ids))
(defn- stored-split-positions [prefs]
(if-some [split-positions (prefs/get-prefs prefs prefs-split-positions nil)]
(if (vector? split-positions) ; Legacy preference format
(zipmap (map keyword legacy-split-ids)
split-positions)
split-positions)
{}))
(defn store-split-positions! [^Scene scene prefs]
(let [split-positions (into (stored-split-positions prefs)
(map (fn [[id ^SplitPane sp]]
[id (.getDividerPositions sp)]))
(existing-split-panes scene))]
(prefs/set-prefs prefs prefs-split-positions split-positions)))
(defn restore-split-positions! [^Scene scene prefs]
(let [split-positions (stored-split-positions prefs)
split-panes (existing-split-panes scene)]
(doseq [[id positions] split-positions]
(when-some [^SplitPane split-pane (get split-panes id)]
(.setDividerPositions split-pane (double-array positions))
(.layout split-pane)))))
(defn stored-hidden-panes [prefs]
(prefs/get-prefs prefs prefs-hidden-panes #{}))
(defn store-hidden-panes! [^Scene scene prefs]
(let [hidden-panes (into #{}
(remove (partial pane-visible? scene))
(keys split-info-by-pane-kw))]
(prefs/set-prefs prefs prefs-hidden-panes hidden-panes)))
(defn restore-hidden-panes! [^Scene scene prefs]
(let [hidden-panes (stored-hidden-panes prefs)]
(doseq [pane-kw hidden-panes]
(set-pane-visible! scene pane-kw false))))
(handler/defhandler :preferences :global
(run [workspace prefs app-view]
(prefs-dialog/open-prefs prefs)
(workspace/update-build-settings! workspace prefs)
(ui/invalidate-menubar-item! ::file)))
(defn- collect-resources [{:keys [children] :as resource}]
(if (empty? children)
#{resource}
(set (concat [resource] (mapcat collect-resources children)))))
(defn- get-active-tabs [app-view evaluation-context]
(let [tab-pane ^TabPane (g/node-value app-view :active-tab-pane evaluation-context)]
(.getTabs tab-pane)))
(defn- make-render-build-error [main-scene tool-tab-pane build-errors-view]
(fn [error-value]
(build-errors-view/update-build-errors build-errors-view error-value)
(show-build-errors! main-scene tool-tab-pane)))
(def ^:private remote-log-pump-thread (atom nil))
(def ^:private console-stream (atom nil))
(defn- reset-remote-log-pump-thread! [^Thread new]
(when-let [old ^Thread @remote-log-pump-thread]
(.interrupt old))
(reset! remote-log-pump-thread new))
(defn- start-log-pump! [log-stream sink-fn]
(doto (Thread. (fn []
(try
(let [this (Thread/currentThread)]
(with-open [buffered-reader ^BufferedReader (io/reader log-stream :encoding "UTF-8")]
(loop []
(when-not (.isInterrupted this)
(when-let [line (.readLine buffered-reader)] ; line of text or nil if eof reached
(sink-fn line)
(recur))))))
(catch IOException _
;; Losing the log connection is ok and even expected
nil)
(catch InterruptedException _
;; Losing the log connection is ok and even expected
nil))))
(.start)))
(defn- local-url [target web-server]
(format "http://%s:%s%s" (:local-address target) (http-server/port web-server) hot-reload/url-prefix))
(def ^:private app-task-progress
{:main (ref progress/done)
:build (ref progress/done)
:resource-sync (ref progress/done)
:save-all (ref progress/done)
:fetch-libraries (ref progress/done)
:download-update (ref progress/done)})
(defn- cancel-task!
[task-key]
(dosync
(let [progress-ref (task-key app-task-progress)]
(ref-set progress-ref (progress/cancel! @progress-ref)))))
(def ^:private app-task-ui-priority
"Task priority in descending order (from highest to lowest)"
[:save-all :resource-sync :fetch-libraries :build :download-update :main])
(def ^:private render-task-progress-ui-inflight (ref false))
(defn- render-task-progress-ui! []
(let [task-progress-snapshot (ref nil)]
(dosync
(ref-set render-task-progress-ui-inflight false)
(ref-set task-progress-snapshot
(into {} (map (juxt first (comp deref second))) app-task-progress)))
(let [status-bar (.. (ui/main-stage) (getScene) (getRoot) (lookup "#status-bar"))
[key progress] (->> app-task-ui-priority
(map (juxt identity @task-progress-snapshot))
(filter (comp (complement progress/done?) second))
first)
show-progress-hbox? (boolean (and (not= key :main)
progress
(not (progress/done? progress))))]
(ui/with-controls status-bar [progress-bar progress-hbox progress-percentage-label status-label progress-cancel-button]
(ui/render-progress-message!
(if key progress (@task-progress-snapshot :main))
status-label)
;; The bottom right of the status bar can show either the progress-hbox
;; or the update-link, or both. The progress-hbox will cover
;; the update-link if both are visible.
(if-not show-progress-hbox?
(ui/visible! progress-hbox false)
(do
(ui/visible! progress-hbox true)
(ui/render-progress-bar! progress progress-bar)
(ui/render-progress-percentage! progress progress-percentage-label)
(if (progress/cancellable? progress)
(doto progress-cancel-button
(ui/visible! true)
(ui/managed! true)
(ui/on-action! (fn [_] (cancel-task! key))))
(doto progress-cancel-button
(ui/visible! false)
(ui/managed! false)
(ui/on-action! identity)))))))))
(defn- render-task-progress! [key progress]
(let [schedule-render-task-progress-ui (ref false)]
(dosync
(ref-set (get app-task-progress key) progress)
(ref-set schedule-render-task-progress-ui (not @render-task-progress-ui-inflight))
(ref-set render-task-progress-ui-inflight true))
(when @schedule-render-task-progress-ui
(ui/run-later (render-task-progress-ui!)))))
(defn make-render-task-progress [key]
(assert (contains? app-task-progress key))
(progress/throttle-render-progress
(fn [progress] (render-task-progress! key progress))))
(defn make-task-cancelled-query [keyword]
(fn [] (progress/cancelled? @(keyword app-task-progress))))
(defn render-main-task-progress! [progress]
(render-task-progress! :main progress))
(defn- report-build-launch-progress! [message]
(render-main-task-progress! (progress/make message)))
(defn- clear-build-launch-progress! []
(render-main-task-progress! progress/done))
(def ^:private build-in-progress-atom (atom false))
(defn- build-in-progress? []
@build-in-progress-atom)
(defn- async-reload-on-app-focus? [prefs]
(prefs/get-prefs prefs "external-changes-load-on-app-focus" true))
(defn- can-async-reload? []
(and (disk-availability/available?)
(not (build-in-progress?))
(not (sync/sync-dialog-open?))))
(defn async-reload!
[app-view changes-view workspace moved-files]
(let [render-reload-progress! (make-render-task-progress :resource-sync)]
(disk/async-reload! render-reload-progress! workspace moved-files changes-view
(fn [_success]
(ui/user-data! (g/node-value app-view :scene) ::ui/refresh-requested? true)))))
(defn handle-application-focused! [app-view changes-view workspace prefs]
(when (and (disk-availability/available?)
(not (build-in-progress?)))
(clear-build-launch-progress!))
(when (and (async-reload-on-app-focus? prefs)
(can-async-reload?))
(async-reload! app-view changes-view workspace [])))
(defn- decorate-target [engine-descriptor target]
(assoc target :engine-id (:id engine-descriptor)))
(defn- launch-engine! [engine-descriptor project-directory prefs debug?]
(try
(report-build-launch-progress! "Launching engine...")
(let [engine (engine/install-engine! project-directory engine-descriptor)
launched-target (->> (engine/launch! engine project-directory prefs debug?)
(decorate-target engine-descriptor)
(targets/add-launched-target!)
(targets/select-target! prefs))]
(report-build-launch-progress! (format "Launched %s" (targets/target-message-label launched-target)))
launched-target)
(catch Exception e
(targets/kill-launched-targets!)
(report-build-launch-progress! "Launch failed")
(throw e))))
(defn- reset-console-stream! [stream]
(reset! console-stream stream)
(console/clear-console!))
(defn- make-remote-log-sink [log-stream]
(fn [line]
(when (= @console-stream log-stream)
(console/append-console-line! line))))
(defn- make-launched-log-sink [launched-target]
(let [initial-output (atom "")]
(fn [line]
(when (< (count @initial-output) 5000)
(swap! initial-output str line "\n")
(when-let [target-info (engine/parse-launched-target-info @initial-output)]
(targets/update-launched-target! launched-target target-info)))
(when (= @console-stream (:log-stream launched-target))
(console/append-console-line! line)))))
(defn- reboot-engine! [target web-server debug?]
(try
(report-build-launch-progress! (format "Rebooting %s..." (targets/target-message-label target)))
(engine/reboot! target (local-url target web-server) debug?)
(report-build-launch-progress! (format "Rebooted %s" (targets/target-message-label target)))
target
(catch Exception e
(report-build-launch-progress! "Reboot failed")
(throw e))))
(defn- on-launched-hook! [project process url]
(let [hook-options {:exception-policy :ignore :opts {:url url}}]
(future
(error-reporting/catch-all!
(extensions/execute-hook! project :on-target-launched hook-options)
(process/on-exit! process #(extensions/execute-hook! project :on-target-terminated hook-options))))))
(defn- target-cannot-swap-engine? [target]
(and (some? target)
(targets/controllable-target? target)
(targets/remote-target? target)))
(defn- launch-built-project! [project engine-descriptor project-directory prefs web-server debug?]
(let [selected-target (targets/selected-target prefs)
launch-new-engine! (fn []
(targets/kill-launched-targets!)
(let [launched-target (launch-engine! engine-descriptor project-directory prefs debug?)
log-stream (:log-stream launched-target)]
(targets/when-url (:id launched-target)
#(on-launched-hook! project (:process launched-target) %))
(reset-console-stream! log-stream)
(reset-remote-log-pump-thread! nil)
(start-log-pump! log-stream (make-launched-log-sink launched-target))
launched-target))]
(try
(cond
(not selected-target)
(launch-new-engine!)
(not (targets/controllable-target? selected-target))
(do
(assert (targets/launched-target? selected-target))
(launch-new-engine!))
(target-cannot-swap-engine? selected-target)
(let [log-stream (engine/get-log-service-stream selected-target)]
(reset-console-stream! log-stream)
(reset-remote-log-pump-thread! (start-log-pump! log-stream (make-remote-log-sink log-stream)))
(reboot-engine! selected-target web-server debug?))
:else
(do
(assert (and (targets/controllable-target? selected-target) (targets/launched-target? selected-target)))
(if (= (:id engine-descriptor) (:engine-id selected-target))
(do
;; We're running "the same" engine and can reuse the
;; running process by rebooting
(reset-console-stream! (:log-stream selected-target))
(reset-remote-log-pump-thread! nil)
;; Launched target log pump already
;; running to keep engine process
;; from halting because stdout/err is
;; not consumed.
(reboot-engine! selected-target web-server debug?))
(launch-new-engine!))))
(catch Exception e
(log/warn :exception e)
(dialogs/make-info-dialog
{:title "Launch Failed"
:icon :icon/triangle-error
:header {:fx/type fx.v-box/lifecycle
:children [{:fx/type fxui/label
:variant :header
:text (format "Launching %s failed"
(if (some? selected-target)
(targets/target-message-label selected-target)
"New Local Engine"))}
{:fx/type fxui/label
:text "If the engine is already running, shut down the process manually and retry"}]}
:content (.getMessage e)})))))
(defn- get-cycle-detected-help-message [node-id]
(let [basis (g/now)
proj-path (some-> (resource-node/owner-resource basis node-id) resource/proj-path)
resource-path (or proj-path "'unknown'")]
(case (g/node-type-kw basis node-id)
:editor.collection/CollectionNode
(format "This is caused by a two or more collections referenced in a loop from either collection proxies or collection factories. One of the resources is: %s." resource-path)
:editor.game-object/GameObjectNode
(format "This is caused by two or more game objects referenced in a loop from game object factories. One of the resources is: %s." resource-path)
:editor.code.script/ScriptNode
(format "This is caused by two or more Lua modules required in a loop. One of the resources is: %s." resource-path)
(format "This is caused by two or more resources referenced in a loop. One of the resources is: %s." resource-path))))
(defn- build-project!
[project evaluation-context extra-build-targets old-artifact-map render-progress!]
(let [game-project (project/get-resource-node project "/game.project" evaluation-context)
render-progress! (progress/throttle-render-progress render-progress!)]
(try
(ui/with-progress [render-progress! render-progress!]
(build/build-project! project game-project evaluation-context extra-build-targets old-artifact-map render-progress!))
(catch ExceptionInfo e
(if (= :cycle-detected (-> e ex-data :cause))
(ui/run-later
(dialogs/make-info-dialog
{:title "Build Error"
:icon :icon/triangle-error
:header "Cyclic resource dependency detected"
:content {:fx/type fxui/label
:style-class "dialog-content-padding"
:text (get-cycle-detected-help-message (-> e ex-data :endpoint gt/endpoint-node-id))}}))
(error-reporting/report-exception! e))
{:error (g/map->error {:severity :fatal
:message (or (when (= :cycle-detected (-> e ex-data :cause))
(str "Cyclic resource dependency detected. " (get-cycle-detected-help-message (-> e ex-data :endpoint gt/endpoint-node-id))))
(.getMessage e)
(.getName (class e)))})})
(catch Throwable error
(error-reporting/report-exception! error)
{:error (g/map->error {:severity :fatal
:message (or (.getMessage error) (.getName (class error)))})}))))
(defn async-build!
"Asynchronously build the project and notify the :result-fn with results
Kv-args:
:result-fn required fn that will receive build results, a map with
the following keys:
* :artifacts, :artifact-map and :etags - results for
successfully built project resources
* :engine - engine descriptor map when asked to build
the engine, and it was successfully built
* :error - error value in case of any errors, be it
project resources, linting or engine build error
* :warning - error value in case there are non-critical
issues reported by the build process
:build-engine optional flag that indicates whether the engine should
be built in addition to the project
:lint optional flag that indicates whether to run LSP lints
and present the diagnostics alongside the build errors
:prefs required if :build-engine is true, preferences for
engine building, e.g. the build server settings
:debug optional flag that indicates whether to also build
debugging tools
:run-build-hooks optional flag that indicates whether to run pre- and
post-build hooks
:render-progress! optional progress reporter fn
:old-artifact-map optional old artifact map with previous build results
to speed up the build process"
[project & {:keys [;; required
result-fn
;; required if :build-engine is true (which is a default)
prefs
;; optional
debug build-engine run-build-hooks render-progress! old-artifact-map lint]
:or {debug false
build-engine true
run-build-hooks true
lint true
render-progress! progress/null-render-progress!
old-artifact-map {}}}]
{:pre [(ifn? result-fn)
(or (not build-engine) (some? prefs))]}
(let [;; After any pre-build hooks have completed successfully, we will start
;; the engine build on a separate background thread so the build servers
;; can work while we build the project. We will await the results of the
;; engine build in the final phase.
engine-build-future-atom (atom nil)
cancel-engine-build!
(fn cancel-engine-build! []
(when-some [engine-build-future (thread-util/preset! engine-build-future-atom nil)]
(future-cancel engine-build-future)
nil))
start-engine-build!
(fn start-engine-build! []
(assert (ui/on-ui-thread?))
(cancel-engine-build!)
(when build-engine
(let [evaluation-context (g/make-evaluation-context)
platform (engine/current-platform)]
(reset! engine-build-future-atom
(future
(try
(let [engine (engine/get-engine project evaluation-context prefs platform)]
(ui/run-later
;; This potentially saves us from having to
;; re-calculate native extension file hashes the
;; next time we build the project.