Debian Codegraph @

tools/castle-editor/code/formproject.pas

raw
1 {
2 Copyright 2018-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Project form (@link(TProjectForm)). }
17 unit FormProject;
18
19 {$I castleconf.inc}
20
21 { Hack to use OpenDocument instead of RunCommandNoWait to execute Delphi.
22 This assumes that Delphi is associated on your system with Pascal files.
23 OTOH it will work a bit nicer, not opening new Delphi instance each time,
24 as Windows underneath will use DDE to communicate with Delphi BDSLauncher. }
25 {$define DELPHI_OPEN_SHELL}
26
27 interface
28
29 uses
30 Classes, SysUtils, DOM, FileUtil, Forms, Controls, Graphics, Dialogs, Menus,
31 ExtCtrls, ComCtrls, CastleShellCtrls, StdCtrls, ValEdit, ActnList, Buttons,
32 AnchorDocking, XMLPropStorage, ImgList,
33 ProjectUtils, Types, Contnrs, CastleControl, CastleUIControls,
34 CastlePropEdits, CastleDialogs, X3DNodes, CastleFindFiles,
35 DataModuleIcons, CastleClassUtils,
36 EditorUtils, FrameDesign, FrameViewFile, FormNewUnit, ToolManifest,
37 ToolPackageFormat;
38
39 const
40 DockLayoutFileName = 'layout.dock-layout';
41 DockLayoutFileNameDefault = 'default.dock-layout';
42
43 type
44 { Main project management. }
45 TProjectForm = class(TForm)
46 ActionCopyUrl: TAction;
47 ActionRunParameterPretendTouchDevice: TAction;
48 ActionFindNext: TAction;
49 ActionFindToggle: TAction;
50 ActionImportSketchfab: TAction;
51 ActionShowStatistics: TAction;
52 ActionRunParameterCapabilitiesForceFixedFunction: TAction;
53 ActionRunParameterCapabilitiesForceModern: TAction;
54 ActionRunParameterCapabilitiesDefault: TAction;
55 ActionRunParameterDefaultWindowOrFullscreen: TAction;
56 ActionRunParameterRequestWindow: TAction;
57 ActionRunParameterRequestFullScreen: TAction;
58 ActionRunParameterDisableFpsLimit: TAction;
59 ActionRunParameterDisableSound: TAction;
60 ActionPlayStop: TAction;
61 ActionShowColliders: TAction;
62 ActionSimulationPlayStop: TAction;
63 ActionSimulationPauseUnpause: TAction;
64 ActionViewportRenderNext: TAction;
65 ActionViewportRenderSolidWireframe: TAction;
66 ActionPhysicsHideAllJointsTools: TAction;
67 ActionPhysicsShowAllJointsTools: TAction;
68 ActionModeSelect: TAction;
69 ActionModeTranslate: TAction;
70 ActionModeRotate: TAction;
71 ActionModeScale: TAction;
72 ActionModeInteract: TAction;
73 ActionFocusDesign: TAction;
74 ActionWarningsCopyAll: TAction;
75 ActionWarningsCopySelected: TAction;
76 ActionWarningsClean: TAction;
77 ActionViewportGridAxis: TAction;
78 ActionViewportRenderWireframeOnly: TAction;
79 ActionViewportRenderNormal: TAction;
80 ActionComponentDuplicate: TAction;
81 ActionComponentSaveSelected: TAction;
82 ActionComponentDelete: TAction;
83 ActionComponentCut: TAction;
84 ActionComponentPaste: TAction;
85 ActionComponentCopy: TAction;
86 ActionViewportToggleProjection: TAction;
87 ActionViewportSetup2D: TAction;
88 ActionViewportAlignCameraToView: TAction;
89 ActionViewportTop: TAction;
90 ActionNavigationToggle2D: TAction;
91 ActionViewportAlignViewToCamera: TAction;
92 ActionViewportBottom: TAction;
93 ActionViewportFront: TAction;
94 ActionViewportBack: TAction;
95 ActionViewportRight: TAction;
96 ActionViewportLeft: TAction;
97 ActionNavigationFly: TAction;
98 ActionNavigationExamine: TAction;
99 ActionNavigation2D: TAction;
100 ActionViewportViewSelected: TAction;
101 ActionViewportViewAll: TAction;
102 ActionSystemInformation: TAction;
103 ActionOutputCopyAll: TAction;
104 ActionOutputCopySelected: TAction;
105 ActionOutputClean: TAction;
106 ActionNewSpriteSheet: TAction;
107 ActionList: TActionList;
108 BitBtnPlayStop: TBitBtn;
109 BitBtnNewView: TBitBtn;
110 LabelOpenExistingView: TLabel;
111 ListOpenExistingView: TListView;
112 MenuItem10: TMenuItem;
113 MenuItem11: TMenuItem;
114 MenuItem12: TMenuItem;
115 MenuItem15: TMenuItem;
116 MenuItem19: TMenuItem;
117 MenuItem43: TMenuItem;
118 MenuItem44: TMenuItem;
119 MenuItemRunParameterPretendTouchDevice: TMenuItem;
120 Separator14: TMenuItem;
121 MenuItem21: TMenuItem;
122 MenuItem22: TMenuItem;
123 MenuItem24: TMenuItem;
124 MenuItem27: TMenuItem;
125 MenuItem2888888: TMenuItem;
126 MenuItem28: TMenuItem;
127 MenuItem33: TMenuItem;
128 MenuItem39: TMenuItem;
129 MenuItem40: TMenuItem;
130 MenuItem41: TMenuItem;
131 MenuItem42: TMenuItem;
132 Separator13: TMenuItem;
133 Separator12: TMenuItem;
134 MenuItemRunParameterDefaultWindowOrFullscreen: TMenuItem;
135 Separator11: TMenuItem;
136 MenuItemRunParameterRequestWindow: TMenuItem;
137 MenuItemRunParameterRequestFullScreen: TMenuItem;
138 MenuItemRunParameterDisableFpsLimit: TMenuItem;
139 MenuItemRunParameterDisableSound: TMenuItem;
140 MenuItemRunParameters: TMenuItem;
141 PanelOpenExistingView: TPanel;
142 PanelNoDesign: TPanel;
143 PanelNoDesignTop: TPanel;
144 Separator9: TMenuItem;
145 MenuItem38: TMenuItem;
146 MenuItemSimulationPauseUnpause: TMenuItem;
147 MenuItemSimulationPlayStop: TMenuItem;
148 SeparatorBeforeShowColliders: TMenuItem;
149 MenuItemShowColliders: TMenuItem;
150 MenuItemPhysics: TMenuItem;
151 MenuItemCacheClean: TMenuItem;
152 MenuItemCache: TMenuItem;
153 SeparatorBeforeCache: TMenuItem;
154 MenuItemWireframe: TMenuItem;
155 MenuItem34: TMenuItem;
156 MenuItem35: TMenuItem;
157 MenuItem36: TMenuItem;
158 MenuItem37: TMenuItem;
159 Separator10: TMenuItem;
160 MenuShowJointTools28: TMenuItem;
161 MenuItem29: TMenuItem;
162 MenuItem30: TMenuItem;
163 MenuItem31: TMenuItem;
164 MenuItem32: TMenuItem;
165 Separator8: TMenuItem;
166 Separator7: TMenuItem;
167 MenuItem25: TMenuItem;
168 MenuItem26: TMenuItem;
169 Separator888888: TMenuItem;
170 WarningsPopup: TPopupMenu;
171 Separator6: TMenuItem;
172 MenuItem23: TMenuItem;
173 MenuSeparator6123: TMenuItem;
174 MenuSeparator6: TMenuItem;
175 Separator5: TMenuItem;
176 MenuItem20: TMenuItem;
177 Separator4: TMenuItem;
178 MenuItem18: TMenuItem;
179 MenuItem2: TMenuItem;
180 Separator2: TMenuItem;
181 MenuItem13: TMenuItem;
182 MenuItem14: TMenuItem;
183 Separator3: TMenuItem;
184 MenuItem16: TMenuItem;
185 MenuItem17: TMenuItem;
186 Separator1: TMenuItem;
187 MenuItem4: TMenuItem;
188 MenuItem6: TMenuItem;
189 MenuItem7: TMenuItem;
190 MenuItem8: TMenuItem;
191 MenuItemViewportViewAll: TMenuItem;
192 MenuItemViewportViewSelected: TMenuItem;
193 MenuItemViewport: TMenuItem;
194 MenuItemSystemInformation: TMenuItem;
195 MenuItemEdit: TMenuItem;
196 MenuItemOutputCopyAll: TMenuItem;
197 MenuItemOutputCopySelected: TMenuItem;
198 MenuItemSeparator12312123123: TMenuItem;
199 MenuItemOutputClean: TMenuItem;
200 MenuItemUIOutput: TMenuItem;
201 MenuItemUIWarnings: TMenuItem;
202 MenuItemUIFiles: TMenuItem;
203 MenuItemUIRestoreDefaultDockSettings: TMenuItem;
204 MenuItemEnableDisableDocking: TMenuItem;
205 MenuItemUIProperties: TMenuItem;
206 MenuItem5: TMenuItem;
207 MenuItemUIHierarchy: TMenuItem;
208 MenuItemUIExplorer: TMenuItem;
209 MenuItemUIDesign: TMenuItem;
210 MenuItem9: TMenuItem;
211 MenuItemWindow: TMenuItem;
212 MenuItemPackageFormat: TMenuItem;
213 MenuItemSeparator12312332424: TMenuItem;
214 MenuItemInstall: TMenuItem;
215 MenuItemSeparator12312131: TMenuItem;
216 MenuItemPlatform: TMenuItem;
217 MenuItemDesignNewNonVisualCustomRoot: TMenuItem;
218 MenuItemDesignNewNonVisual: TMenuItem;
219 MenuItemDesignAddNonVisual: TMenuItem;
220 MenuItemDesignAddBehavior: TMenuItem;
221 MenuItemNewCastleSpriteSheet: TMenuItem;
222 MenuItemData: TMenuItem;
223 MenuItemNewSpriteSheet: TMenuItem;
224 MenuItemSepraratorSLP002: TMenuItem;
225 ActionRegenerateProject: TAction;
226 ActionEditAssociatedUnit: TAction;
227 ActionNewUnitHereClass: TAction;
228 ActionNewUnitHereView: TAction;
229 ActionNewUnitHereEmpty: TAction;
230 ActionNewUnitHereBehavior: TAction;
231 ActionNewUnitClass: TAction;
232 ActionNewUnitView: TAction;
233 ActionNewUnitEmpty: TAction;
234 ActionNewUnitBehavior: TAction;
235 ActionEditUnit: TAction;
236 ActionOpenProjectCode: TAction;
237 ApplicationProperties1: TApplicationProperties;
238 MenuItem1: TMenuItem;
239 MenuItemRegenerateProject: TMenuItem;
240 MenuItemSeparator123123345: TMenuItem;
241 OpenPascalUnitDialog: TCastleOpenPascalUnitDialog;
242 MenuItemPopupNewUnitEmpty: TMenuItem;
243 MenuItemPopupNewUnitClass: TMenuItem;
244 MenuItemPopupNewUnitView: TMenuItem;
245 MenuItemPopupNewUnitBehavior: TMenuItem;
246 MenuItemPopupNewUnit: TMenuItem;
247 N3: TMenuItem;
248 MenuItemNewUnitView: TMenuItem;
249 MenuItemNewUnitClass: TMenuItem;
250 MenuItemNewUnitEmpty: TMenuItem;
251 MenuItemNewUnitBehavior: TMenuItem;
252 MenuItemNewUnit: TMenuItem;
253 N2: TMenuItem;
254 MenuItemEditUnitCode: TMenuItem;
255 MenuItemOpenProjectCode: TMenuItem;
256 MenuItemCode: TMenuItem;
257 MenuItemNewDirectory: TMenuItem;
258 MenuItemShellTreeSeparator13123: TMenuItem;
259 MenuItemShellTreeRefresh: TMenuItem;
260 PanelWarnings: TPanel;
261 ShellIcons: TImageList;
262 ListWarnings: TListBox;
263 MenuItemRename: TMenuItem;
264 MenuItemRedo: TMenuItem;
265 MenuItemUndo: TMenuItem;
266 MenuItemSeparator78: TMenuItem;
267 MenuItemReferenceOfCurrent: TMenuItem;
268 MenuItemRefreshDir: TMenuItem;
269 MenuItemSeparator123123213: TMenuItem;
270 MenuItemOpenDirFromFile: TMenuItem;
271 MenuItemDeleteFile: TMenuItem;
272 MenuItemOpenDefault: TMenuItem;
273 MenuItemShellTreeOpenDir: TMenuItem;
274 MenuItemPreferences: TMenuItem;
275 N1: TMenuItem;
276 MenuItemDuplicateComponent: TMenuItem;
277 MenuItemPasteComponent: TMenuItem;
278 MenuItemCopyComponent: TMenuItem;
279 MenuItemSupport: TMenuItem;
280 MenuItemSeparator788: TMenuItem;
281 MenuItemRestartRebuildEditor: TMenuItem;
282 MenuItemSeparator1300: TMenuItem;
283 MenuItemSeparator170: TMenuItem;
284 MenuItemDesignNewUserInterfaceCustomRoot: TMenuItem;
285 MenuItemDesignNewTransformCustomRoot: TMenuItem;
286 MenuItemDesignDeleteComponent: TMenuItem;
287 MenuItemDesignAddTransform: TMenuItem;
288 MenuItemDesignAddUserInterface: TMenuItem;
289 MenuItemSeparator150: TMenuItem;
290 MenuItemDesignClose: TMenuItem;
291 MenuItemDesign: TMenuItem;
292 OpenDesignDialog: TCastleOpenDialog;
293 MenuItemOpenDesign: TMenuItem;
294 MenuItemSeparator201: TMenuItem;
295 MenuItemDesignNewTransform: TMenuItem;
296 MenuItemDesignNewUserInterfaceRect: TMenuItem;
297 ShellListPopupMenu: TPopupMenu;
298 OutputPopup: TPopupMenu;
299 ShellTreePopupMenu: TPopupMenu;
300 SaveDesignDialog: TCastleSaveDialog;
301 MenuItemSaveAsDesign: TMenuItem;
302 MenuItemSaveDesign: TMenuItem;
303 ListOutput: TListBox;
304 MainMenu1: TMainMenu;
305 MenuItemSeparator101: TMenuItem;
306 MenuItemStopProcess: TMenuItem;
307 MenuItemSeprator100: TMenuItem;
308 MenuItemAutoGenerateClean: TMenuItem;
309 MenuItemAutoGenerateTextures: TMenuItem;
310 MenuItemPackageSource: TMenuItem;
311 MenuItemModeRelease: TMenuItem;
312 MenuItemPackage: TMenuItem;
313 MenuItem3: TMenuItem;
314 MenuItemModeDebug: TMenuItem;
315 MenuItemSeparator3: TMenuItem;
316 MenuItemSeparator2: TMenuItem;
317 MenuItemReference: TMenuItem;
318 MenuItemManual: TMenuItem;
319 MenuItemCgeWww: TMenuItem;
320 MenuItemAbout: TMenuItem;
321 MenuItemSeparator: TMenuItem;
322 MenuItemHelp: TMenuItem;
323 MenuItemClean: TMenuItem;
324 MenuItemOnlyRun: TMenuItem;
325 MenuItemCompileRun: TMenuItem;
326 MenuItemCompile: TMenuItem;
327 MenuItemSwitchProject: TMenuItem;
328 MenuItemRun: TMenuItem;
329 MenuItemFile: TMenuItem;
330 MenuItemQuit: TMenuItem;
331 PageControlBottom: TPageControl;
332 PanelAboveTabs: TPanel;
333 SplitterBetweenFiles: TSplitter;
334 Splitter2: TSplitter;
335 TabFiles: TTabSheet;
336 TabOutput: TTabSheet;
337 ProcessUpdateTimer: TTimer;
338 TabWarnings: TTabSheet;
339 procedure ActionCopyUrlExecute(Sender: TObject);
340 procedure ActionFindNextExecute(Sender: TObject);
341 procedure ActionFindToggleExecute(Sender: TObject);
342 procedure ActionImportSketchfabExecute(Sender: TObject);
343 procedure ActionPhysicsShowAllJointsToolsExecute(Sender: TObject);
344 procedure ActionPhysicsHideAllJointsToolsExecute(Sender: TObject);
345 procedure ActionFocusDesignExecute(Sender: TObject);
346 procedure ActionModeInteractExecute(Sender: TObject);
347 procedure ActionModeRotateExecute(Sender: TObject);
348 procedure ActionModeScaleExecute(Sender: TObject);
349 procedure ActionModeSelectExecute(Sender: TObject);
350 procedure ActionModeTranslateExecute(Sender: TObject);
351 procedure ActionPlayStopExecute(Sender: TObject);
352 procedure ActionPlayStopUpdate(Sender: TObject);
353 procedure ActionRunParameterCapabilitiesDefaultExecute(Sender: TObject);
354 procedure ActionRunParameterCapabilitiesForceFixedFunctionExecute(
355 Sender: TObject);
356 procedure ActionRunParameterCapabilitiesForceModernExecute(Sender: TObject);
357 procedure ActionRunParameterDefaultWindowOrFullscreenExecute(Sender: TObject
358 );
359 procedure ActionRunParameterDisableFpsLimitExecute(Sender: TObject);
360 procedure ActionRunParameterDisableSoundExecute(Sender: TObject);
361 procedure ActionRunParameterPretendTouchDeviceExecute(Sender: TObject);
362 procedure ActionRunParameterRequestFullScreenExecute(Sender: TObject);
363 procedure ActionRunParameterRequestWindowExecute(Sender: TObject);
364 procedure ActionShowCollidersExecute(Sender: TObject);
365 procedure ActionSimulationPauseUnpauseExecute(Sender: TObject);
366 procedure ActionSimulationPauseUnpauseUpdate(Sender: TObject);
367 procedure ActionSimulationPlayStopExecute(Sender: TObject);
368 procedure ActionSimulationPlayStopUpdate(Sender: TObject);
369 procedure ActionViewportGridAxisExecute(Sender: TObject);
370 procedure ActionComponentCutExecute(Sender: TObject);
371 procedure ActionComponentSaveSelectedExecute(Sender: TObject);
372 procedure ActionViewportAlignCameraToViewExecute(Sender: TObject);
373 procedure ActionViewportAlignViewToCameraExecute(Sender: TObject);
374 procedure ActionViewportGridAxisUpdate(Sender: TObject);
375 procedure ActionViewportRenderNextExecute(Sender: TObject);
376 procedure ActionViewportRenderNormalExecute(Sender: TObject);
377 procedure ActionViewportRenderSolidWireframeExecute(Sender: TObject);
378 procedure ActionViewportRenderWireframeOnlyExecute(Sender: TObject);
379 procedure ActionViewportToggleProjectionExecute(Sender: TObject);
380 procedure ActionNavigation2DExecute(Sender: TObject);
381 procedure ActionNavigationExamineExecute(Sender: TObject);
382 procedure ActionNavigationFlyExecute(Sender: TObject);
383 procedure ActionNavigationToggle2DExecute(Sender: TObject);
384 procedure ActionSystemInformationExecute(Sender: TObject);
385 procedure ActionOutputCleanExecute(Sender: TObject);
386 procedure ActionNewSpriteSheetExecute(Sender: TObject);
387 procedure ActionEditAssociatedUnitExecute(Sender: TObject);
388 procedure ActionEditUnitExecute(Sender: TObject);
389 procedure ActionNewUnitClassExecute(Sender: TObject);
390 procedure ActionNewUnitEmptyExecute(Sender: TObject);
391 procedure ActionNewUnitViewExecute(Sender: TObject);
392 procedure ActionNewUnitBehaviorExecute(Sender: TObject);
393 procedure ActionNewUnitHereClassExecute(Sender: TObject);
394 procedure ActionNewUnitHereEmptyExecute(Sender: TObject);
395 procedure ActionNewUnitHereViewExecute(Sender: TObject);
396 procedure ActionNewUnitHereBehaviorExecute(Sender: TObject);
397 procedure ActionOpenProjectCodeExecute(Sender: TObject);
398 procedure ActionOutputCopyAllExecute(Sender: TObject);
399 procedure ActionOutputCopySelectedExecute(Sender: TObject);
400 procedure ActionOutputCopySelectedUpdate(Sender: TObject);
401 procedure ActionRegenerateProjectExecute(Sender: TObject);
402 procedure ActionViewportBackExecute(Sender: TObject);
403 procedure ActionViewportBottomExecute(Sender: TObject);
404 procedure ActionViewportFrontExecute(Sender: TObject);
405 procedure ActionViewportLeftExecute(Sender: TObject);
406 procedure ActionViewportRightExecute(Sender: TObject);
407 procedure ActionViewportSetup2DExecute(Sender: TObject);
408 procedure ActionViewportTopExecute(Sender: TObject);
409 procedure ActionViewportViewAllExecute(Sender: TObject);
410 procedure ActionViewportViewSelectedExecute(Sender: TObject);
411 procedure ActionViewportUpdate(Sender: TObject);
412 procedure ActionWarningsCleanExecute(Sender: TObject);
413 procedure ActionWarningsCopyAllExecute(Sender: TObject);
414 procedure ActionWarningsCopySelectedExecute(Sender: TObject);
415 procedure ApplicationProperties1Activate(Sender: TObject);
416 procedure ApplicationProperties1Deactivate(Sender: TObject);
417 procedure ApplicationProperties1Exception(Sender: TObject; E: Exception);
418 procedure FormChangeBounds(Sender: TObject);
419 procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
420 procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
421 procedure FormCreate(Sender: TObject);
422 procedure FormDestroy(Sender: TObject);
423 procedure FormHide(Sender: TObject);
424 procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
425 procedure FormShow(Sender: TObject);
426 procedure ListOpenExistingViewDblClick(Sender: TObject);
427 procedure ListOutputDblClick(Sender: TObject);
428 procedure MenuItemCacheCleanClick(Sender: TObject);
429 procedure MenuItemCacheClick(Sender: TObject);
430 procedure MenuItemDesignNewNonVisualClick(Sender: TObject);
431 procedure MenuItemEnableDisableDockingClick(Sender: TObject);
432 procedure MenuItemInstallClick(Sender: TObject);
433 procedure MenuItemNewDirectoryClick(Sender: TObject);
434 procedure MenuItemRenameClick(Sender: TObject);
435 procedure MenuItemShellTreeRefreshClick(Sender: TObject);
436 procedure MenuItemUIDesignClick(Sender: TObject);
437 procedure MenuItemUIExplorerClick(Sender: TObject);
438 procedure MenuItemUIFilesClick(Sender: TObject);
439 procedure MenuItemUIHierarchyClick(Sender: TObject);
440 procedure MenuItemUIOutputClick(Sender: TObject);
441 procedure MenuItemUIPropertiesClick(Sender: TObject);
442 procedure MenuItemUIRestoreDefaultDockSettingsClick(Sender: TObject);
443 procedure MenuItemUIWarningsClick(Sender: TObject);
444 procedure UpdateUndo(Sender: TObject);
445 procedure UpdateRenameItem(Sender: TObject);
446 procedure MenuItemRedoClick(Sender: TObject);
447 procedure MenuItemUndoClick(Sender: TObject);
448 procedure MenuItemDeleteFileClick(Sender: TObject);
449 procedure MenuItemOpenDefaultClick(Sender: TObject);
450 procedure MenuItemOpenDirFromFileClick(Sender: TObject);
451 procedure MenuItemPreferencesClick(Sender: TObject);
452 procedure MenuItemAutoGenerateCleanClick(Sender: TObject);
453 procedure MenuItemAboutClick(Sender: TObject);
454 procedure MenuItemAutoGenerateTexturesClick(Sender: TObject);
455 procedure MenuItemStopProcessClick(Sender: TObject);
456 procedure MenuItemCgeWwwClick(Sender: TObject);
457 procedure MenuItemCleanClick(Sender: TObject);
458 procedure MenuItemCompileClick(Sender: TObject);
459 procedure MenuItemCompileRunClick(Sender: TObject);
460 procedure ActionCopyComponentExecute(Sender: TObject);
461 procedure MenuItemDesignCloseClick(Sender: TObject);
462 procedure ActionDeleteComponentExecute(Sender: TObject);
463 procedure ActionDuplicateComponentExecute(Sender: TObject);
464 procedure MenuItemManualClick(Sender: TObject);
465 procedure MenuItemModeDebugClick(Sender: TObject);
466 procedure MenuItemDesignNewUserInterfaceRectClick(Sender: TObject);
467 procedure MenuItemDesignNewTransformClick(Sender: TObject);
468 procedure MenuItemOnlyRunClick(Sender: TObject);
469 procedure MenuItemOpenDesignClick(Sender: TObject);
470 procedure MenuItemPackageClick(Sender: TObject);
471 procedure MenuItemPackageSourceClick(Sender: TObject);
472 procedure ActionPasteComponentExecute(Sender: TObject);
473 procedure MenuItemQuitClick(Sender: TObject);
474 procedure MenuItemReferenceClick(Sender: TObject);
475 procedure MenuItemModeReleaseClick(Sender: TObject);
476 procedure MenuItemReferenceOfCurrentClick(Sender: TObject);
477 procedure MenuItemRefreshDirClick(Sender: TObject);
478 procedure MenuItemRestartRebuildEditorClick(Sender: TObject);
479 procedure MenuItemSaveAsDesignClick(Sender: TObject);
480 procedure MenuItemSaveDesignClick(Sender: TObject);
481 procedure MenuItemShellTreeOpenDirClick(Sender: TObject);
482 procedure MenuItemSupportClick(Sender: TObject);
483 procedure MenuItemSwitchProjectClick(Sender: TObject);
484 procedure ProcessUpdateTimerTimer(Sender: TObject);
485 procedure ShellListPopupMenuPopup(Sender: TObject);
486 private
487 type
488 // Argument for RefreshFiles
489 TRefreshFiles = (
490 // only files (not directories) within current directory changed
491 rfFilesInCurrentDir,
492 // files or directories, but only within current directory (not outside) changed
493 rfEverythingInCurrentDir,
494 // everything potentially changed
495 rfEverything
496 );
497 var
498 Manifest: TCastleManifest;
499 ProjectName: String;
500 ProjectPath, ProjectPathUrl, ProjectStandaloneSource,
501 ProjectLazarus, ProjectDelphi: String;
502 BuildMode: TBuildMode;
503 OutputList: TOutputList;
504 RunningProcess: TAsynchronousProcessQueue;
505 Design: TDesignFrame;
506 DesignObserver: TFreeNotificationObserver;
507 ShellListView1: TCastleShellListView;
508 ShellTreeView1: TCastleShellTreeView;
509 ViewFileFrame: TViewFileFrame;
510 SplitterBetweenViewFile: TSplitter;
511 Docking: Boolean;
512 WantedDocking: Boolean;
513 ErrorShownRefreshFilesMissingDirectory: Boolean;
514 { Non-zero prevents the ShellListViewSelectItem from updating
515 preview window (ViewFileFrame). }
516 ShellListViewUpdating: Cardinal;
517 PlatformsInfo: TPlatformInfoList;
518 CurrentPlatformInfo: Integer; //< Index to PlatformsInfo
519 CurrentPackageFormat: TPackageFormat;
520 ListOpenExistingViewStr: TStringList;
521 { Anchor docking forms }
522 DesignForm: TForm;
523 DesignHierarchyForm: TForm;
524 DesignPropertiesForm: TForm;
525 DesignExplorerForm: TForm;
526 DesignFilesForm: TForm;
527 DesignOutputForm: TForm;
528 DesignWarningsForm: TForm;
529 procedure BuildToolCall(const Commands: array of String;
530 const RestartOnSuccess: Boolean = false);
531 procedure BuildToolCallFinished(Sender: TObject);
532 procedure ListOpenExistingViewAddFile(const FileInfo: TFileInfo;
533 var StopSearch: boolean);
534 procedure ListOpenExistingViewRefresh;
535 procedure MenuItemAddComponentClick(Sender: TObject);
536 procedure MenuItemDesignNewCustomRootClick(Sender: TObject);
537 procedure MenuItemPackageFormatChangeClick(Sender: TObject);
538 { Open Pascal file in preferred code editor.
539 Line = -1 means to not use any particular line.
540 Column = -1 means to not use any particular column. }
541 procedure OpenPascal(const FileName: String;
542 Line: Integer = -1;
543 Column: Integer = -1);
544 procedure RefreshFiles(const RefreshNecessary: TRefreshFiles);
545 procedure RefreshAllFiles(Sender: TObject);
546 (*Runs custom code editor.
547 Use this only when CodeEditor = ceCustom.
548 CustomCodeEditorCommand is the command to use (like CodeEditorCommand
549 or CodeEditorCommandProject).
550 PascalFileName will be used as ${PAS} macro value.
551 Line and Column, if not -1, will be passed as ${LINE} ${COLUMN macros. *)
552 procedure RunCustomCodeEditor(const CustomCodeEditorCommand: String;
553 const PascalFileName: String;
554 const Line: Integer = -1;
555 const Column: Integer = -1);
556 procedure IsRunningChanged;
557 procedure FreeProcess;
558 procedure RunningToggle(Sender: TObject);
559 function IsRunning: Boolean;
560 procedure ShellListViewDoubleClick(Sender: TObject);
561 procedure ShellListViewSelectItem(Sender: TObject; Item: TListItem;
562 Selected: Boolean);
563 procedure ShowNewUnitForm(const AUnitType: TNewUnitType;
564 const UnitOutputDirFromFileBrowser: Boolean);
565 function ShowStatistics: Boolean;
566 procedure UpdateFormCaption(Sender: TObject);
567 { Propose saving the hierarchy.
568 Returns should we continue (user did not cancel). }
569 function ProposeSaveDesign: Boolean;
570 { Propose saving the current design (if any) and then (unless user said "cancel")
571 open the given design URL. }
572 procedure ProposeOpenDesign(const DesignUrl: String);
573 { Call always when Design<>nil value changed. }
574 procedure DesignExistenceChanged;
575 { Create Design, if nil. }
576 procedure NeedsDesignFrame;
577 { Separated procedure to not duplicate code in various ways to create new
578 Design }
579 procedure NewDesign(const ComponentClass: TComponentClass;
580 const ComponentOnCreate: TNotifyEvent);
581 { Separated procedure to not duplicate code in various ways to open Design
582 (files view, menu) }
583 procedure OpenDesign(const DesignUrl: String);
584 procedure WarningNotification(const Category, Message: string);
585 { Clears all warnings and hides warnings tab }
586 procedure ClearAllWarnings;
587 { Update ViewFileFrame existence and visibility to show currently
588 selected item in ShellListView1. }
589 procedure ViewFileFrameUpdate;
590 procedure LoadDockLayout;
591 procedure SaveDockLayout;
592 procedure MenuItemPlatformChangeClick(Sender: TObject);
593 procedure RestartEditor(Sender: TObject);
594 procedure CurrentViewportChanged(Sender: TObject);
595 { Question about saving during physics simulation. }
596 function SaveDuringPhysicsSimulation: Boolean;
597 function IsCreatingNewDesignAvailable: Boolean;
598 procedure DesignObserverFreeNotification(const Sender: TFreeNotificationObserver);
599 public
600 { Open a project, given an absolute path to CastleEngineManifest.xml }
601 procedure OpenProject(const ManifestUrl: String);
602
603 { Can we right now add imported thing from this URL? }
604 function CanAddImported(const AddUrl: String): Boolean;
605
606 { Import URL (to instantiate it in design) now. }
607 procedure AddImported(const AddUrl: String);
608 end;
609
610 var
611 ProjectForm: TProjectForm;
612
613 implementation
614
615 {$R *.lfm}
616
617 {$warnings off} // using deprecated Castle2DSceneManager to keep it registered
618
619 uses TypInfo, LCLType, RegExpr, StrUtils, LCLVersion,
620 CastleXmlUtils, CastleLCLUtils, CastleOpenDocument, CastleUriUtils,
621 CastleFilesUtils, CastleUtils, CastleVectors, CastleColors, CastleConfig,
622 CastleScene, CastleViewport, Castle2DSceneManager, CastleCameras,
623 CastleTransform, CastleControls, CastleDownload, CastleApplicationProperties,
624 CastleLog, CastleComponentSerialize, CastleSceneCore, CastleStringUtils,
625 CastleFonts, X3DLoad, CastleFileFilters, CastleImages, CastleSoundEngine,
626 CastleLclEditHack, CastleRenderOptions, CastleTimeUtils,
627 CastleInternalFileMonitor,
628 FormAbout, FormChooseProject, FormPreferences, FormSpriteSheetEditor,
629 FormSystemInformation, FormRestartCustomEditor, FormImportSketchfab,
630 ToolCompilerInfo, ToolCommonUtils, ToolArchitectures, ToolProcess,
631 ToolFpcVersion;
632
633 {$warnings on}
634
635 {$ifdef LCLGTK2}
636 { TODO:
637 LCL on GTK2 has random crashes at TProjectForm freeing
638 (from Application.ReleaseComponents).
639 The current workaround is rather brutal but effective,
640 we let old TProjectForm instances leak (but we free Design with
641 really heavy resources),
642 and we close with Halt. }
643 {$define CASTLE_CLOSE_HACK}
644 {$endif}
645
646 procedure TProjectForm.MenuItemQuitClick(Sender: TObject);
647 begin
648 if CastleApplicationMode in [appSimulation, appSimulationPaused] then
649 begin
650 InfoBox('Stop the physics simulation to be able to close editor.');
651 Exit;
652 end;
653
654 if ProposeSaveDesign then
655 begin
656 {$ifdef CASTLE_CLOSE_HACK}
657 Halt;
658 {$else}
659 Application.Terminate;
660 {$endif}
661 end;
662 end;
663
664 procedure TProjectForm.MenuItemReferenceClick(Sender: TObject);
665 begin
666 OpenUrl(ApiReferenceUrl + 'index.html');
667 end;
668
669 procedure TProjectForm.MenuItemModeReleaseClick(Sender: TObject);
670 begin
671 BuildMode := bmRelease;
672 MenuItemModeRelease.Checked := true;
673 end;
674
675 procedure TProjectForm.MenuItemReferenceOfCurrentClick(Sender: TObject);
676 var
677 Url: String;
678 begin
679 Url := ApiReferenceUrl + 'index.html';
680 if Design <> nil then
681 Design.CurrentComponentApiUrl(Url);
682 OpenUrl(Url);
683 end;
684
685 procedure TProjectForm.MenuItemRefreshDirClick(Sender: TObject);
686 begin
687 RefreshFiles(rfEverythingInCurrentDir);
688 end;
689
690 procedure TProjectForm.MenuItemRestartRebuildEditorClick(Sender: TObject);
691 begin
692 BuildToolCall(['editor-rebuild-if-needed'], true);
693 end;
694
695 procedure TProjectForm.MenuItemSaveAsDesignClick(Sender: TObject);
696 begin
697 if not SaveDuringPhysicsSimulation then
698 Exit;
699
700 Assert(Design <> nil); // menu item is disabled otherwise
701 PrepareSaveDesignDialog(SaveDesignDialog, Design.DesignRoot);
702 SaveDesignDialog.Url := Design.DesignUrl;
703 if SaveDesignDialog.Execute then
704 begin
705 Design.SaveDesign(SaveDesignDialog.Url);
706 // TODO: save DesignUrl somewhere? CastleEditorSettings.xml?
707
708 // make sure to show new file in "Files" in editor
709 RefreshFiles(rfFilesInCurrentDir);
710 end;
711
712 { On GTK, this happens when we open a dialog box, like open/save.
713 It's important to stop treating keys/mouse as pressed then.
714
715 Testcase:
716 - Make new design,
717 - add 3D viewport,
718 - press right mouse button and S (to move back),
719 - press Ctrl (invokes Save dialog),
720 - release all keys, press "Cancel",
721 -> without this line, TCastleControl would think "S" key is still down.
722
723 Note:
724 - TCastleControl.DoExit is not called in this case.
725 - Form OnDeactive is also not called (matches docs on
726 https://wiki.lazarus.freepascal.org/Event_order#Form.OnDeactivate ).
727 - ApplicationProperties1Deactivate is not effective workaround for this
728 (workarounds "open" but not "save" testcase for some reason,
729 maybe because of "S" and Ctrl+S interaction).
730 }
731 Design.ReleaseAllKeysAndMouse;
732 end;
733
734 procedure TProjectForm.MenuItemSaveDesignClick(Sender: TObject);
735 begin
736 if not SaveDuringPhysicsSimulation then
737 Exit;
738
739 Assert(Design <> nil); // menu item is disabled otherwise
740
741 if Design.DesignUrl = '' then
742 MenuItemSaveAsDesignClick(Sender)
743 else
744 begin
745 Design.SaveDesign(Design.DesignUrl);
746
747 // make sure to show new file in "Files" in editor
748 RefreshFiles(rfFilesInCurrentDir);
749 end;
750 end;
751
752 procedure TProjectForm.MenuItemShellTreeOpenDirClick(Sender: TObject);
753 var
754 Dir: String;
755 begin
756 if ShellTreeView1.Selected <> nil then
757 begin
758 Dir := ShellTreeView1.GetPathFromNode(ShellTreeView1.Selected);
759 OpenDocument(Dir);
760 end;
761 end;
762
763 procedure TProjectForm.MenuItemSupportClick(Sender: TObject);
764 begin
765 OpenUrl('https://patreon.com/castleengine/');
766 end;
767
768 procedure TProjectForm.MenuItemCgeWwwClick(Sender: TObject);
769 begin
770 OpenUrl('https://castle-engine.io/');
771 end;
772
773 procedure TProjectForm.MenuItemAboutClick(Sender: TObject);
774 begin
775 AboutForm.ShowModal;
776 end;
777
778 procedure TProjectForm.MenuItemAutoGenerateTexturesClick(Sender: TObject);
779 begin
780 BuildToolCall(['auto-generate-textures']);
781 end;
782
783 procedure TProjectForm.MenuItemStopProcessClick(Sender: TObject);
784 begin
785 if RunningProcess = nil then
786 raise EInternalError.Create('No process is running now');
787
788 OutputList.AddSeparator;
789 OutputList.AddLine('Stopping the process.', okInfo);
790 RunningProcess.TerminateChildrenHarder;
791 FreeProcess;
792 end;
793
794 procedure TProjectForm.FormCloseQuery(Sender: TObject; var CanClose: boolean);
795
796 function HandleNonModalAssociatedForm(Form: TForm): Boolean;
797 begin
798 Result := true;
799 if (Form <> nil) and Form.Visible then
800 begin
801 if not Form.CloseQuery then
802 begin
803 CanClose := false;
804 Exit(false);
805 end;
806 end;
807 end;
808
809 begin
810 if CastleApplicationMode in [appSimulation, appSimulationPaused] then
811 begin
812 InfoBox('Stop the physics simulation to be able to turn off the editor.');
813 CanClose := false;
814 Exit;
815 end;
816
817 if ProposeSaveDesign then
818 begin
819 { Close associated windows if visible }
820 if not HandleNonModalAssociatedForm(SpriteSheetEditorForm) then
821 begin
822 CanClose := false;
823 Exit;
824 end;
825 if not HandleNonModalAssociatedForm(ImportSketchfabForm) then
826 begin
827 CanClose := false;
828 Exit;
829 end;
830
831 Application.Terminate;
832 end else
833 CanClose := false;
834 end;
835
836 procedure TProjectForm.FormClose(Sender: TObject; var CloseAction: TCloseAction);
837 begin
838 SaveDockLayout;
839 {$ifdef CASTLE_CLOSE_HACK}
840 // TODO: Hack to avoid LCL crashes. Memory will leak
841 // (trying to manually free ProjectForm from ChooseProjectForm would also crash).
842 CloseAction := caHide;
843 {$endif}
844 end;
845
846 procedure TProjectForm.ActionNewSpriteSheetExecute(Sender: TObject);
847 begin
848 if SpriteSheetEditorForm = nil then
849 SpriteSheetEditorForm := TSpriteSheetEditorForm.Create(Application);
850
851 SpriteSheetEditorForm.Show;
852 SpriteSheetEditorForm.NewSpriteSheet;
853 end;
854
855 procedure TProjectForm.ActionOutputCleanExecute(Sender: TObject);
856 begin
857 ListOutput.Clear;
858 end;
859
860 procedure TProjectForm.ActionSystemInformationExecute(Sender: TObject);
861 begin
862 if SystemInformationForm = nil then
863 SystemInformationForm := TSystemInformationForm.Create(Application);
864 SystemInformationForm.Show;
865 end;
866
867 procedure TProjectForm.ActionNavigationToggle2DExecute(Sender: TObject);
868 begin
869 if (Design <> nil) and (Design.CurrentViewport <> nil) then
870 begin
871 { This comparison also determines what happens if current navigation
872 is neither 2D, nor Fly.
873 In this case we want to switch to 2D, because all other navigations
874 are more 3D. }
875 if Design.CurrentViewport.InternalDesignNavigationType = dn2D then
876 begin
877 Design.CurrentViewport.InternalDesignNavigationType := dnFly;
878 ActionNavigationFly.Checked := true;
879 end else
880 begin
881 Design.CurrentViewport.InternalDesignNavigationType := dn2D;
882 ActionNavigation2D.Checked := true;
883 end;
884 end;
885 end;
886
887 procedure TProjectForm.ActionNavigationFlyExecute(Sender: TObject);
888 begin
889 if (Design <> nil) and (Design.CurrentViewport <> nil) then
890 begin
891 Design.CurrentViewport.InternalDesignNavigationType := dnFly;
892 ActionNavigationFly.Checked := true;
893 end;
894 end;
895
896 procedure TProjectForm.ActionNavigation2DExecute(Sender: TObject);
897 begin
898 if (Design <> nil) and (Design.CurrentViewport <> nil) then
899 begin
900 Design.CurrentViewport.InternalDesignNavigationType := dn2D;
901 ActionNavigation2D.Checked := true;
902 end;
903 end;
904
905 procedure TProjectForm.ActionNavigationExamineExecute(Sender: TObject);
906 begin
907 if (Design <> nil) and (Design.CurrentViewport <> nil) then
908 begin
909 Design.CurrentViewport.InternalDesignNavigationType := dnExamine;
910 ActionNavigationExamine.Checked := true;
911 end;
912 end;
913
914 procedure TProjectForm.ActionViewportToggleProjectionExecute(Sender: TObject);
915 begin
916 if Design <> nil then
917 Design.ViewportToggleProjection;
918 end;
919
920 procedure TProjectForm.ActionViewportAlignViewToCameraExecute(Sender: TObject);
921 begin
922 if Design <> nil then
923 Design.ViewportAlignViewToCamera;
924 end;
925
926 procedure TProjectForm.ActionViewportGridAxisUpdate(Sender: TObject);
927 begin
928 ActionViewportGridAxis.Checked :=
929 (Design <> nil) and
930 (Design.CurrentViewport <> nil) and
931 Design.CurrentViewport.InternalGridAxis;
932 ActionViewportUpdate(Sender);
933 end;
934
935 procedure TProjectForm.ActionViewportRenderNextExecute(Sender: TObject);
936 begin
937 case InternalForceWireframe of
938 weNormal : ActionViewportRenderWireframeOnlyExecute(nil);
939 weWireframeOnly : ActionViewportRenderSolidWireframeExecute(nil);
940 weSolidWireframe: ActionViewportRenderNormalExecute(nil);
941 else
942 begin
943 WritelnWarning('Unexpected InternalForceWireframe value');
944 ActionViewportRenderWireframeOnlyExecute(nil);
945 end;
946 end;
947 end;
948
949 procedure TProjectForm.ActionViewportRenderNormalExecute(Sender: TObject);
950 begin
951 InternalForceWireframe := weNormal;
952 ActionViewportRenderNormal.Checked := true;
953 end;
954
955 procedure TProjectForm.ActionViewportRenderSolidWireframeExecute(Sender: TObject);
956 begin
957 InternalForceWireframe := weSolidWireframe;
958 ActionViewportRenderSolidWireframe.Checked := true;
959 end;
960
961 procedure TProjectForm.ActionViewportRenderWireframeOnlyExecute(Sender: TObject);
962 begin
963 InternalForceWireframe := weWireframeOnly;
964 ActionViewportRenderWireframeOnly.Checked := true;
965 end;
966
967 procedure TProjectForm.ActionViewportAlignCameraToViewExecute(Sender: TObject);
968 begin
969 if Design <> nil then
970 Design.ViewportAlignCameraToView;
971 end;
972
973 procedure TProjectForm.ActionComponentCutExecute(Sender: TObject);
974 begin
975 Assert(Design <> nil); // menu item is disabled otherwise
976 Design.CutComponent;
977 end;
978
979 procedure TProjectForm.ActionViewportGridAxisExecute(Sender: TObject);
980 begin
981 if (Design <> nil) and (Design.CurrentViewport <> nil) then
982 Design.CurrentViewport.InternalGridAxis := not Design.CurrentViewport.InternalGridAxis;
983 end;
984
985 procedure TProjectForm.ActionPhysicsShowAllJointsToolsExecute(Sender: TObject);
986 begin
987 Assert(Design <> nil); // menu item is disabled otherwise
988 Design.ShowAllJointsTools;
989 end;
990
991 procedure TProjectForm.ActionImportSketchfabExecute(Sender: TObject);
992 begin
993 if ImportSketchfabForm = nil then
994 ImportSketchfabForm := TImportSketchfabForm.Create(Application);
995
996 ImportSketchfabForm.ProjectPath := ProjectPath;
997 ImportSketchfabForm.OnRefreshFiles := @RefreshAllFiles;
998 ImportSketchfabForm.OnCanAddImported := @CanAddImported;
999 ImportSketchfabForm.OnAddImported := @AddImported;
1000 ImportSketchfabForm.Show;
1001 end;
1002
1003 procedure TProjectForm.ActionFindNextExecute(Sender: TObject);
1004 begin
1005 Assert(Design <> nil); // menu item is disabled otherwise
1006 Design.FindNext;
1007 end;
1008
1009 procedure TProjectForm.ActionCopyUrlExecute(Sender: TObject);
1010 var
1011 SelectedFileName, Url: String;
1012 begin
1013 if ShellListView1.Selected <> nil then
1014 begin
1015 SelectedFileName := ShellListView1.GetPathFromItem(ShellListView1.Selected);
1016 Url := FilenameToUriSafe(SelectedFileName);
1017 Url := MaybeUseDataProtocol(Url);
1018 Clipboard.AsText := Url;
1019 end;
1020 end;
1021
1022 procedure TProjectForm.ActionFindToggleExecute(Sender: TObject);
1023 begin
1024 Assert(Design <> nil); // menu item is disabled otherwise
1025
1026 // TODO: Make it a checked action, toggle checked state,
1027 // synchronize with design (also when it's closed).
1028
1029 Design.FindToggle;
1030 end;
1031
1032 procedure TProjectForm.ActionPhysicsHideAllJointsToolsExecute(Sender: TObject);
1033 begin
1034 Assert(Design <> nil); // menu item is disabled otherwise
1035 Design.HideAllJointsTools;
1036 end;
1037
1038 procedure TProjectForm.ActionFocusDesignExecute(Sender: TObject);
1039 begin
1040 Assert(Design <> nil); // menu item is disabled otherwise
1041 Design.FocusDesign;
1042 end;
1043
1044 procedure TProjectForm.ActionModeInteractExecute(Sender: TObject);
1045 begin
1046 Assert(Design <> nil); // menu item is disabled otherwise
1047 Design.ChangeMode(moInteract);
1048 end;
1049
1050 procedure TProjectForm.ActionModeRotateExecute(Sender: TObject);
1051 begin
1052 Assert(Design <> nil); // menu item is disabled otherwise
1053 Design.ChangeMode(moRotate);
1054 end;
1055
1056 procedure TProjectForm.ActionModeScaleExecute(Sender: TObject);
1057 begin
1058 Assert(Design <> nil); // menu item is disabled otherwise
1059 Design.ChangeMode(moScale);
1060 end;
1061
1062 procedure TProjectForm.ActionModeSelectExecute(Sender: TObject);
1063 begin
1064 Assert(Design <> nil); // menu item is disabled otherwise
1065 Design.ChangeMode(moSelect);
1066 end;
1067
1068 procedure TProjectForm.ActionModeTranslateExecute(Sender: TObject);
1069 begin
1070 Assert(Design <> nil); // menu item is disabled otherwise
1071 Design.ChangeMode(moTranslate);
1072 end;
1073
1074 procedure TProjectForm.ActionPlayStopExecute(Sender: TObject);
1075 begin
1076 RunningToggle(Sender);
1077 end;
1078
1079 procedure TProjectForm.ActionPlayStopUpdate(Sender: TObject);
1080 var
1081 NowIsRunning: Boolean;
1082 begin
1083 NowIsRunning := IsRunning;
1084 if NowIsRunning then
1085 ActionPlayStop.ImageIndex := TImageIndex(iiStop)
1086 else
1087 ActionPlayStop.ImageIndex := TImageIndex(iiPlay);
1088 ActionPlayStop.Checked := NowIsRunning;
1089
1090 BitBtnPlayStop.ImageIndex := ActionPlayStop.ImageIndex;
1091 if NowIsRunning then
1092 begin
1093 BitBtnPlayStop.Caption := 'Stop';
1094 BitBtnPlayStop.Hint := 'Break Compilation or Run (Ctrl + F2)';
1095 end else
1096 begin
1097 BitBtnPlayStop.Caption := 'Compile and Run';
1098 BitBtnPlayStop.Hint := 'Compile and Run (F9)';
1099 end;
1100 //BitBtnPlayStop.Checked := NowIsRunning;
1101 end;
1102
1103 procedure TProjectForm.ActionRunParameterCapabilitiesDefaultExecute(
1104 Sender: TObject);
1105 begin
1106 (Sender as TAction).Checked := true; // GroupIndex will make others unselected
1107 end;
1108
1109 procedure TProjectForm.ActionRunParameterCapabilitiesForceFixedFunctionExecute(
1110 Sender: TObject);
1111 begin
1112 (Sender as TAction).Checked := true; // GroupIndex will make others unselected
1113 end;
1114
1115 procedure TProjectForm.ActionRunParameterCapabilitiesForceModernExecute(
1116 Sender: TObject);
1117 begin
1118 (Sender as TAction).Checked := true; // GroupIndex will make others unselected
1119 end;
1120
1121 procedure TProjectForm.ActionRunParameterDefaultWindowOrFullscreenExecute(
1122 Sender: TObject);
1123 begin
1124 (Sender as TAction).Checked := true; // GroupIndex will make others unselected
1125 end;
1126
1127 procedure TProjectForm.ActionRunParameterDisableFpsLimitExecute(Sender: TObject);
1128 begin
1129 (Sender as TAction).Checked := not (Sender as TAction).Checked;
1130 end;
1131
1132 procedure TProjectForm.ActionRunParameterDisableSoundExecute(Sender: TObject);
1133 begin
1134 (Sender as TAction).Checked := not (Sender as TAction).Checked;
1135 end;
1136
1137 procedure TProjectForm.ActionRunParameterPretendTouchDeviceExecute(
1138 Sender: TObject);
1139 begin
1140 (Sender as TAction).Checked := not (Sender as TAction).Checked;
1141 end;
1142
1143 procedure TProjectForm.ActionRunParameterRequestFullScreenExecute(
1144 Sender: TObject);
1145 begin
1146 (Sender as TAction).Checked := true; // GroupIndex will make others unselected
1147 end;
1148
1149 procedure TProjectForm.ActionRunParameterRequestWindowExecute(Sender: TObject);
1150 begin
1151 (Sender as TAction).Checked := true; // GroupIndex will make others unselected
1152 end;
1153
1154 procedure TProjectForm.ActionShowCollidersExecute(Sender: TObject);
1155 begin
1156 Assert(Design <> nil); // menu item is disabled otherwise
1157 Design.ShowColliders := not Design.ShowColliders;
1158 ActionShowColliders.Checked := Design.ShowColliders;
1159 end;
1160
1161 procedure TProjectForm.ActionSimulationPauseUnpauseExecute(Sender: TObject);
1162 begin
1163 Assert(Design <> nil);
1164 Design.SimulationPauseUnpause;
1165 end;
1166
1167 procedure TProjectForm.ActionSimulationPauseUnpauseUpdate(Sender: TObject);
1168 begin
1169 ActionSimulationPauseUnpause.Enabled := (Design <> nil) and
1170 (CastleApplicationMode in [appSimulation, appSimulationPaused]);
1171 ActionSimulationPauseUnpause.Checked := (Design <> nil) and
1172 (CastleApplicationMode = appSimulationPaused);
1173 end;
1174
1175 procedure TProjectForm.ActionSimulationPlayStopExecute(Sender: TObject);
1176 begin
1177 Assert(Design <> nil);
1178 Design.SimulationPlayStop;
1179 end;
1180
1181 procedure TProjectForm.ActionSimulationPlayStopUpdate(Sender: TObject);
1182 begin
1183 ActionSimulationPlayStop.Enabled := Design <> nil;
1184 ActionSimulationPlayStop.Checked := (Design <> nil) and
1185 (CastleApplicationMode in [appSimulation, appSimulationPaused]);
1186 end;
1187
1188 procedure TProjectForm.ActionComponentSaveSelectedExecute(Sender: TObject);
1189 begin
1190 Assert(Design <> nil); // menu item is disabled otherwise
1191 Design.SaveSelected;
1192 end;
1193
1194 procedure TProjectForm.ApplicationProperties1Activate(Sender: TObject);
1195 begin
1196 { TODO: At least on Linux, GTK2 backend, this is *not* reliably
1197 run always when we switch back to CGE editor with Alt+Tab.
1198 This in turn means we don't always auto-reload scenes, images etc.
1199 when their content changed.
1200 WritelnLog('TProjectForm.ApplicationProperties1Activate ' + FormatDateTime('yyyy"-"mm"-"dd" "tt', Now));
1201 }
1202
1203 { Refresh contents of selected dir, and tree of subdirectories,
1204 in case user created some files/directories in other applications. }
1205 RefreshFiles(rfEverything);
1206 FileMonitor.CheckChanges;
1207 end;
1208
1209 procedure TProjectForm.ApplicationProperties1Deactivate(Sender: TObject);
1210 begin
1211 { On GTK, this happens when we open a dialog box, like open/save.
1212 It's important to stop treating keys/mouse as pressed then.
1213
1214 Testcase:
1215 - Make new design,
1216 - add 3D viewport,
1217 - press right mouse button and W (to move forward),
1218 - release mouse,
1219 - press Ctrl+O (invokes Open dialog),
1220 - release all keys, press "Cancel",
1221 -> without this line, TCastleControl would think "W" key is still down.
1222
1223 Note: TCastleControl.DoExit is not called in this case.
1224 Form OnDeactive is also not called (matches docs on
1225 https://wiki.lazarus.freepascal.org/Event_order#Form.OnDeactivate ).
1226 }
1227
1228 if Design <> nil then
1229 Design.ReleaseAllKeysAndMouse;
1230 end;
1231
1232 procedure TProjectForm.ActionOpenProjectCodeExecute(Sender: TObject);
1233 var
1234 Exe, DelphiExe: String;
1235 Ce: TCodeEditor;
1236 begin
1237 if CodeEditor = ceAutodetect then
1238 Ce := AutodetectCodeEditor
1239 else
1240 Ce := CodeEditor;
1241
1242 case Ce of
1243 ceCustom:
1244 begin
1245 if CodeEditorCommandProject <> '' then
1246 RunCustomCodeEditor(CodeEditorCommandProject, '')
1247 else
1248 if ProjectStandaloneSource <> '' then
1249 RunCustomCodeEditor(CodeEditorCommand, ProjectStandaloneSource)
1250 else
1251 { We should not really pass directory name
1252 as PascalFileName to RunCustomCodeEditor,
1253 but in this case we kind of have no choice: we want to run custom editor
1254 with something. }
1255 RunCustomCodeEditor(CodeEditorCommand, ProjectPath);
1256 end;
1257 ceLazarus:
1258 begin
1259 Exe := FindExeLazarusIDE;
1260
1261 { Open through LPI to change the project. }
1262 if ProjectLazarus <> '' then
1263 RunCommandNoWait(CreateTemporaryDir, Exe, [ProjectLazarus])
1264 else
1265 ErrorBox('Lazarus project not defined (neither "standalone_source" nor "lazarus_project" were specified in CastleEngineManifest.xml).' + NL +
1266 NL +
1267 'Create Lazarus project (e.g. by "castle-engine generate-program") and update CastleEngineManifest.xml.');
1268 end;
1269 ceDelphi:
1270 begin
1271 FindDelphiPath(true, DelphiExe);
1272
1273 { Open through DPROJ, this seems to be the only thing that works reliably. }
1274 if ProjectDelphi = '' then
1275 begin
1276 ErrorBox('Delphi project not defined (neither "standalone_source" nor "delphi_project" were specified in CastleEngineManifest.xml).' + NL +
1277 NL +
1278 'Create Delphi project (e.g. by "castle-engine generate-program") and update CastleEngineManifest.xml.');
1279 Exit;
1280 end;
1281 if not RegularFileExists(ProjectDelphi) then
1282 begin
1283 ErrorBox(Format('Delphi project file does not exist: %s.' + NL +
1284 NL +
1285 'Create Delphi project (by "castle-engine generate-program" or using Delphi).', [
1286 ProjectDelphi
1287 ]));
1288 Exit;
1289 end;
1290
1291 {$ifdef DELPHI_OPEN_SHELL}
1292 OpenDocument(ProjectDelphi); // hack to open Pascal names in existing Delphi window, using DDE
1293 {$else}
1294 RunCommandNoWait(ProjectPath, DelphiExe, [
1295 ProjectDelphi
1296 //ProjectStandaloneSource
1297 ]);
1298 {$endif}
1299 end;
1300 ceVSCode:
1301 begin
1302 Exe := FindExeVSCode(true);
1303 RunCommandNoWait(ProjectPath, Exe, [
1304 { --add would add project to workspace in current window.
1305 See OpenPascal for comments. }
1306 //'--add',
1307
1308 { We pass relative filenames, not absolute, to avoid
1309 VS Code on Windows inability to deal with spaces in filenames.
1310 See OpenPascal for comments. }
1311 '.'
1312 ], [rcNoConsole]);
1313 end;
1314 else raise EInternalError.Create('CodeEditor?');
1315 end;
1316 end;
1317
1318 procedure TProjectForm.ActionOutputCopyAllExecute(Sender: TObject);
1319 begin
1320 Clipboard.AsText := ListOutput.Items.Text;
1321 end;
1322
1323 procedure TProjectForm.ActionOutputCopySelectedExecute(Sender: TObject);
1324 begin
1325 Clipboard.AsText := ListOutput.GetSelectedText;
1326 end;
1327
1328 procedure TProjectForm.ActionOutputCopySelectedUpdate(Sender: TObject);
1329 begin
1330 (Sender as TAction).Enabled := ListOutput.SelCount <> 0;
1331 end;
1332
1333 procedure TProjectForm.ActionRegenerateProjectExecute(Sender: TObject);
1334 begin
1335 BuildToolCall(['generate-program']);
1336 end;
1337
1338 procedure TProjectForm.ActionViewportBackExecute(Sender: TObject);
1339 begin
1340 if Design <> nil then
1341 Design.ViewportViewAxis(Vector3(0, 0, 1), Vector3(0, 1, 0));
1342 end;
1343
1344 procedure TProjectForm.ActionViewportBottomExecute(Sender: TObject);
1345 begin
1346 if Design <> nil then
1347 Design.ViewportViewAxis(Vector3(0, 1, 0), Vector3(0, 0, -1));
1348 end;
1349
1350 procedure TProjectForm.ActionViewportFrontExecute(Sender: TObject);
1351 begin
1352 if Design <> nil then
1353 Design.ViewportViewAxis(Vector3(0, 0, -1), Vector3(0, 1, 0));
1354 end;
1355
1356 procedure TProjectForm.ActionViewportLeftExecute(Sender: TObject);
1357 begin
1358 if Design <> nil then
1359 Design.ViewportViewAxis(Vector3(1, 0, 0), Vector3(0, 1, 0));
1360 end;
1361
1362 procedure TProjectForm.ActionViewportRightExecute(Sender: TObject);
1363 begin
1364 if Design <> nil then
1365 Design.ViewportViewAxis(Vector3(-1, 0, 0), Vector3(0, 1, 0));
1366 end;
1367
1368 procedure TProjectForm.ActionViewportSetup2DExecute(Sender: TObject);
1369 begin
1370 if Design <> nil then
1371 Design.ViewportSetup2D;
1372 end;
1373
1374 procedure TProjectForm.ActionViewportTopExecute(Sender: TObject);
1375 begin
1376 if Design <> nil then
1377 { up -Z better than up +Z: makes more natural rotation when using 1/3/7 }
1378 Design.ViewportViewAxis(Vector3(0, -1, 0), Vector3(0, 0, -1));
1379 end;
1380
1381 procedure TProjectForm.ActionViewportViewAllExecute(Sender: TObject);
1382 begin
1383 if Design <> nil then
1384 Design.ViewportViewAll;
1385 end;
1386
1387 procedure TProjectForm.ActionViewportViewSelectedExecute(Sender: TObject);
1388 begin
1389 if Design <> nil then
1390 Design.ViewportViewSelected;
1391 end;
1392
1393 procedure TProjectForm.ActionViewportUpdate(Sender: TObject);
1394 var
1395 ViewportActionsAllowed: Boolean;
1396 begin
1397 ViewportActionsAllowed := (Design <> nil) and (Design.CurrentViewport <> nil);
1398 (Sender as TAction).Enabled := ViewportActionsAllowed;
1399 // MenuItemViewport.Enabled := ViewportActionsAllowed; // TODO would disable everything without ability to restore
1400 end;
1401
1402 procedure TProjectForm.ActionWarningsCleanExecute(Sender: TObject);
1403 begin
1404 ClearAllWarnings;
1405 end;
1406
1407 procedure TProjectForm.ActionWarningsCopyAllExecute(Sender: TObject);
1408 begin
1409 Clipboard.AsText := ListWarnings.Items.Text;
1410 end;
1411
1412 procedure TProjectForm.ActionWarningsCopySelectedExecute(Sender: TObject);
1413 //var
1414 // S: String;
1415 begin
1416 Clipboard.AsText := ListWarnings.GetSelectedText;
1417 //S := '';
1418 //for I := 0 to ListWarnings.SelCount - 1 do
1419 // S := SAppendPart(S, NL, ListWarnings.Selected[I]);
1420 //Clipboard.AsText := S;
1421 end;
1422
1423 procedure TProjectForm.ActionEditUnitExecute(Sender: TObject);
1424 begin
1425 if OpenPascalUnitDialog.Execute then
1426 OpenPascal(OpenPascalUnitDialog.FileName);
1427 end;
1428
1429 procedure TProjectForm.ActionEditAssociatedUnitExecute(Sender: TObject);
1430 var
1431 AUnitName, UnitFileNameAbsolute: String;
1432 begin
1433 AUnitName := DeleteUriExt(ExtractUriName(Design.DesignUrl));
1434 UnitFileNameAbsolute := Manifest.SearchPascalUnit(AUnitName);
1435 if UnitFileNameAbsolute <> '' then
1436 OpenPascal(UnitFileNameAbsolute)
1437 else
1438 ErrorBox('Cannot find Pascal unit ' + AUnitName + ' (filename like "' + AUnitName + '.pas") among the search paths listed in CastleEngineManifest.xml');
1439 end;
1440
1441 procedure TProjectForm.ActionNewUnitClassExecute(Sender: TObject);
1442 begin
1443 ShowNewUnitForm(utClass, false);
1444 end;
1445
1446 procedure TProjectForm.ActionNewUnitEmptyExecute(Sender: TObject);
1447 begin
1448 ShowNewUnitForm(utEmpty, false);
1449 end;
1450
1451 procedure TProjectForm.ActionNewUnitViewExecute(Sender: TObject);
1452 begin
1453 ShowNewUnitForm(utView, false);
1454 end;
1455
1456 procedure TProjectForm.ActionNewUnitBehaviorExecute(Sender: TObject);
1457 begin
1458 ShowNewUnitForm(utBehavior, false);
1459 end;
1460
1461 procedure TProjectForm.ActionNewUnitHereClassExecute(Sender: TObject);
1462 begin
1463 ShowNewUnitForm(utClass, true);
1464 end;
1465
1466 procedure TProjectForm.ActionNewUnitHereEmptyExecute(Sender: TObject);
1467 begin
1468 ShowNewUnitForm(utEmpty, true);
1469 end;
1470
1471 procedure TProjectForm.ActionNewUnitHereViewExecute(Sender: TObject);
1472 begin
1473 ShowNewUnitForm(utView, true);
1474 end;
1475
1476 procedure TProjectForm.ActionNewUnitHereBehaviorExecute(Sender: TObject);
1477 begin
1478 ShowNewUnitForm(utBehavior, true);
1479 end;
1480
1481 procedure TProjectForm.ShowNewUnitForm(const AUnitType: TNewUnitType;
1482 const UnitOutputDirFromFileBrowser: Boolean);
1483
1484 { Check if unit is on search path, as we don't edit CastleEngineManifest.xml
1485 search paths automatically now. }
1486 procedure CheckNewUnitOnSearchPath;
1487 var
1488 UnitBaseName: String;
1489 begin
1490 if NewUnitForm.CreatedUnitRelative <> '' then
1491 begin
1492 UnitBaseName := DeleteFileExt(ExtractFileName(NewUnitForm.CreatedUnitRelative));
1493 if Manifest.SearchPascalUnit(UnitBaseName) = '' then
1494 begin
1495 WarningBox(Format('Created unit "%s" not found on the search path. Make sure that subdirectory "%s" is listed among search paths inside CastleEngineManifest.xml.', [
1496 NewUnitForm.CreatedUnitRelative,
1497 ExtractFilePath(NewUnitForm.CreatedUnitRelative)
1498 ]));
1499 end;
1500 end;
1501 end;
1502
1503 { Propose to open design or unit code immediately. }
1504 procedure ProposeToOpenNewFile;
1505 begin
1506 if NewUnitForm.CreatedDesignRelative <> '' then
1507 begin
1508 Assert(NewUnitForm.CreatedUnitRelative <> '');
1509 if YesNoBox('Open design', Format(
1510 'Created unit: %s' + NL +
1511 NL +
1512 'Created user interface design: %s' + NL +
1513 NL +
1514 'Open the user interface design now?', [
1515 NewUnitForm.CreatedUnitRelative,
1516 NewUnitForm.CreatedDesignRelative
1517 ])) then
1518 OpenDesign(NewUnitForm.CreatedDesignAbsolute);
1519 end else
1520 if NewUnitForm.CreatedUnitRelative <> '' then
1521 begin
1522 if YesNoBox('Edit unit', Format(
1523 'Created unit: %s' + NL +
1524 NL +
1525 'Edit the unit code now?', [
1526 NewUnitForm.CreatedUnitRelative
1527 ])) then
1528 OpenPascal(NewUnitForm.CreatedUnitAbsolute);
1529 end;
1530 end;
1531
1532 var
1533 UnitOutputPath: String;
1534 begin
1535 { calculate UnitOutputPath }
1536 if UnitOutputDirFromFileBrowser then
1537 begin
1538 UnitOutputPath := ShellListView1.Root;
1539 end else
1540 begin
1541 { place code in code/ subdirectory, if possible }
1542 UnitOutputPath := CombinePaths(Manifest.Path, 'code');
1543 if not DirectoryExists(UnitOutputPath) then
1544 UnitOutputPath := Manifest.Path;
1545 end;
1546 UnitOutputPath := InclPathDelim(UnitOutputPath);
1547
1548 NewUnitForm.InitializeUi(AUnitType, UnitOutputPath, Manifest);
1549
1550 if NewUnitForm.ShowModal = mrOK then
1551 begin
1552 ListOpenExistingViewRefresh;
1553 CheckNewUnitOnSearchPath;
1554 ProposeToOpenNewFile;
1555 RefreshFiles(rfEverything); // NewUnitForm maybe created dirs
1556 end;
1557 end;
1558
1559 function TProjectForm.ShowStatistics: Boolean;
1560 begin
1561 Result := ActionShowStatistics.Checked;
1562 end;
1563
1564 procedure TProjectForm.ApplicationProperties1Exception(Sender: TObject;
1565 E: Exception);
1566 begin
1567 { In case of CGE editor, exceptions are nothing alarming.
1568
1569 We may raise exception during normal execution e.g.
1570 - when you try to do invalid file operation (creating dir with invalid name,
1571 deleting something to which you have no permission),
1572 - renaming component to invalid value,
1573 - in general doing anything that causes exception in FPC or CGE code.
1574
1575 So display a normal dialog box about them, user-friendly
1576 (don't even show exception class for now),
1577 instead of the default LCL dialog that proposes to kill the application. }
1578 ErrorBox(E.Message);
1579 end;
1580
1581 procedure TProjectForm.FormChangeBounds(Sender: TObject);
1582 begin
1583 { Update inspector data for property editors needed by color pick to show in
1584 right position. }
1585 if Design <> nil then
1586 Design.UpdateEditorDataForPropertyEditors;
1587 end;
1588
1589 procedure TProjectForm.LoadDockLayout;
1590 var
1591 XMLConfig: TXMLConfigStorage;
1592 Site: TAnchorDockHostSite;
1593 URLFileName: String;
1594 begin
1595 if not Docking then Exit;
1596 URLFileName := ApplicationConfig(DockLayoutFileName);
1597 { Try to load default layout if user layout is not exist }
1598 if not UriFileExists(URLFileName) then
1599 URLFileName := InternalCastleDesignData + 'layouts/' + DockLayoutFileNameDefault;
1600 try
1601 XMLConfig := TXMLConfigStorage.Create(UriToFilenameSafe(URLFileName), True);
1602 try
1603 DockMaster.LoadLayoutFromConfig(XMLConfig, True);
1604 finally
1605 FreeAndNil(XMLConfig);
1606 end;
1607 except
1608 on E: Exception do
1609 begin
1610 { If no default layout setting is found, we manually dock design form to
1611 main form, and let other forms scatter around. }
1612 ErrorBox('Error while loading layout:' + NL + E.Message + NL + NL +
1613 'The editor will try to use default layout instead.');
1614 Site := DockMaster.GetAnchorSite(DesignForm);
1615 DockMaster.ManualDock(Site, Self, alClient);
1616 end;
1617 end;
1618 end;
1619
1620 procedure TProjectForm.SaveDockLayout;
1621 var
1622 XMLConfig: TXMLConfigStorage;
1623 begin
1624 if not Docking then Exit;
1625 try
1626 XMLConfig := TXMLConfigStorage.Create(UriToFilenameSafe(ApplicationConfig(DockLayoutFileName)), false);
1627 try
1628 DockMaster.SaveLayoutToConfig(XMLConfig);
1629 XMLConfig.WriteToDisk;
1630 finally
1631 FreeAndNil(XMLConfig);
1632 end;
1633 except
1634 on E: Exception do
1635 ErrorBox('Error saving layout:' + NL + E.Message);
1636 end;
1637 end;
1638
1639 procedure TProjectForm.FormCreate(Sender: TObject);
1640
1641 { We create some components by code, this way we don't have to put
1642 in package TCastleShellTreeView and TCastleShellListView,
1643 making compiling CGE editor a bit easier. }
1644 procedure CreateShellViews;
1645 const
1646 { Similar to paths removed by build-tool "clean", or excluded by default by
1647 build-tool "package". This should be configurable some day. }
1648 ExcludeMask = 'castle-engine-output;*~;*.bak;*.exe;*.dll';
1649 begin
1650 ShellTreeView1 := TCastleShellTreeView.Create(Self);
1651 ShellTreeView1.Parent := TabFiles;
1652 ShellTreeView1.Width := MulDiv(250, PixelsPerInch, 96);
1653 ShellTreeView1.Align := alLeft;
1654 ShellTreeView1.FileSortType := fstAlphabet;
1655 ShellTreeView1.HotTrack := True;
1656 ShellTreeView1.ReadOnly := True;
1657 ShellTreeView1.ShowRoot := False;
1658 ShellTreeView1.TabOrder := 0;
1659 ShellTreeView1.Options := [tvoAutoItemHeight, tvoHideSelection, tvoHotTrack, tvoKeepCollapsedNodes, tvoReadOnly, tvoShowButtons, tvoShowLines, tvoToolTips, tvoThemedDraw];
1660 ShellTreeView1.ObjectTypes := [otFolders];
1661 ShellTreeView1.ExcludeMask := ExcludeMask;
1662 ShellTreeView1.PopupMenu := ShellTreePopupMenu;
1663
1664 ShellListView1 := TCastleShellListView.Create(Self);
1665 ShellListView1.Parent := TabFiles;
1666 ShellListView1.Align := alClient;
1667 ShellListView1.ReadOnly := True;
1668 ShellListView1.SortColumn := 0;
1669 ShellListView1.TabOrder := 1;
1670 ShellListView1.ObjectTypes := [otNonFolders, otFolders];
1671 { Without this, files are in undefined order
1672 (it seems SortColumn=0 above doesn't work). }
1673 ShellListView1.FileSortType := fstFoldersFirst;
1674 ShellListView1.ExcludeMask := ExcludeMask;
1675 ShellListView1.OnDblClick := @ShellListViewDoubleClick;
1676 ShellListView1.ShowHint := true;
1677 ShellListView1.RowSelect := true;
1678 ShellListView1.OnSelectItem := @ShellListViewSelectItem;
1679 ShellListView1.Hint := 'Double-click to open.' + NL +
1680 NL +
1681 '- Scenes and images open in engine viewers (castle-model-viewer, castle-image-viewer).' + NL +
1682 '- Designs open in this editor.' + NL +
1683 '- Pascal files open in the code editor.' + NL +
1684 '- Other files open in OS default applications.';
1685 ShellListView1.PopupMenu := ShellListPopupMenu;
1686 ShellListView1.SmallImages := ShellIcons;
1687 ShellListView1.DragMode := dmAutomatic;
1688
1689 ShellTreeView1.ShellListView := ShellListView1;
1690 ShellListView1.ShellTreeView := ShellTreeView1;
1691 end;
1692
1693 procedure BuildPlatformsMenu;
1694
1695 procedure AddPlatform(const Name: String; const Target: TTarget; const OS: TOS; const CPU: TCPU);
1696 var
1697 Mi: TMenuItem;
1698 MiCaption: String;
1699 P: TPlatformInfo;
1700 begin
1701 Mi := TMenuItem.Create(MenuItemPlatform);
1702 MiCaption := Name;
1703 if Target = targetCustom then
1704 MiCaption += ' (' + OSToString(OS) + ' / ' + CPUToString(CPU) + ')';
1705 Mi.Caption := MiCaption;
1706 Mi.Tag := PlatformsInfo.Count;
1707 Mi.OnClick := @MenuItemPlatformChangeClick;
1708 Mi.GroupIndex := 200;
1709 Mi.RadioItem := true;
1710 Mi.ShowAlwaysCheckable := true;
1711 Mi.Checked := Mi.Tag = CurrentPlatformInfo;
1712 MenuItemPlatform.Add(Mi);
1713
1714 P := TPlatformInfo.Create;
1715 P.Target := Target;
1716 P.OS := OS;
1717 P.CPU := CPU;
1718 PlatformsInfo.Add(P);
1719 end;
1720
1721 procedure AddPlatformSeparator;
1722 var
1723 Mi: TMenuItem;
1724 begin
1725 Mi := TMenuItem.Create(MenuItemPlatform);
1726 Mi.Caption := '-';
1727 MenuItemPlatform.Add(Mi);
1728 end;
1729
1730 begin
1731 PlatformsInfo := TPlatformInfoList.Create(true);
1732 AddPlatform('Default', targetCustom, DefaultOS, DefaultCPU);
1733 AddPlatformSeparator;
1734 AddPlatform('Android (Arm 32-bit and 64-bit)', targetAndroid, { OS and CPU ignored } DefaultOS, DefaultCPU);
1735 AddPlatform('Android (emulator 32-bit)', targetCustom, Android, i386);
1736 AddPlatform('Android (emulator 64-bit)', targetCustom, Android, x86_64);
1737 AddPlatformSeparator;
1738 AddPlatform('iOS (Arm 32-bit and 64-bit)', targetIOS, { OS and CPU ignored } DefaultOS, DefaultCPU);
1739 AddPlatformSeparator;
1740 AddPlatform('Linux 32-bit', targetCustom, Linux, i386);
1741 AddPlatform('Linux 64-bit', targetCustom, Linux, x86_64);
1742 AddPlatform('Linux Arm 32-bit', targetCustom, Linux, Arm);
1743 AddPlatform('Linux Arm 64-bit', targetCustom, Linux, Aarch64);
1744 AddPlatformSeparator;
1745 AddPlatform('Windows 32-bit', targetCustom, Win32, i386);
1746 AddPlatform('Windows 64-bit', targetCustom, Win64, x86_64);
1747 AddPlatformSeparator;
1748 AddPlatform('macOS 64-bit', targetCustom, Darwin, x86_64);
1749 AddPlatform('macOS Arm 64-bit', targetCustom, Darwin, Aarch64);
1750 AddPlatformSeparator;
1751 AddPlatform('FreeBSD 32-bit', targetCustom, FreeBSD, i386);
1752 AddPlatform('FreeBSD 64-bit', targetCustom, FreeBSD, x86_64);
1753 end;
1754
1755 procedure BuildPackageFormatsMenu;
1756 const
1757 PackageFormatCaptions: array [TPackageFormat] of string = (
1758 'Default',
1759 'Directory',
1760 'Compressed zip',
1761 'Compressed tar.gz',
1762 'Debian Package (DEB)',
1763 'Android APK',
1764 'Android App Bundle (AAB)',
1765 'iOS Xcode Project',
1766 'iOS Archive -> Development',
1767 'iOS Archive -> ad-hoc',
1768 'iOS Archive -> AppStore',
1769 'Nintendo Switch Project',
1770 'macOS App Bundle (APP)',
1771 'macOS App Bundle (APP) zip'
1772 );
1773 var
1774 Mi: TMenuItem;
1775 P: TPackageFormat;
1776 begin
1777 for P in TPackageFormat do
1778 begin
1779 Mi := TMenuItem.Create(MenuItemPackageFormat);
1780 Mi.Caption := PackageFormatCaptions[P];
1781 Mi.Tag := Ord(P);
1782 Mi.OnClick := @MenuItemPackageFormatChangeClick;
1783 Mi.GroupIndex := 210;
1784 Mi.RadioItem := true;
1785 Mi.ShowAlwaysCheckable := true;
1786 Mi.Checked := P = CurrentPackageFormat;
1787 MenuItemPackageFormat.Add(Mi);
1788 end;
1789 end;
1790
1791 var
1792 EnableDocking: Boolean;
1793 begin
1794 DesignObserver := TFreeNotificationObserver.Create(Self);
1795 DesignObserver.OnFreeNotification := {$ifdef FPC}@{$endif} DesignObserverFreeNotification;
1796 EnableDocking := UriFileExists(ApplicationConfig('enable-docking.txt'));
1797 MenuItemWindow.SetEnabledVisible(EnableDocking);
1798 Docking := EnableDocking and UserConfig.GetValue('ProjectForm_Docking', false);
1799 OutputList := TOutputList.Create(ListOutput);
1800 BuildComponentsMenu(
1801 MenuItemDesignNewUserInterfaceCustomRoot,
1802 MenuItemDesignNewTransformCustomRoot,
1803 nil,
1804 MenuItemDesignNewNonVisualCustomRoot,
1805 @MenuItemDesignNewCustomRootClick);
1806 BuildComponentsMenu(
1807 MenuItemDesignAddUserInterface,
1808 MenuItemDesignAddTransform,
1809 MenuItemDesignAddBehavior,
1810 MenuItemDesignAddNonVisual,
1811 @MenuItemAddComponentClick);
1812 CreateShellViews;
1813 BuildPlatformsMenu;
1814 BuildPackageFormatsMenu;
1815 ApplicationProperties.OnWarning.Add(@WarningNotification);
1816 ListOpenExistingViewStr := TStringList.Create;
1817 if Docking then
1818 begin
1819 // Create dockable forms
1820 // DockMaster.DockSitesCanBeMinimized := True;
1821 DockMaster.MakeDockSite(Self, [akBottom], admrpNone);
1822 DesignForm := TForm.CreateNew(nil);
1823 DesignForm.Name := 'DesignForm';
1824 DesignForm.Caption := 'Design';
1825 DesignHierarchyForm := TForm.CreateNew(nil);
1826 DesignHierarchyForm.Name := 'DesignHierarchyForm';
1827 DesignHierarchyForm.Caption := 'Hierarchy';
1828 { We need to set the DesignTimePPI on new forms,
1829 otherwise when user has system-wide font scaling 125% then the layout
1830 from the initial LoadDockLayout call is not correct (and only calling
1831 later "Restore Default Docking Layout" helps). }
1832 DesignHierarchyForm.DesignTimePPI := DesignTimePPI;
1833 DesignPropertiesForm := TForm.CreateNew(nil);
1834 DesignPropertiesForm.Name := 'DesignPropertiesForm';
1835 DesignPropertiesForm.Caption := 'Properties';
1836 DesignPropertiesForm.DesignTimePPI := DesignTimePPI;
1837 DesignExplorerForm := TForm.CreateNew(nil);
1838 DesignExplorerForm.Name := 'DesignExplorerForm';
1839 DesignExplorerForm.Caption := 'Explorer';
1840 DesignExplorerForm.DesignTimePPI := DesignTimePPI;
1841 DesignFilesForm := TForm.CreateNew(nil);
1842 DesignFilesForm.Name := 'DesignFilesForm';
1843 DesignFilesForm.Caption := 'Files';
1844 DesignFilesForm.DesignTimePPI := DesignTimePPI;
1845 DesignOutputForm := TForm.CreateNew(nil);
1846 DesignOutputForm.Name := 'DesignOutputForm';
1847 DesignOutputForm.Caption := 'Output';
1848 DesignOutputForm.DesignTimePPI := DesignTimePPI;
1849 DesignWarningsForm := TForm.CreateNew(nil);
1850 DesignWarningsForm.Name := 'DesignWarningsForm';
1851 DesignWarningsForm.Caption := 'Warnings';
1852 DesignWarningsForm.DesignTimePPI := DesignTimePPI;
1853 DockMaster.MakeDockable(DesignForm, true, true);
1854 DockMaster.MakeDockable(DesignHierarchyForm, true, true);
1855 DockMaster.MakeDockable(DesignPropertiesForm, true, true);
1856 DockMaster.MakeDockable(DesignExplorerForm, true, true);
1857 DockMaster.MakeDockable(DesignFilesForm, true, true);
1858 DockMaster.MakeDockable(DesignOutputForm, true, true);
1859 DockMaster.MakeDockable(DesignWarningsForm, true, true);
1860
1861 PageControlBottom.Parent := DesignExplorerForm;
1862 PageControlBottom.Align := alClient;
1863 ShellListView1.Parent := DesignFilesForm;
1864 ShellTreeView1.Align := alClient;
1865 ShellListView1.Align := alClient;
1866 ListOutput.Parent := DesignOutputForm;
1867 ListWarnings.Parent := DesignWarningsForm;
1868 PanelWarnings.Parent := DesignWarningsForm;
1869 // Hide splitters, as they aren't needed anymore since we use docked forms
1870 Splitter2.Visible := false;
1871 SplitterBetweenFiles.Visible := false;
1872 // Hide bottom tab's header
1873 PageControlBottom.ShowTabs := false;
1874
1875 LoadDockLayout;
1876 end;
1877 WantedDocking := Docking;
1878 MenuItemEnableDisableDocking.Checked := Docking;
1879 MenuItemUIRestoreDefaultDockSettings.Enabled := Docking;
1880 MenuItemUIDesign.Enabled := Docking;
1881 MenuItemUIExplorer.Enabled := Docking;
1882 MenuItemUIHierarchy.Enabled := Docking;
1883 MenuItemUIProperties.Enabled := Docking;
1884 MenuItemUIFiles.Enabled := Docking;
1885 MenuItemUIOutput.Enabled := Docking;
1886 MenuItemUIWarnings.Enabled := Docking;
1887 end;
1888
1889 procedure TProjectForm.FormDestroy(Sender: TObject);
1890 begin
1891 UserConfig.SetValue('ProjectForm_Docking', WantedDocking);
1892 FormHide(Self); //to save config properly
1893 ApplicationProperties.OnWarning.Remove(@WarningNotification);
1894 FreeProcess;
1895 FreeAndNil(OutputList);
1896 FreeAndNil(Manifest);
1897 FreeAndNil(DesignForm);
1898 FreeAndNil(DesignHierarchyForm);
1899 FreeAndNil(DesignPropertiesForm);
1900 FreeAndNil(DesignExplorerForm);
1901 FreeAndNil(DesignFilesForm);
1902 FreeAndNil(DesignOutputForm);
1903 FreeAndNil(DesignWarningsForm);
1904 FreeAndNil(PlatformsInfo);
1905 FreeAndNil(ListOpenExistingViewStr);
1906 FreeAndNil(Design);
1907
1908 { It is important to reset ApplicationDataOverride
1909 *after* FreeAndNil(Design), which in turn freed components like
1910 TCastleScene that possibly interacted with FileMonitor.
1911
1912 That's because TCastleScene doing FileMonitor.Watch of
1913 e.g. "castle-data:/soldier.gltf" with one ApplicationDataOverride value,
1914 and then doing Unwatch on the same "castle-data:/soldier.gltf"
1915 but *after* ApplicationDataOverride changed,
1916 is effectively talking about 2 different files.
1917
1918 And FileMonitor detects it, as it remembers "final" URLs,
1919 with castle-data resolved (and that's good).
1920
1921 Testcase: Open 3D FPS game template (it has 4 soldiers),
1922 open play view,
1923 close the editor with Alt + F4.
1924 There should be no warnings that we "cannot unwatch .../soldier.gltf" }
1925 ApplicationDataOverride := '';
1926 end;
1927
1928 procedure TProjectForm.DesignObserverFreeNotification(const Sender: TFreeNotificationObserver);
1929 begin
1930 // set property to nil when the referenced component is freed
1931 Design := nil;
1932 end;
1933
1934 procedure TProjectForm.FormHide(Sender: TObject);
1935
1936 function WindowStateToStr(const AWindowState: TWindowState): String;
1937 begin
1938 case AWindowState of
1939 wsNormal: Result := 'wsNormal';
1940 wsMinimized: Result := 'wsMinimized';
1941 wsMaximized: Result := 'wsMaximized';
1942 wsFullScreen: Result := 'wsFullScreen';
1943 end;
1944 end;
1945
1946 begin
1947 if not Docking then
1948 begin
1949 UserConfig.SetValue('ProjectForm_Saved', true);
1950 UserConfig.SetValue('ProjectForm_Width', Width);
1951 UserConfig.SetValue('ProjectForm_Height', Height);
1952 UserConfig.SetValue('ProjectForm_Left', Left);
1953 UserConfig.SetValue('ProjectForm_Top', Top);
1954 UserConfig.SetValue('ProjectForm_WindowState', WindowStateToStr(WindowState));
1955 UserConfig.SetValue('ProjectForm_PageControlBottom.Height', PageControlBottom.Height);
1956 if Design <> nil then
1957 begin
1958 UserConfig.SetValue('ProjectForm_DesignSaved', true);
1959 UserConfig.SetValue('ProjectForm_Design.PanelRight.Width', Design.PanelRight.Width);
1960 UserConfig.SetValue('ProjectForm_Design.PanelLeft.Width', Design.PanelLeft.Width);
1961 end;
1962 UserConfig.Save;
1963 end;
1964 end;
1965
1966 procedure TProjectForm.FormKeyDown(Sender: TObject; var Key: Word;
1967 Shift: TShiftState);
1968 begin
1969 { See CastleLclEditHack for an expanation of this hack. }
1970 ProcessKeyToPerformEdit(ActiveControl, Key, Shift);
1971 end;
1972
1973 procedure TProjectForm.FormShow(Sender: TObject);
1974
1975 function StrToWindowState(const AWindowStateStr: String): TWindowState;
1976 begin
1977 case AWindowStateStr of
1978 'wsNormal': Result := wsNormal;
1979 'wsMaximized': Result := wsMaximized;
1980 else
1981 Result := wsNormal; //treat wsMinimized and any other value as wsNormal
1982 end;
1983 end;
1984
1985 var
1986 NewWidth, NewHeight, NewLeft, NewTop, NewControlHeight: Integer;
1987 NewWindowState: TWindowState;
1988 begin
1989 if (not Docking) and UserConfig.GetValue('ProjectForm_Saved', false) then
1990 begin
1991 NewWidth := UserConfig.GetValue('ProjectForm_Width', -MaxInt);
1992 NewHeight := UserConfig.GetValue('ProjectForm_Height', -MaxInt);
1993 NewLeft := UserConfig.GetValue('ProjectForm_Left', -MaxInt);
1994 NewTop := UserConfig.GetValue('ProjectForm_Top', -MaxInt);
1995 NewControlHeight := UserConfig.GetValue('ProjectForm_PageControlBottom.Height', -MaxInt);
1996 NewWindowState := StrToWindowState(UserConfig.GetValue('ProjectForm_WindowState', 'wsNormal'));
1997
1998 { Apply new values.
1999 Note that we don't apply position/size values when NewWindowState <> wsMaximized,
2000 as on Windows this causes form to flicker when it appears (initially with invalid sizes
2001 inside a maximized form). }
2002 case NewWindowState of
2003 wsNormal:
2004 begin
2005 WindowState := NewWindowState;
2006 if (NewWidth + NewLeft <= Screen.Width + 32) and (NewWidth > 128) and
2007 (NewHeight + NewTop <= Screen.Height + 32) and (NewHeight > 128) and
2008 (NewControlHeight < NewHeight) and (NewControlHeight >= 0) and
2009 (NewLeft > -32) and (NewTop > -32) then
2010 begin
2011 Width := NewWidth;
2012 Height := NewHeight;
2013 Left := NewLeft;
2014 Top := NewTop;
2015 PageControlBottom.Height := NewControlHeight;
2016 end;
2017 end;
2018 wsMaximized:
2019 begin
2020 WindowState := NewWindowState;
2021 { We use NewControlHeight, just like with wsNormal, but with a different condition. }
2022 if (NewControlHeight <= Screen.Height - 32) and (NewControlHeight >= 0) then
2023 begin
2024 PageControlBottom.Height := NewControlHeight;
2025 end;
2026 end;
2027 else ; // do not restore other state, like wsMinimized
2028 end;
2029 end;
2030 end;
2031
2032 procedure TProjectForm.ListOpenExistingViewDblClick(Sender: TObject);
2033 var
2034 DesignFileName, DesignUrl: String;
2035 begin
2036 if ListOpenExistingView.ItemIndex <> -1 then
2037 begin
2038 DesignFileName := ListOpenExistingViewStr[ListOpenExistingView.ItemIndex];
2039 DesignUrl := FilenameToUriSafe(DesignFileName);
2040 ProposeOpenDesign(DesignUrl);
2041 end;
2042 end;
2043
2044 procedure TProjectForm.ListOutputDblClick(Sender: TObject);
2045
2046 { For a filename in output, return absolute filename or raise exception. }
2047 function FilenameFromOutput(const S: String): String;
2048 var
2049 Test: String;
2050 CgeFileInfo: TFileInfo;
2051 begin
2052 // absolute filename
2053 if IsPathAbsolute(S) then
2054 Exit(S);
2055
2056 // filename relative to project root
2057 Test := CombinePaths(ProjectPath, S);
2058 if FileExists(Test) then
2059 Exit(Test);
2060
2061 // filename that has to be found on search paths
2062 if CharsPos(AllowDirectorySeparators, S) = 0 then
2063 begin
2064 Test := Manifest.SearchPascalFile(S);
2065 if Test <> '' then
2066 Exit(Test);
2067 end;
2068
2069 // filename in CGE sources
2070 if (CastleEnginePath <> '') and
2071 FindFirstFile(CastleEnginePath, S, false, [ffRecursive], CgeFileInfo) then
2072 Exit(CgeFileInfo.AbsoluteName);
2073
2074 raise Exception.CreateFmt('Cannot find Pascal filename "%s"', [S]);
2075 end;
2076
2077 var
2078 R: TRegExpr;
2079 Line: String;
2080 begin
2081 // jump to source code line in case of error message here
2082
2083 if ListOutput.ItemIndex = -1 then
2084 Exit;
2085 Line := ListOutput.Items[ListOutput.ItemIndex];
2086
2087 R := TRegExpr.Create;
2088 try
2089 R.Expression := '^([^()]+)\(([\d]+),([\d]+)\) (Error|Fatal|Warning|Note):';
2090
2091 if R.Exec(Line) then
2092 begin
2093 OpenPascal(FilenameFromOutput(R.Match[1]), StrToInt(R.Match[2]), StrToInt(R.Match[3]));
2094 Exit;
2095 end;
2096
2097 R.Expression := '^([^()]+)\(([\d]+)\) (Error|Fatal|Warning|Note):';
2098 if R.Exec(Line) then
2099 begin
2100 OpenPascal(FilenameFromOutput(R.Match[1]), StrToInt(R.Match[2]));
2101 Exit;
2102 end;
2103
2104 R.Expression := '^Compiling ([^()]+)';
2105 if R.Exec(Line) then
2106 begin
2107 OpenPascal(FilenameFromOutput(R.Match[1]));
2108 Exit;
2109 end;
2110 finally
2111 FreeAndNil(R);
2112 end;
2113 end;
2114
2115 procedure TProjectForm.MenuItemCacheCleanClick(Sender: TObject);
2116 begin
2117 BuildToolCall(['cache-clean']);
2118 end;
2119
2120 procedure TProjectForm.MenuItemCacheClick(Sender: TObject);
2121 begin
2122 BuildToolCall(['cache']);
2123 end;
2124
2125 procedure TProjectForm.MenuItemDesignNewNonVisualClick(Sender: TObject);
2126 begin
2127 if not IsCreatingNewDesignAvailable then
2128 Exit;
2129
2130 if ProposeSaveDesign then
2131 NewDesign(TCastleComponent, nil);
2132 end;
2133
2134 procedure TProjectForm.MenuItemEnableDisableDockingClick(Sender: TObject);
2135 begin
2136 InfoBox('Please close the project window and open it again to activate / deactivate the Docking Layout.');
2137 WantedDocking := not WantedDocking;
2138 MenuItemEnableDisableDocking.Checked := WantedDocking;
2139 end;
2140
2141 procedure TProjectForm.MenuItemInstallClick(Sender: TObject);
2142 begin
2143 BuildToolCall(['install']);
2144 end;
2145
2146 procedure TProjectForm.MenuItemNewDirectoryClick(Sender: TObject);
2147 var
2148 NewDir, FullNewDir: String;
2149 begin
2150 if InputQuery('New Directory', 'Create a new directory:', NewDir) then
2151 begin
2152 FullNewDir := InclPathDelim(ShellListView1.Root) + NewDir;
2153 if not CreateDir(FullNewDir) then
2154 raise Exception.CreateFmt('Creating new directory "%s" failed', [FullNewDir]);
2155 RefreshFiles(rfEverythingInCurrentDir);
2156 // Select newly added dir
2157 ShellListView1.SelectedFileNameInRoot := NewDir;
2158 end;
2159 end;
2160
2161 procedure TProjectForm.MenuItemRenameClick(Sender: TObject);
2162 begin
2163 Design.RenameSelectedItem;
2164 end;
2165
2166 procedure TProjectForm.MenuItemShellTreeRefreshClick(Sender: TObject);
2167 begin
2168 RefreshFiles(rfEverything);
2169 end;
2170
2171 procedure TProjectForm.MenuItemUIDesignClick(Sender: TObject);
2172 begin
2173 DockMaster.MakeDockable(DesignForm, True, True);
2174 end;
2175
2176 procedure TProjectForm.MenuItemUIExplorerClick(Sender: TObject);
2177 begin
2178 DockMaster.MakeDockable(DesignExplorerForm, True, True);
2179 end;
2180
2181 procedure TProjectForm.MenuItemUIFilesClick(Sender: TObject);
2182 begin
2183 DockMaster.MakeDockable(DesignFilesForm, True, True);
2184 end;
2185
2186 procedure TProjectForm.MenuItemUIHierarchyClick(Sender: TObject);
2187 begin
2188 DockMaster.MakeDockable(DesignHierarchyForm, True, True);
2189 end;
2190
2191 procedure TProjectForm.MenuItemUIOutputClick(Sender: TObject);
2192 begin
2193 DockMaster.MakeDockable(DesignOutputForm, True, True);
2194 end;
2195
2196 procedure TProjectForm.MenuItemUIPropertiesClick(Sender: TObject);
2197 begin
2198 DockMaster.MakeDockable(DesignPropertiesForm, True, True);
2199 end;
2200
2201 procedure TProjectForm.MenuItemUIRestoreDefaultDockSettingsClick(Sender: TObject
2202 );
2203 var
2204 DockLayoutUrl: String;
2205 begin
2206 { Simply remove the dock ui config file in order to restore default settings }
2207 DockLayoutUrl := ApplicationConfig(DockLayoutFileName);
2208 if UriFileExists(DockLayoutUrl) then
2209 CheckDeleteFile(UriToFilenameSafe(DockLayoutUrl));
2210 LoadDockLayout;
2211 end;
2212
2213 procedure TProjectForm.MenuItemUIWarningsClick(Sender: TObject);
2214 begin
2215 DockMaster.MakeDockable(DesignWarningsForm, True, True);
2216 end;
2217
2218 procedure TProjectForm.UpdateRenameItem(Sender: TObject);
2219 begin
2220 if (Design <> nil) and Design.RenameSelectedPossible then
2221 MenuItemRename.Enabled := true
2222 else
2223 MenuItemRename.Enabled := false;
2224 end;
2225
2226 procedure TProjectForm.UpdateUndo(Sender: TObject);
2227 begin
2228 { It is important to disable these actions, as e.g. calling
2229 TUndoSystem.Undo when IsUndoPossible=false will result in an exception.
2230 Testcase: right after loading the design, undo should not be possible,
2231 Ctrl+Z should do nothing. }
2232 if Design <> nil then
2233 begin
2234 MenuItemUndo.Enabled := Design.UndoSystem.IsUndoPossible;
2235 MenuItemUndo.Caption := Design.UndoSystem.UndoComment;
2236 MenuItemRedo.Enabled := Design.UndoSystem.IsRedoPossible;
2237 MenuItemRedo.Caption := Design.UndoSystem.RedoComment;
2238 end else
2239 begin
2240 MenuItemUndo.Enabled := false;
2241 MenuItemRedo.Enabled := false;
2242 end;
2243 end;
2244
2245 procedure TProjectForm.MenuItemRedoClick(Sender: TObject);
2246 begin
2247 Design.PerformRedo;
2248 end;
2249
2250 procedure TProjectForm.MenuItemUndoClick(Sender: TObject);
2251 begin
2252 Design.PerformUndo;
2253 end;
2254
2255 procedure TProjectForm.MenuItemDeleteFileClick(Sender: TObject);
2256 var
2257 SelectedFileName: String;
2258 begin
2259 if ShellListView1.Selected <> nil then
2260 begin
2261 SelectedFileName := ShellListView1.GetPathFromItem(ShellListView1.Selected);
2262 if DirectoryExists(SelectedFileName) then
2263 begin
2264 if MessageDlg('Delete Directory', 'Delete directory "' + SelectedFileName + '"?',
2265 mtConfirmation, mbYesNo, 0) = mrYes then
2266 begin
2267 RemoveNonEmptyDir(SelectedFileName);
2268 RefreshFiles(rfEverythingInCurrentDir);
2269 end;
2270 end else
2271 begin
2272 if MessageDlg('Delete File', 'Delete file "' + SelectedFileName + '"?',
2273 mtConfirmation, mbYesNo, 0) = mrYes then
2274 begin
2275 CheckDeleteFile(SelectedFileName);
2276 RefreshFiles(rfFilesInCurrentDir);
2277 end;
2278 end;
2279 end;
2280 end;
2281
2282 procedure TProjectForm.MenuItemOpenDefaultClick(Sender: TObject);
2283 begin
2284 ShellListViewDoubleClick(ShellListView1);
2285 end;
2286
2287 procedure TProjectForm.MenuItemOpenDirFromFileClick(Sender: TObject);
2288 begin
2289 OpenDocument(ShellListView1.Root);
2290 end;
2291
2292 procedure TProjectForm.MenuItemPreferencesClick(Sender: TObject);
2293 begin
2294 PreferencesForm.ShowModal;
2295 end;
2296
2297 procedure TProjectForm.MenuItemAutoGenerateCleanClick(Sender: TObject);
2298 begin
2299 BuildToolCall(['auto-generate-clean']);
2300 end;
2301
2302 procedure TProjectForm.MenuItemCleanClick(Sender: TObject);
2303 begin
2304 BuildToolCall(['clean']);
2305 end;
2306
2307 procedure TProjectForm.MenuItemCompileClick(Sender: TObject);
2308 begin
2309 BuildToolCall(['compile']);
2310 end;
2311
2312 procedure TProjectForm.MenuItemCompileRunClick(Sender: TObject);
2313 begin
2314 if ProposeSaveDesign then
2315 begin
2316 RunningApplication := true;
2317 SoundEngineSetVolume;
2318 if PlatformsInfo[CurrentPlatformInfo].Target = targetAndroid then
2319 BuildToolCall(['package', 'install', 'run'])
2320 else
2321 BuildToolCall(['compile', 'run']);
2322 end;
2323 end;
2324
2325 procedure TProjectForm.ActionCopyComponentExecute(Sender: TObject);
2326 begin
2327 Assert(Design <> nil); // menu item is disabled otherwise
2328 Design.CopyComponent;
2329 end;
2330
2331 procedure TProjectForm.MenuItemDesignCloseClick(Sender: TObject);
2332 begin
2333 Assert(Design <> nil); // menu item is disabled otherwise
2334
2335 if CastleApplicationMode in [appSimulation, appSimulationPaused] then
2336 begin
2337 InfoBox('Stop the physics simulation to be able to close design.');
2338 Exit;
2339 end;
2340
2341 if ProposeSaveDesign then
2342 begin
2343 UserConfig.SetValue('ProjectForm_Design.PanelRight.Width', Design.PanelRight.Width);
2344 UserConfig.SetValue('ProjectForm_Design.PanelLeft.Width', Design.PanelLeft.Width);
2345 UserConfig.SetValue('ProjectForm_DesignSaved', true);
2346 UserConfig.Save;
2347 FreeAndNil(Design);
2348 DesignExistenceChanged;
2349 end;
2350 end;
2351
2352 procedure TProjectForm.ActionDeleteComponentExecute(Sender: TObject);
2353 begin
2354 Assert(Design <> nil); // menu item is disabled otherwise
2355 Design.DeleteComponent;
2356 end;
2357
2358 procedure TProjectForm.ActionDuplicateComponentExecute(Sender: TObject);
2359 begin
2360 Assert(Design <> nil); // menu item is disabled otherwise
2361 Design.DuplicateComponent;
2362 end;
2363
2364 procedure TProjectForm.MenuItemManualClick(Sender: TObject);
2365 begin
2366 OpenUrl('https://castle-engine.io/manual_intro.php');
2367 end;
2368
2369 procedure TProjectForm.MenuItemModeDebugClick(Sender: TObject);
2370 begin
2371 BuildMode := bmDebug;
2372 MenuItemModeDebug.Checked := true;
2373 end;
2374
2375 procedure TProjectForm.ListOpenExistingViewAddFile(const FileInfo: TFileInfo; var StopSearch: boolean);
2376 begin
2377 ListOpenExistingViewStr.Append(FileInfo.AbsoluteName);
2378 end;
2379
2380 procedure TProjectForm.ListOpenExistingViewRefresh;
2381
2382 function ShortDesignName(const S: String): String;
2383 begin
2384 Result := DeleteFileExt(ExtractFileName(S));
2385 Result := PrefixRemove('gameview', Result, true);
2386 Result := PrefixRemove('gamestate', Result, true);
2387 Result := SuffixRemove('.castle-user-interface', Result, true);
2388 end;
2389
2390 var
2391 ListItem: TListItem;
2392 DesignFileName, ProjectDataUrl: String;
2393 begin
2394 { calculate ListOpenExistingViewStr contents }
2395 ListOpenExistingViewStr.Clear;
2396 { Search in ProjectDataUrl, not ProjectPathUrl, as all designs should be part of data
2397 to be possible to open them at runtime.
2398 This also avoids finding stuff in castle-engine-output, which is possible,
2399 e.g. after "castle-engine package --target=android" the castle-engine-output contains
2400 some temporary data with copies of design files -- and we *do not* want to show them here. }
2401 ProjectDataUrl := CombineUri(ProjectPathUrl, 'data/');
2402 if UriExists(ProjectDataUrl) <> ueNotExists then
2403 begin
2404 FindFiles(ProjectDataUrl, 'gameview*.castle-user-interface', false, @ListOpenExistingViewAddFile, [ffRecursive]);
2405 // support deprecated names
2406 FindFiles(ProjectDataUrl, 'gamestate*.castle-user-interface', false, @ListOpenExistingViewAddFile, [ffRecursive]);
2407 end;
2408 { without sorting, the order would be ~random (as FindFiles enumarates).
2409 Note that we sort including the subdirectory names, which is good,
2410 we want files in the same subdirectory to be together. }
2411 ListOpenExistingViewStr.Sort;
2412
2413 { TODO: It seems LCL UI always shows as if the "Last Modified" (column 2)
2414 was sorted, and setting ListOpenExistingView.SortColumn from code
2415 or LFM doesn't change it. }
2416
2417 { copy ListOpenExistingViewStr contents -> ListOpenExistingView GUI contents }
2418 ListOpenExistingView.Items.Clear;
2419 for DesignFileName in ListOpenExistingViewStr do
2420 begin
2421 ListItem := ListOpenExistingView.Items.Add;
2422 ListItem.Caption := ShortDesignName(DesignFileName);
2423 ListItem.SubItems.Append(ExtractRelativePath(ProjectPath, DesignFileName));
2424 ListItem.SubItems.Append(FileDateTimeStr(DesignFileName));
2425 end;
2426 end;
2427
2428 procedure TProjectForm.DesignExistenceChanged;
2429 var
2430 NewPanelRightWidth, NewPanelLeftWidth: Integer;
2431 begin
2432 MenuItemSaveAsDesign.Enabled := Design <> nil;
2433 MenuItemSaveDesign.Enabled := Design <> nil;
2434 MenuItemDesignClose.Enabled := Design <> nil;
2435 MenuItemDesignAddTransform.Enabled := Design <> nil;
2436 MenuItemDesignAddUserInterface.Enabled := Design <> nil;
2437 MenuItemDesignAddBehavior.Enabled := Design <> nil;
2438 MenuItemDesignAddNonVisual.Enabled := Design <> nil;
2439 ActionComponentDelete.Enabled := Design <> nil;
2440 ActionComponentCopy.Enabled := Design <> nil;
2441 ActionComponentPaste.Enabled := Design <> nil;
2442 ActionComponentCut.Enabled := Design <> nil;
2443 ActionComponentDuplicate.Enabled := Design <> nil;
2444 ActionComponentSaveSelected.Enabled := Design <> nil;
2445 ActionEditAssociatedUnit.Enabled := Design <> nil;
2446 ActionFocusDesign.Enabled := Design <> nil;
2447 ActionModeInteract.Enabled := Design <> nil;
2448 ActionModeSelect.Enabled := Design <> nil;
2449 ActionModeTranslate.Enabled := Design <> nil;
2450 ActionModeRotate.Enabled := Design <> nil;
2451 ActionModeScale.Enabled := Design <> nil;
2452 ActionShowStatistics.Enabled := Design <> nil;
2453 ActionFindToggle.Enabled := Design <> nil;
2454 ActionFindNext.Enabled := Design <> nil;
2455
2456 { Options that toggle InternalForceWireframe could actually work with Design=nil,
2457 with current implementation.
2458 But their effect would be invisible, so better disable. }
2459 ActionViewportRenderNormal.Enabled := Design <> nil;
2460 ActionViewportRenderWireframeOnly.Enabled := Design <> nil;
2461 ActionViewportRenderSolidWireframe.Enabled := Design <> nil;
2462 ActionViewportRenderNext.Enabled := Design <> nil;
2463 MenuItemWireframe.Enabled := Design <> nil;
2464
2465 UpdateUndo(nil);
2466 UpdateRenameItem(nil);
2467 UpdateFormCaption(nil);
2468
2469 if (Design <> nil) and
2470 UserConfig.GetValue('ProjectForm_DesignSaved', false) and
2471 (not Docking) then
2472 begin
2473 NewPanelRightWidth := UserConfig.GetValue('ProjectForm_Design.PanelRight.Width', -MaxInt);
2474 NewPanelLeftWidth := UserConfig.GetValue('ProjectForm_Design.PanelLeft.Width', -MaxInt);
2475 if (NewPanelRightWidth >= 0) and (NewPanelLeftWidth >= 0) and
2476 (NewPanelRightWidth + NewPanelLeftWidth <= Width) then
2477 begin
2478 Design.PanelRight.Width := NewPanelRightWidth;
2479 Design.PanelLeft.Width := NewPanelLeftWidth;
2480 end;
2481 end;
2482
2483 SetEnabledVisible(PanelNoDesign, Design = nil);
2484
2485 if Design = nil then
2486 ListOpenExistingViewRefresh;
2487
2488 { Synchronize action state with new design.
2489 Testcase:
2490 - open project
2491 - open design
2492 - toggle "Show Colliders" to true by clicking in menu
2493 - close design
2494 - open design again
2495 - -> desired effect: "Show Colliders" is synchronized with Design.ShowColliders,
2496 which means it is reset to false now.
2497 }
2498 if Design <> nil then
2499 ActionShowColliders.Checked := Design.ShowColliders;
2500 end;
2501
2502 procedure TProjectForm.ProposeOpenDesign(const DesignUrl: String);
2503 begin
2504 if CastleApplicationMode in [appSimulation, appSimulationPaused] then
2505 begin
2506 InfoBox('Stop the physics simulation to be able to open design.');
2507 Exit;
2508 end;
2509
2510 if ProposeSaveDesign then
2511 OpenDesign(DesignUrl);
2512 end;
2513
2514 procedure TProjectForm.NeedsDesignFrame;
2515 begin
2516 if Design = nil then
2517 begin
2518 Design := TDesignFrame.Create(Self);
2519 DesignObserver.Observed := Design;
2520 Design.Parent := PanelAboveTabs;
2521 Design.Align := alClient;
2522 Design.OnUpdateFormCaption := @UpdateFormCaption;
2523 Design.UndoSystem.OnUpdateUndo := @UpdateUndo;
2524 Design.OnSelectionChanged := @UpdateRenameItem;
2525 Design.OnCurrentViewportChanged := @CurrentViewportChanged;
2526 Design.OnProposeOpenDesign := @ProposeOpenDesign;
2527 Design.OnIsRunning := @IsRunning;
2528 Design.OnShowStatistics := @ShowStatistics;
2529 Design.OnRunningToggle := @RunningToggle;
2530 Design.OnApiReferenceOfCurrent := @MenuItemReferenceOfCurrentClick;
2531
2532 // Update Design.ActionPlayStop, after OnIsRunning and OnRunningToggle are set
2533 Design.ActionPlayStopUpdate(Design.ActionPlayStop);
2534
2535 DesignExistenceChanged;
2536 if Docking then
2537 begin
2538 // Transfer controls to dock forms, and modify it's align rule
2539 Design.Parent := DesignForm;
2540 Design.PanelLeft.Parent := DesignHierarchyForm;
2541 Design.PanelRight.Parent := DesignPropertiesForm;
2542 Design.Align := alClient;
2543 Design.PanelLeft.Align := alClient;
2544 Design.PanelRight.Align := alClient;
2545 // Hide splitters, as they dont need anymore since we use docked forms
2546 Design.SplitterLeft.Visible := False;
2547 Design.SplitterRight.Visible := False;
2548 end;
2549 end;
2550 end;
2551
2552 procedure TProjectForm.CurrentViewportChanged(Sender: TObject);
2553
2554 procedure UnselectAll;
2555 begin
2556 ActionNavigation2D.Checked := false;
2557 ActionNavigationFly.Checked := false;
2558 ActionNavigationExamine.Checked := false;
2559 end;
2560
2561 begin
2562 if (Design <> nil) and (Design.CurrentViewport <> nil) then
2563 begin
2564 { update menu state from Design.CurrentViewport.InternalDesignNavigationType }
2565 case Design.CurrentViewport.InternalDesignNavigationType of
2566 dn2D : ActionNavigation2D.Checked := true;
2567 dnFly : ActionNavigationFly.Checked := true;
2568 dnExamine: ActionNavigationExamine.Checked := true;
2569 else UnselectAll;
2570 end;
2571 end else
2572 UnselectAll;
2573 end;
2574
2575 function TProjectForm.SaveDuringPhysicsSimulation: Boolean;
2576 begin
2577 Result := true;
2578 if CastleApplicationMode in [appSimulation, appSimulationPaused] then
2579 begin
2580 Result := YesNoBox('The editor is during of physics simulation.'+ NL +
2581 'Saving the design will save the current state, not the state before the start of the simulation. Do you want to continue?');
2582 end;
2583 end;
2584
2585 function TProjectForm.IsCreatingNewDesignAvailable: Boolean;
2586 begin
2587 Result := true;
2588 if CastleApplicationMode in [appSimulation, appSimulationPaused] then
2589 begin
2590 InfoBox('Stop the physics simulation to be able to create new design.');
2591 Result := false;
2592 end;
2593 end;
2594
2595 procedure TProjectForm.NewDesign(const ComponentClass: TComponentClass;
2596 const ComponentOnCreate: TNotifyEvent);
2597 begin
2598 NeedsDesignFrame;
2599 ClearAllWarnings;
2600 Design.NewDesign(ComponentClass, ComponentOnCreate);
2601 end;
2602
2603 procedure TProjectForm.OpenDesign(const DesignUrl: String);
2604 begin
2605 NeedsDesignFrame;
2606 ClearAllWarnings;
2607 try
2608 Design.OpenDesign(DesignUrl);
2609 except
2610 { In case Design.OpenDesign raised exception (e.g. file unreadable or invalid),
2611 do not leave Design in half-uninitialized state (e.g. treeview will not
2612 show anything valid). }
2613 FreeAndNil(Design);
2614 DesignExistenceChanged;
2615 raise;
2616 end;
2617 end;
2618
2619 procedure TProjectForm.WarningNotification(const Category,
2620 Message: string);
2621 begin
2622 if Category <> '' then
2623 ListWarnings.Items.Add(Category + ': ' + Message)
2624 else
2625 ListWarnings.Items.Add(Message);
2626 TabWarnings.Caption := 'Warnings (' + IntToStr(ListWarnings.Count) + ')';
2627 TabWarnings.TabVisible := true;
2628 end;
2629
2630 procedure TProjectForm.ClearAllWarnings;
2631 begin
2632 ListWarnings.Clear;
2633 TabWarnings.TabVisible := false;
2634 end;
2635
2636 procedure TProjectForm.MenuItemDesignNewUserInterfaceRectClick(Sender: TObject);
2637 begin
2638 if not IsCreatingNewDesignAvailable then
2639 Exit;
2640
2641 if ProposeSaveDesign then
2642 NewDesign(TCastleUserInterface, nil);
2643 end;
2644
2645 procedure TProjectForm.MenuItemDesignNewTransformClick(Sender: TObject);
2646 begin
2647 if not IsCreatingNewDesignAvailable then
2648 Exit;
2649
2650 if ProposeSaveDesign then
2651 NewDesign(TCastleTransform, nil);
2652 end;
2653
2654 procedure TProjectForm.MenuItemOnlyRunClick(Sender: TObject);
2655 begin
2656 if ProposeSaveDesign then
2657 begin
2658 RunningApplication := true;
2659 SoundEngineSetVolume;
2660 BuildToolCall(['run']);
2661 end;
2662 end;
2663
2664 procedure TProjectForm.MenuItemOpenDesignClick(Sender: TObject);
2665 begin
2666 if CastleApplicationMode in [appSimulation, appSimulationPaused] then
2667 begin
2668 InfoBox('Stop the physics simulation to be able to open design.');
2669 Exit;
2670 end;
2671
2672 if ProposeSaveDesign then
2673 begin
2674 if Design <> nil then
2675 OpenDesignDialog.Url := Design.DesignUrl;
2676 if OpenDesignDialog.Execute then
2677 begin
2678 OpenDesign(OpenDesignDialog.Url);
2679 end;
2680 end;
2681 end;
2682
2683 procedure TProjectForm.MenuItemPackageClick(Sender: TObject);
2684 begin
2685 BuildToolCall(['package']);
2686 end;
2687
2688 procedure TProjectForm.MenuItemPackageSourceClick(Sender: TObject);
2689 begin
2690 BuildToolCall(['package-source']);
2691 end;
2692
2693 procedure TProjectForm.ActionPasteComponentExecute(Sender: TObject);
2694 begin
2695 Assert(Design <> nil); // menu item is disabled otherwise
2696 Design.PasteComponent;
2697 end;
2698
2699 procedure TProjectForm.MenuItemSwitchProjectClick(Sender: TObject);
2700
2701 function HandleNonModalAssociatedForm(var Form: TForm): Boolean;
2702 begin
2703 Result := true;
2704 if (Form <> nil) and Form.Visible then
2705 begin
2706 if not Form.CloseQuery then
2707 Exit(false);
2708 Form.Close; // not needed on GTK2, maybe add ifdef?
2709 // Calling Release seems safer than FreeAndNil(Form) below,
2710 // though tests didn't actually show any difference now.
2711 Form.Release;
2712 end;
2713 //FreeAndNil(Form);
2714 end;
2715
2716 begin
2717 if CastleApplicationMode in [appSimulation, appSimulationPaused] then
2718 begin
2719 InfoBox('Stop the physics simulation to be able to switch project.');
2720 Exit;
2721 end;
2722
2723 if ProposeSaveDesign then
2724 begin
2725 { Close and free associated windows.
2726 Reason for free: E.g. ImportSketchfabForm has some "links" to current project,
2727 like TImportSketchfabForm.OnAddImported, so it's simpler to just
2728 free it and recreate in new projects. }
2729 if not HandleNonModalAssociatedForm(TForm(SpriteSheetEditorForm)) then
2730 Exit;
2731 if not HandleNonModalAssociatedForm(TForm(ImportSketchfabForm)) then
2732 Exit;
2733
2734 {$ifdef CASTLE_CLOSE_HACK}
2735 if Design <> nil then
2736 begin
2737 FreeAndNil(Design);
2738 DesignExistenceChanged;
2739 end;
2740
2741 { Call Close, not Release.
2742 Avoids crashes on closing sometimes.
2743 Testcase: open escape-universe, open loading design, "Close and SWitch Project". }
2744 OnCloseQuery := nil;
2745 Close;
2746 {$else}
2747 Release; // do not call MenuItemDesignClose, to avoid OnCloseQuery
2748 {$endif}
2749
2750 ChooseProjectForm.Show;
2751 end;
2752 end;
2753
2754 procedure TProjectForm.ProcessUpdateTimerTimer(Sender: TObject);
2755 begin
2756 if RunningProcess <> nil then
2757 begin
2758 RunningProcess.Update;
2759 if not RunningProcess.Running then
2760 FreeProcess;
2761 end;
2762 end;
2763
2764 procedure TProjectForm.ShellListPopupMenuPopup(Sender: TObject);
2765 begin
2766 MenuItemOpenDefault.Enabled := ShellListView1.Selected <> nil;
2767 MenuItemDeleteFile.Enabled := ShellListView1.Selected <> nil;
2768 ActionCopyUrl.Enabled := ShellListView1.Selected <> nil;
2769 end;
2770
2771 procedure TProjectForm.FreeProcess;
2772 begin
2773 FreeAndNil(RunningProcess);
2774 ProcessUpdateTimer.Enabled := false;
2775 IsRunningChanged;
2776 end;
2777
2778 procedure TProjectForm.ShellListViewSelectItem(Sender: TObject;
2779 Item: TListItem; Selected: Boolean);
2780 begin
2781 if ShellListViewUpdating = 0 then
2782 ViewFileFrameUpdate;
2783 end;
2784
2785 procedure TProjectForm.ViewFileFrameUpdate;
2786
2787 { Make sure ViewFileFrame is created and visible.
2788 For now we create ViewFileFrame on-demand, just in case there's a problem
2789 with initializing 2nd OpenGL context on some computer. }
2790 procedure NeedsViewFile;
2791 begin
2792 if ViewFileFrame = nil then
2793 begin
2794 ViewFileFrame := TViewFileFrame.Create(Self);
2795 ViewFileFrame.Parent := TabFiles;
2796 ViewFileFrame.Align := alRight;
2797
2798 SplitterBetweenViewFile := TSplitter.Create(Self);
2799 SplitterBetweenViewFile.Parent := TabFiles;
2800 SplitterBetweenViewFile.Align := alRight;
2801 end;
2802 ViewFileFrame.Enabled := true;
2803 ViewFileFrame.Visible := true;
2804 SplitterBetweenViewFile.Enabled := true;
2805 SplitterBetweenViewFile.Visible := true;
2806 end;
2807
2808 var
2809 SelectedFileName, SelectedURL: String;
2810 begin
2811 if ShellListView1.Selected <> nil then
2812 begin
2813 SelectedFileName := ShellListView1.GetPathFromItem(ShellListView1.Selected);
2814 SelectedURL := FilenameToUriSafe(SelectedFileName);
2815
2816 { Check for images first because TCastleScene can now load images. }
2817 if LoadImage_FileFilters.Matches(SelectedURL) then
2818 begin
2819 NeedsViewFile;
2820 ViewFileFrame.LoadImage(SelectedURL);
2821 Exit;
2822 end;
2823
2824 if TFileFilterList.Matches(LoadScene_FileFilters, SelectedURL) then
2825 begin
2826 NeedsViewFile;
2827 ViewFileFrame.LoadScene(SelectedURL);
2828 Exit;
2829 end;
2830
2831 if TFileFilterList.Matches(LoadSound_FileFilters, SelectedURL) then
2832 begin
2833 NeedsViewFile;
2834 ViewFileFrame.LoadSound(SelectedURL);
2835 Exit;
2836 end;
2837 end;
2838
2839 { if control reached here, hide ViewFileFrame if needed }
2840 if ViewFileFrame <> nil then
2841 begin
2842 ViewFileFrame.ClearLoaded; // stops playing preview sound
2843 ViewFileFrame.Enabled := false;
2844 ViewFileFrame.Visible := false;
2845 SplitterBetweenViewFile.Enabled := false;
2846 SplitterBetweenViewFile.Visible := false;
2847 end;
2848 end;
2849
2850 procedure TProjectForm.RunCustomCodeEditor(
2851 const CustomCodeEditorCommand: String; const PascalFileName: String;
2852 const Line: Integer; const Column: Integer);
2853
2854 { Copied from FPC packages/fcl-process/src/processbody.inc
2855 (licence "LGPL with static linking exception", so compatible with us). }
2856 procedure CommandToList(S : String; List : TStringList);
2857
2858 Function GetNextWord : String;
2859
2860 Const
2861 WhiteSpace = [' ',#9,#10,#13];
2862 Literals = ['"',''''];
2863
2864 Var
2865 Wstart,wend : Integer;
2866 InLiteral : Boolean;
2867 LastLiteral : Char;
2868
2869 begin
2870 WStart:=1;
2871 While (WStart<=Length(S)) and charinset(S[WStart],WhiteSpace) do
2872 Inc(WStart);
2873 WEnd:=WStart;
2874 InLiteral:=False;
2875 LastLiteral:=#0;
2876 While (Wend<=Length(S)) and (Not charinset(S[Wend],WhiteSpace) or InLiteral) do
2877 begin
2878 if charinset(S[Wend],Literals) then
2879 If InLiteral then
2880 InLiteral:=Not (S[Wend]=LastLiteral)
2881 else
2882 begin
2883 InLiteral:=True;
2884 LastLiteral:=S[Wend];
2885 end;
2886 inc(wend);
2887 end;
2888
2889 Result:=Copy(S,WStart,WEnd-WStart);
2890
2891 if (Length(Result) > 0)
2892 and (Result[1] = Result[Length(Result)]) // if 1st char = last char and..
2893 and (Result[1] in Literals) then // it's one of the literals, then
2894 Result:=Copy(Result, 2, Length(Result) - 2); //delete the 2 (but not others in it)
2895
2896 While (WEnd<=Length(S)) and (S[Wend] in WhiteSpace) do
2897 inc(Wend);
2898 Delete(S,1,WEnd-1);
2899
2900 end;
2901
2902 Var
2903 W : String;
2904
2905 begin
2906 While Length(S)>0 do
2907 begin
2908 W:=GetNextWord;
2909 If (W<>'') then
2910 List.Add(W);
2911 end;
2912 end;
2913 { End of copy from FPC. }
2914
2915 var
2916 Exe: String;
2917 Parameters: TCastleStringList;
2918 I: Integer;
2919 Macros: TStringStringMap;
2920 begin
2921 Parameters := TCastleStringList.Create;
2922 try
2923 CommandToList(CustomCodeEditorCommand, Parameters);
2924 if Parameters.Count = 0 then
2925 raise Exception.CreateFmt('Code editor command was split into zero items: "%s"', [CustomCodeEditorCommand]);
2926 Exe := Parameters[0];
2927 Parameters.Delete(0);
2928 Macros := TStringStringMap.Create;
2929 try
2930 Macros.Add('${PAS}', PascalFileName);
2931 Macros.Add('${STANDALONE_SOURCE}', ProjectStandaloneSource);
2932 Macros.Add('${PROJECT_DIR}', ProjectPath);
2933 if Line <> -1 then
2934 Macros.Add('${LINE}', IntToStr(Line));
2935 if Column <> -1 then
2936 Macros.Add('${COLUMN}', IntToStr(Column));
2937 for I := 0 to Parameters.Count - 1 do
2938 Parameters[I] := SReplacePatterns(Parameters[I], Macros, true);
2939 finally FreeAndNil(Macros) end;
2940 RunCommandNoWait(CreateTemporaryDir, Exe, Parameters.ToArray);
2941 finally FreeAndNil(Parameters) end;
2942 end;
2943
2944 function TProjectForm.IsRunning: Boolean;
2945 begin
2946 Result := RunningProcess <> nil;
2947 end;
2948
2949 procedure TProjectForm.RunningToggle(Sender: TObject);
2950 begin
2951 if RunningProcess = nil then
2952 MenuItemCompileRunClick(MenuItemCompileRun)
2953 else
2954 MenuItemStopProcessClick(MenuItemStopProcess);
2955 end;
2956
2957 procedure TProjectForm.OpenPascal(const FileName: String; Line: Integer;
2958 Column: Integer);
2959 var
2960 Exe, DelphiExe, VsCodeFileArgument: String;
2961 Ce: TCodeEditor;
2962 begin
2963 if CodeEditor = ceAutodetect then
2964 Ce := AutodetectCodeEditor
2965 else
2966 Ce := CodeEditor;
2967
2968 case Ce of
2969 ceCustom:
2970 begin
2971 if (Line <> -1) and
2972 (CodeEditorCommandLineColumn <> '') then
2973 begin
2974 if Column = -1 then
2975 Column := 1; // we don't have a command to open only at line, so use column = 1
2976 RunCustomCodeEditor(CodeEditorCommandLineColumn, FileName, Line, Column);
2977 end else
2978 RunCustomCodeEditor(CodeEditorCommand, FileName);
2979 end;
2980 ceLazarus:
2981 begin
2982 Exe := FindExeLazarusIDE;
2983
2984 if ProjectLazarus = '' then
2985 begin
2986 WritelnWarning('Lazarus project not defined (neither "standalone_source" nor "lazarus_project" were specified in CastleEngineManifest.xml), the file will be opened without changing Lazarus project.');
2987 RunCommandNoWait(CreateTemporaryDir, Exe, [FileName]);
2988 end else
2989 if not LazarusVersion.AtLeast(2, 2, 0) then
2990 begin
2991 { Before Lazarus 2.2, that brought fix to https://gitlab.com/freepascal.org/lazarus/lazarus/-/issues/39338 ,
2992 using LPI on the command-line didn't work OK.
2993
2994 Lazarus < 2.2 opens LPI as a regular XML file then, without changing the project.
2995 Moreover:
2996 - using LPR doesn't change the project either
2997 - using *only* LPI asks to change the project, even if it's already the current project
2998 (so we cannot fix the problem by executing it twice in a row, once with LPI once with PAS
2999 -- it would show dialog box every time)
3000 }
3001
3002 WritelnWarning('Lazarus is older than 2.2, file will be opened without changing Lazarus project.');
3003 RunCommandNoWait(CreateTemporaryDir, Exe, [FileName]);
3004 end else
3005 begin
3006 // pass both project name, and particular filename, to open file within this project.
3007 RunCommandNoWait(CreateTemporaryDir, Exe, [ProjectLazarus, FileName])
3008 end;
3009 end;
3010 ceDelphi:
3011 begin
3012 FindDelphiPath(true, DelphiExe);
3013
3014 { Open through DPROJ }
3015 (*
3016 if ProjectDelphi = '' then
3017 begin
3018 ErrorBox('Delphi project not defined (neither "standalone_source" nor "delphi_project" were specified in CastleEngineManifest.xml).' + NL +
3019 NL +
3020 'Create Delphi project (e.g. by "castle-engine generate-program") and update CastleEngineManifest.xml.');
3021 Exit;
3022 end;
3023 if not RegularFileExists(ProjectDelphi) then
3024 begin
3025 ErrorBox(Format('Delphi project file does not exist: %s.' + NL +
3026 NL +
3027 'Create Delphi project (by "castle-engine generate-program" or using Delphi).', [
3028 ProjectDelphi
3029 ]));
3030 Exit;
3031 end;
3032 *)
3033
3034 { We use DelphiExe, which is BDS.exe.
3035
3036 Notes:
3037
3038 - Do not use BDSLauncher.exe. BDSLauncher is defined in registry as the application
3039 doing "shell open", but using BDSLauncher is not so easy: we would need
3040 then to pass filename using DDE (Windows inter-process communication API).
3041 Using just BDS is simpler.
3042
3043 - Multiple filenames are not supported.
3044 We cannot point to the project *and* filename within, it seems.
3045 TODO: Need to use Delphi DDE for this?
3046
3047 - We cannot open in existing Delphi instance?
3048 TODO: Need to use Delphi DDE for this?
3049
3050 - Using /np doesn't work, in fact it makes the following filename ignored.
3051 Maybe BDS doesn't understand /np at all, and treats it as another filename?
3052 And only 1 filename is handler, as stated above.
3053 }
3054
3055 {$ifdef DELPHI_OPEN_SHELL}
3056 OpenDocument(FileName); // hack to open Pascal names in existing Delphi window, using DDE
3057 {$else}
3058 RunCommandNoWait(ProjectPath, DelphiExe, [
3059 FileName
3060 ]);
3061 {$endif}
3062
3063 end;
3064 ceVSCode:
3065 begin
3066 Exe := FindExeVSCode(true);
3067
3068 { Explanation of ExtractRelativePath:
3069
3070 We pass relative filenames, not absolute, to avoid
3071 VS Code on Windows inability to deal with spaces in filenames.
3072 Other solutions tried:
3073
3074 - calling code.exe without intermediate code.cmd
3075 - using vscode:// URL with spaces encoded using %20.
3076
3077 See EditorUtils -- nothing helped.
3078
3079 Using relative paths is a workaround, as long as you don't
3080 place Pascal code in subdirectory with spaces. }
3081 VsCodeFileArgument := ExtractRelativePath(ProjectPath, FileName);
3082
3083 { Explanation of '.':
3084
3085 How to open a project?
3086 -add would add project to workspace in current window.
3087 It avoids opening new window ever,
3088 but it seems more confusing than helpful in our case
3089 -- it creates multi-root workspace which may be surprising to users.
3090
3091 Instead we just pass project dir, as ".", to make sure this is
3092 opened as a workspace.
3093 See https://code.visualstudio.com/docs/editor/command-line ,
3094 https://stackoverflow.com/questions/29955785/opening-microsoft-visual-studio-code-from-command-prompt-windows
3095 //'--add'
3096 }
3097
3098 if Line <> -1 then
3099 begin
3100 VsCodeFileArgument += ':' + IntToStr(Line);
3101 if Column <> -1 then
3102 VsCodeFileArgument += ':' + IntToStr(Column);
3103 RunCommandNoWait(ProjectPath, Exe, ['.', '--goto', VsCodeFileArgument],
3104 [rcNoConsole]);
3105 end else
3106 RunCommandNoWait(ProjectPath, Exe, ['.', VsCodeFileArgument],
3107 [rcNoConsole]);
3108 end;
3109 else raise EInternalError.Create('CodeEditor?');
3110 end;
3111 end;
3112
3113 procedure TProjectForm.ShellListViewDoubleClick(Sender: TObject);
3114
3115 procedure OpenWithCastleTool(const ToolName: String;
3116 const SelectedURL: String;
3117 const Arguments: array of String);
3118 var
3119 Exe: String;
3120 begin
3121 Exe := FindExeCastleTool(ToolName);
3122 if Exe = '' then
3123 begin
3124 ErrorBox(Format('Cannot find Castle Game Engine tool "%s", opening "%s" failed. Make sure CGE is installed correctly, the tool should be distributed along with engine binary.',
3125 [ToolName, SelectedURL]));
3126 Exit;
3127 end;
3128
3129 RunCommandNoWait(CreateTemporaryDir, Exe, Arguments);
3130 end;
3131
3132 procedure OpenLazarusProject(const FileName: String);
3133 var
3134 Exe: String;
3135 begin
3136 Exe := FindExeLazarusIDE;
3137 RunCommandNoWait(CreateTemporaryDir, Exe, [FileName]);
3138 end;
3139
3140 var
3141 SelectedFileName, Ext, SelectedURL: String;
3142 begin
3143 { Forcefully stop dragging.
3144
3145 This workarounds LCL error with GTK 2 backend:
3146 1. if you open another design (xxx.castle-transform
3147 or xxx.castle-user-interface) by double-clicking (*not* by menu item "open...")
3148 2. and it causes a dialog box "save this design" (you can answer yes or no,
3149 doesn't matter)
3150 3. .. then the dragging remains "true" (even though you're no longer pressing
3151 down the mouse button).
3152
3153 This causes weird behavior if you then do some mouse-down + move + mouse-up
3154 in newly opened design.
3155 - e.g. mouse look by right-click on any viewport in newly opened design.
3156 - or left click (mouse down and up) anywhere on UI.
3157 ... They will all try to drag-and-drop the design you have just opened onto
3158 itself.
3159
3160 TODO: There remains a problem in the above case, even after this fix:
3161 First mouse down after such "forceful break of dragging" is not passed to TCastleControl.
3162 So you need to click again to actually start e.g. mouse look on a viewport.
3163 }
3164 if DragManager.IsDragging then
3165 begin
3166 DragManager.DragStop(false);
3167 WritelnLog('Forcefully breaking drag-and-drop on double-click to workaround LCL bug, afterwards IsDragging: %s', [
3168 BoolToStr(DragManager.IsDragging, true)
3169 ]);
3170 end;
3171
3172 if ShellListView1.Selected <> nil then
3173 begin
3174 SelectedFileName := ShellListView1.GetPathFromItem(ShellListView1.Selected);
3175 if DirectoryExists(SelectedFileName) then
3176 begin
3177 ShellTreeView1.Path := SelectedFileName;
3178 Exit;
3179 end;
3180
3181 SelectedURL := FilenameToUriSafe(SelectedFileName);
3182 Ext := ExtractFileExt(SelectedFileName);
3183
3184 { Check for images first because TCastleScene can now load images. }
3185 if LoadImage_FileFilters.Matches(SelectedURL) then
3186 begin
3187 OpenWithCastleTool('castle-image-viewer', SelectedURL, [SelectedURL]);
3188 Exit;
3189 end;
3190
3191 { Check for Castle Sprite Sheets, to open them in sprite editor }
3192 if (UriMimeType(SelectedURL) = 'application/x-castle-sprite-sheet') then
3193 begin
3194 if SpriteSheetEditorForm = nil then
3195 SpriteSheetEditorForm := TSpriteSheetEditorForm.Create(Application);
3196 SpriteSheetEditorForm.Show;
3197 SpriteSheetEditorForm.OpenSpriteSheet(SelectedURL, true);
3198 Exit;
3199 end;
3200
3201 if TFileFilterList.Matches(LoadScene_FileFilters, SelectedURL) then
3202 begin
3203 OpenWithCastleTool('castle-model-viewer', SelectedURL,
3204 ['--project', ProjectPathUrl, SelectedURL]);
3205 Exit;
3206 end;
3207
3208 if AnsiSameText(Ext, '.castle-user-interface') or
3209 AnsiSameText(Ext, '.castle-transform') or
3210 AnsiSameText(Ext, '.castle-component') then
3211 begin
3212 ProposeOpenDesign(SelectedURL);
3213 Exit;
3214 end;
3215
3216 if AnsiSameText(Ext, '.pas') or
3217 AnsiSameText(Ext, '.inc') or
3218 AnsiSameText(Ext, '.pp') or
3219 AnsiSameText(Ext, '.lpr') or
3220 AnsiSameText(Ext, '.dpr') then
3221 begin
3222 OpenPascal(SelectedFileName);
3223 Exit;
3224 end;
3225
3226 if AnsiSameText(Ext, '.lpi') then
3227 begin
3228 OpenLazarusProject(SelectedFileName);
3229 Exit;
3230 end;
3231
3232 if not OpenDocument(SelectedFileName) then
3233 ErrorBox(Format('Opening "%s" failed.', [SelectedFileName]));
3234 end;
3235 end;
3236
3237 procedure TProjectForm.BuildToolCall(const Commands: array of String;
3238 const RestartOnSuccess: Boolean);
3239
3240 procedure AddPlatformParameters(const Params: TStrings; const PlatformInfo: TPlatformInfo);
3241 begin
3242 if (PlatformInfo.Target = targetCustom) and
3243 (PlatformInfo.OS = DefaultOS) and
3244 (PlatformInfo.CPU = DefaultCPU) then
3245 // keep command-line simple, to be simpler for user; no point is adding extra parameters
3246 Exit;
3247
3248 if PlatformInfo.Target <> targetCustom then
3249 begin
3250 Params.Add('--target=' + TargetToString(PlatformInfo.Target));
3251 end else
3252 begin
3253 Params.Add('--os=' + OSToString(PlatformInfo.OS));
3254 Params.Add('--cpu=' + CPUToString(PlatformInfo.CPU));
3255 end;
3256 end;
3257
3258 procedure AddModeParameters(const Params: TStrings);
3259 var
3260 ModeString: String;
3261 begin
3262 case BuildMode of
3263 bmDebug : ModeString := '--mode=debug';
3264 bmRelease: ModeString := '--mode=release';
3265 {$ifndef COMPILER_CASE_ANALYSIS}
3266 else raise EInternalError.Create('BuildMode?');
3267 {$endif}
3268 end;
3269 Params.Add(ModeString);
3270 end;
3271
3272 procedure AddCompilerParameters(const Params: TStrings);
3273 begin
3274 if Compiler <> DefaultCompiler then
3275 Params.Add('--compiler=' + CompilerToString(Compiler));
3276 end;
3277
3278 procedure AddPackageFormatParameters(const Params: TStrings; const Format: TPackageFormat);
3279 begin
3280 if Format <> pfDefault then
3281 Params.Add('--package-format=' + PackageFormatToString(Format));
3282 end;
3283
3284 { Add parameters for "castle-engine run".
3285 Call it last, because it has to add also "--" that delimits build tool params
3286 from application params. }
3287 procedure AddRunParameters(const Params: TStrings);
3288 begin
3289 Params.Add('--');
3290 if ActionRunParameterDisableSound.Checked then
3291 Params.Add('--no-sound');
3292 if ActionRunParameterDisableFpsLimit.Checked then
3293 Params.Add('--no-limit-fps');
3294 if ActionRunParameterPretendTouchDevice.Checked then
3295 Params.Add('--pretend-touch-device');
3296 if ActionRunParameterRequestFullScreen.Checked then
3297 Params.Add('--fullscreen');
3298 if ActionRunParameterRequestWindow.Checked then
3299 Params.Add('--window');
3300 if ActionRunParameterCapabilitiesForceFixedFunction.Checked then
3301 Params.Add('--capabilities=force-fixed-function');
3302 if ActionRunParameterCapabilitiesForceModern.Checked then
3303 Params.Add('--capabilities=force-modern');
3304 end;
3305
3306 var
3307 BuildToolExe, Command: String;
3308 QueueItem: TAsynchronousProcessQueue.TQueueItem;
3309 begin
3310 if RunningProcess <> nil then
3311 raise EInternalError.Create('It should not be possible to call this when RunningProcess <> nil');
3312
3313 BuildToolExe := FindExeCastleTool('castle-engine');
3314 if BuildToolExe = '' then
3315 begin
3316 ErrorBox('Cannot find build tool (castle-engine). Set the $CASTLE_ENGINE_PATH or $PATH environment variables or place all tools in CGE bin/ subdirectory.');
3317 Exit;
3318 end;
3319
3320 OutputList.Clear;
3321 PageControlBottom.ActivePage := TabOutput;
3322 ProcessUpdateTimer.Enabled := true;
3323
3324 RunningProcess := TAsynchronousProcessQueue.Create;
3325 RunningProcess.OutputList := OutputList;
3326
3327 for Command in Commands do
3328 begin
3329 QueueItem := TAsynchronousProcessQueue.TQueueItem.Create;
3330 QueueItem.ExeName := BuildToolExe;
3331 QueueItem.CurrentDirectory := ProjectPath;
3332 QueueItem.Parameters.Add(Command);
3333 // add --mode=xxx parameter
3334 if not (
3335 (Command = 'package-source') or
3336 (Command = 'clean') or
3337 (Command = 'auto-generate-textures') or
3338 (Command = 'auto-generate-clean') or
3339 (Command = 'generate-program') or
3340 (Command = 'editor') or
3341 (Command = 'editor-rebuild-if-needed') or
3342 (Command = 'editor-run') or
3343 (Command = 'cache')
3344 ) then
3345 AddModeParameters(QueueItem.Parameters);
3346 // add --compiler parameter
3347 if (Command = 'compile') or
3348 (Command = 'package') then
3349 AddCompilerParameters(QueueItem.Parameters);
3350 // add --target, --os, --cpu parameters
3351 if (Command = 'compile') or
3352 (Command = 'run') or
3353 (Command = 'package') or
3354 (Command = 'install') or
3355 (Command = 'cache') then
3356 AddPlatformParameters(QueueItem.Parameters, PlatformsInfo[CurrentPlatformInfo]);
3357 // add --package-format
3358 if (Command = 'package') or
3359 (Command = 'install') then
3360 AddPackageFormatParameters(QueueItem.Parameters, CurrentPackageFormat);
3361 // editor always add --fast to package, as its more comfortable for normal development
3362 if (Command = 'package') then
3363 QueueItem.Parameters.Add('--fast');
3364 // add --target, --os, --cpu parameters
3365 if (Command = 'run') then
3366 AddRunParameters(QueueItem.Parameters);
3367 RunningProcess.Queue.Add(QueueItem);
3368 end;
3369
3370 if RestartOnSuccess then
3371 RunningProcess.OnSuccessfullyFinishedAll := @RestartEditor;
3372 RunningProcess.OnFinished := @BuildToolCallFinished;
3373
3374 RunningProcess.Start;
3375
3376 IsRunningChanged;
3377 end;
3378
3379 procedure TProjectForm.RestartEditor(Sender: TObject);
3380 var
3381 BuildToolExe: String;
3382 begin
3383 if ProposeSaveDesign then
3384 begin
3385 { Run custom editor, and finish current process.
3386 We use --wait-for-process-exit primarily because on Windows,
3387 we need to "unlock" the exe, to be able to copy new exe over the old exe
3388 (otherwise recompiling the custom editor could not just place
3389 new editor at the same exe).
3390 It is also sensible on all platforms, to make sure previous editor closes
3391 stuf (e.g. config files) reliably. }
3392 BuildToolExe := FindExeCastleTool('castle-engine');
3393 if BuildToolExe = '' then
3394 begin
3395 ErrorBox('Cannot find build tool (castle-engine). Set the $CASTLE_ENGINE_PATH or $PATH environment variables or place all tools in CGE bin/ subdirectory.');
3396 Exit;
3397 end;
3398
3399 RunCommandNoWait(ProjectPath, BuildToolExe,
3400 ['editor-run', '--gui-errors', '--wait-for-process-exit', IntToStr(CurrentProcessId)],
3401 [rcNoConsole]);
3402
3403 { Once ProposeSaveDesign and RunCommandNoWait are both successful,
3404 we want to terminate ASAP as user is waiting for new editor to run. }
3405 Application.Terminate;
3406 end;
3407 end;
3408
3409 procedure TProjectForm.BuildToolCallFinished(Sender: TObject);
3410 begin
3411 // bring back volume, in case MuteOnRun
3412 RunningApplication := false;
3413 SoundEngineSetVolume;
3414 RefreshFiles(rfFilesInCurrentDir); // show new files created by "package"
3415 end;
3416
3417 procedure TProjectForm.MenuItemAddComponentClick(Sender: TObject);
3418 var
3419 R: TRegisteredComponent;
3420 begin
3421 R := TRegisteredComponent(Pointer((Sender as TComponent).Tag));
3422 Design.AddComponent(R.ComponentClass, R.OnCreate);
3423 end;
3424
3425 procedure TProjectForm.MenuItemDesignNewCustomRootClick(Sender: TObject);
3426 var
3427 R: TRegisteredComponent;
3428 begin
3429 if not IsCreatingNewDesignAvailable then
3430 Exit;
3431
3432 if ProposeSaveDesign then
3433 begin
3434 R := TRegisteredComponent(Pointer((Sender as TComponent).Tag));
3435 NewDesign(R.ComponentClass, R.OnCreate);
3436 end;
3437 end;
3438
3439 procedure TProjectForm.IsRunningChanged;
3440 var
3441 EnableRun: Boolean;
3442 begin
3443 EnableRun := not IsRunning;
3444
3445 MenuItemCompile.Enabled := EnableRun;
3446 MenuItemCompileRun.Enabled := EnableRun;
3447 MenuItemOnlyRun.Enabled := EnableRun;
3448 MenuItemClean.Enabled := EnableRun;
3449 MenuItemPackage.Enabled := EnableRun;
3450 MenuItemPackageSource.Enabled := EnableRun;
3451 MenuItemInstall.Enabled := EnableRun;
3452 MenuItemAutoGenerateTextures.Enabled := EnableRun;
3453 MenuItemAutoGenerateClean.Enabled := EnableRun;
3454 MenuItemRestartRebuildEditor.Enabled := EnableRun;
3455 MenuItemCache.Enabled := EnableRun;
3456 MenuItemCacheClean.Enabled := EnableRun;
3457 ActionRegenerateProject.Enabled := EnableRun;
3458
3459 MenuItemStopProcess.Enabled := not EnableRun;
3460
3461 // Looks like we need to call this manually
3462 // (to update because of ActionPlayStopExecute or when process starts/stops independently)
3463 if Design <> nil then
3464 Design.ActionPlayStopUpdate(Design.ActionPlayStop);
3465 end;
3466
3467 procedure TProjectForm.UpdateFormCaption(Sender: TObject);
3468 var
3469 S: String;
3470 begin
3471 if Design <> nil then
3472 S := Design.FormCaption
3473 else
3474 S := '';
3475 S := S + SQuoteLCLCaption(ProjectName);
3476 if InternalCustomComponentsForProject <> '' then
3477 begin
3478 if InternalCustomComponentsForProject = ProjectName then
3479 S := S + ' (With Custom Components)'
3480 else
3481 S := S + ' (With Custom Components from ' + InternalCustomComponentsForProject + ')';
3482 end;
3483 Caption := S + ' | Castle Game Engine';
3484 end;
3485
3486 function TProjectForm.ProposeSaveDesign: Boolean;
3487 var
3488 Mr: TModalResult;
3489 DesignName: String;
3490 begin
3491 Result := true;
3492
3493 if Design <> nil then
3494 begin
3495 Design.BeforeProposeSaveDesign;
3496 if Design.DesignModified then
3497 begin
3498 if Design.DesignUrl <> '' then
3499 DesignName := '"' + Design.DesignUrl + '"'
3500 else
3501 DesignName := '<unnnamed>';
3502 Mr := MessageDlg('Save Design',
3503 'Design ' + DesignName + ' was modified but not saved yet. Save it now?',
3504 mtConfirmation, mbYesNoCancel, 0);
3505 case Mr of
3506 mrYes: MenuItemSaveDesign.Click;
3507 mrCancel: Result := false;
3508 end;
3509 end;
3510 end;
3511 end;
3512
3513 procedure TProjectForm.OpenProject(const ManifestUrl: String);
3514 begin
3515 { Below we assume ManifestUrl contains an absolute path,
3516 otherwise ProjectPathUrl could be '',
3517 and OpenDesignDialog.InitialDir would be left '' and so on. }
3518
3519 FreeAndNil(Manifest); // free previous manifest, if any
3520 Manifest := TCastleManifest.CreateFromUrl(ManifestUrl);
3521
3522 ProjectName := Manifest.Name;
3523 ProjectPath := Manifest.Path;
3524 ProjectPathUrl := Manifest.PathUrl;
3525 ProjectStandaloneSource := Manifest.StandaloneSource;
3526 ProjectLazarus := Manifest.LazarusProject;
3527 ProjectDelphi := Manifest.DelphiProject;
3528
3529 { Make some fields absolute paths, or empty }
3530 if ProjectStandaloneSource <> '' then
3531 ProjectStandaloneSource := CombinePaths(ProjectPath, ProjectStandaloneSource);
3532 if ProjectLazarus <> '' then
3533 ProjectLazarus := CombinePaths(ProjectPath, ProjectLazarus);
3534 if ProjectDelphi <> '' then
3535 ProjectDelphi := CombinePaths(ProjectPath, ProjectDelphi);
3536
3537 { override ApplicationData interpretation, and castle-data:/xxx URL,
3538 while this project is open. }
3539 ApplicationDataOverride := CombineUri(ProjectPathUrl, 'data/');
3540
3541 { adjust some InitialDir values to make open dialogs natural }
3542 OpenDesignDialog.InitialDir := UriToFilenameSafe(ApplicationDataOverride);
3543 SaveDesignDialog.InitialDir := UriToFilenameSafe(ApplicationDataOverride);
3544 OpenPascalUnitDialog.InitialDir := ProjectPath;
3545
3546 ShellTreeView1.Root := ProjectPath;
3547
3548 // It's too easy to change it visually and forget, so we set it from code
3549 PageControlBottom.ActivePage := TabFiles;
3550 IsRunningChanged;
3551
3552 BuildMode := bmDebug;
3553 MenuItemModeDebug.Checked := true;
3554
3555 DesignExistenceChanged;
3556 UpdateFormCaption(nil); // make form Caption reflect project name (although this is now done also by DesignExistenceChanged)
3557
3558 if (Manifest.EditorUnits <> '') and
3559 (ProjectName <> InternalCustomComponentsForProject) then
3560 begin
3561 RestartCustomEditorForm.Initialize(ProjectName, ProjectPath);
3562 case RestartCustomEditorForm.ShowModal of
3563 mrOK: MenuItemRestartRebuildEditorClick(nil);
3564 mrYesToAll: RestartEditor(nil);
3565 end;
3566 //WritelnWarning('Project uses custom components (declares editor_units in CastleEngineManifest.xml), but this is not a custom editor build.' + NL + 'Use the menu item "Project -> Restart Editor (With Custom Components)" to build and run correct editor.');
3567 end;
3568 end;
3569
3570 procedure TProjectForm.RefreshAllFiles(Sender: TObject);
3571 begin
3572 RefreshFiles(rfEverything);
3573 end;
3574
3575 procedure TProjectForm.RefreshFiles(const RefreshNecessary: TRefreshFiles);
3576 var
3577 DirToRefresh, ErrorStr, TreeViewPath, SavedSelectedFileNameInRoot: String;
3578 SavedListViewOrigin: TPoint;
3579 begin
3580 DirToRefresh := CombinePaths(ShellTreeView1.Root, ShellTreeView1.Path);
3581 if not DirectoryExists(DirToRefresh) then
3582 begin
3583 ErrorStr := Format('Directory "%s" no longer exists.', [DirToRefresh]);
3584 if not ErrorShownRefreshFilesMissingDirectory then
3585 begin
3586 { Set it before showing ErrorBox,
3587 as going back from ErrorBox can again cause this method to be called,
3588 so it may be in recursive call. }
3589 ErrorShownRefreshFilesMissingDirectory := true;
3590 ErrorBox(ErrorStr + NL +
3591 NL +
3592 'Further errors about this will be only shown as warnings.');
3593 end else
3594 WritelnWarning(ErrorStr);
3595 Exit;
3596 end;
3597
3598 { save and restore selected file when refreshing.
3599 This way Alt+Tab doesn't deselect file. }
3600 SavedSelectedFileNameInRoot := ShellListView1.SelectedFileNameInRoot;
3601 SavedListViewOrigin := ShellListView1.ViewOrigin;
3602 Inc(ShellListViewUpdating);
3603
3604 try
3605 ShellListView1.RefreshContents;
3606
3607 { It is important to refresh ShellTreeView1 e.g. when new directory
3608 was added, otherwise user could not navigate
3609 into newly created directories, since they must exist in ShellTreeView1. }
3610
3611 case RefreshNecessary of
3612 { Unfortunately this special implementation of "refresh current dir"
3613 doesn't work for non-root directories. }
3614 //rfEverythingInCurrentDir:
3615 // ShellTreeView1.Refresh(ShellTreeView1.Selected);
3616 rfEverythingInCurrentDir, rfEverything:
3617 begin
3618 TreeViewPath := ShellTreeView1.Path;
3619 ShellTreeView1.Refresh(nil);
3620 ShellTreeView1.Path := TreeViewPath;
3621 end;
3622 else ; // no need to do for others
3623 end;
3624
3625 ShellListView1.SelectedFileNameInRoot := SavedSelectedFileNameInRoot;
3626 ShellListView1.ViewOrigin := SavedListViewOrigin;
3627
3628 finally
3629 { we update ViewFileFrame after everything is done,
3630 this way it doesn't blink off/on when doing Alt+Tab }
3631 Dec(ShellListViewUpdating);
3632 if ShellListViewUpdating = 0 then
3633 ViewFileFrameUpdate;
3634 end;
3635 end;
3636
3637 procedure TProjectForm.MenuItemPlatformChangeClick(Sender: TObject);
3638 var
3639 Mi: TMenuItem;
3640 begin
3641 Mi := Sender as TMenuItem;
3642 CurrentPlatformInfo := Mi.Tag;
3643 Mi.Checked := true;
3644 end;
3645
3646 procedure TProjectForm.MenuItemPackageFormatChangeClick(Sender: TObject);
3647 var
3648 Mi: TMenuItem;
3649 begin
3650 Mi := Sender as TMenuItem;
3651 CurrentPackageFormat := TPackageFormat(Mi.Tag);
3652 Mi.Checked := true;
3653 end;
3654
3655 function TProjectForm.CanAddImported(const AddUrl: String): Boolean;
3656 begin
3657 { TODO: Maybe in the future it will query more,
3658 e.g. to add glTF we need Design.AddImportedUrl be able to determine
3659 parent that is TCastleTransform descendant.
3660 For now we let Design.AddImportedUrl to raise exception in such case. }
3661 Result := Design <> nil;
3662 end;
3663
3664 procedure TProjectForm.AddImported(const AddUrl: String);
3665 begin
3666 if Design <> nil then
3667 begin
3668 if Design.AddImported(AddUrl) = nil then
3669 ErrorBox(Format('Coult not import "%s". Make sure the current design has a viewport selected', [
3670 UriDisplay(AddUrl)
3671 ]));
3672 end;
3673 end;
3674
3675 initialization
3676 // initialize CGE log
3677 ApplicationProperties.ApplicationName := 'castle-editor';
3678 // Useful for testing of custom editor run by "Restart Editor", to see the log easily on Unix
3679 // LogFileName := FileNameAutoInc('/tmp/castle-editor-%d.log');
3680 InitializeLog;
3681 end.