Debian Codegraph @

tools/castle-editor/code/framedesign.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 { Frame where you can design
17 a xxx.castle-user-interface, xxx.castle-transform, xxx.castle-component file. }
18 unit FrameDesign;
19
20 {$I castleconf.inc}
21
22 interface
23
24 uses
25 Classes, SysUtils, FileUtil, Forms, Controls, ExtCtrls, StdCtrls, ComCtrls,
26 Spin, Buttons, Menus, ActnList, Contnrs, Generics.Collections,
27 // for icons
28 DataModuleIcons, ImgList,
29 // for TOIPropertyGrid usage
30 ObjectInspector, PropEdits, PropEditUtils, GraphPropEdits,
31 CollectionPropEditForm, ComponentEditors,
32 // CGE units
33 CastleControl, CastleUIControls, CastlePropEdits, CastleDialogs,
34 CastleSceneCore, CastleKeysMouse, CastleVectors, CastleRectangles,
35 CastleViewport, CastleClassUtils, CastleControls, CastleTiledMap,
36 CastleCameras, CastleBoxes, CastleTransform, CastleDebugTransform,
37 CastleColors, CastleScene, CastleRenderOptions, CastleEditorPropEdits,
38 // editor units
39 FrameAnchors, CastleShellCtrls, EditorUtils,
40 DesignVisualizeTransform, DesignUndoSystem, DesignCameraPreview,
41 DesignObjectInspector;
42
43 type
44 TProposeOpenDesignEvent = procedure (const DesignUrl: String) of object;
45
46 TBooleanEvent = function: Boolean of object;
47
48 TMode = (
49 moInteract,
50 moSelect,
51 moTranslate,
52 moRotate,
53 moScale
54 );
55
56 { Frame to visually design component hierarchy. }
57 TDesignFrame = class(TFrame)
58 ActionApiReferenceOfCurrent: TAction;
59 ActionPlayStop: TAction;
60 ActionSimulationPauseUnpause: TAction;
61 ActionSimulationPlayStop: TAction;
62 ActionListDesign: TActionList;
63 ButtonResetTransformation: TButton;
64 ButtonClearTranslation: TButton;
65 ButtonPlayStop: TSpeedButton;
66 ButtonApiReferenceForCurrent: TSpeedButton;
67 EditFindInHierarchy: TEdit;
68 LabelPhysics: TLabel;
69 LabelPlayStop: TLabel;
70 LabelViewport: TLabel;
71 LabelHeaderUi: TLabel;
72 LabelEventsInfo: TLabel;
73 LabelSimulation: TLabel;
74 LabelSizeInfo: TLabel;
75 MemoInfo: TMemo;
76 PanelSpinEditAllowVerticalCentering: TPanel;
77 SeparatorBeforeChangeClass: TMenuItem;
78 MenuItemChangeClassUserInterface: TMenuItem;
79 MenuItemChangeClassNonVisual: TMenuItem;
80 MenuItemChangeClassTransform: TMenuItem;
81 MenuItemChangeClassBehavior: TMenuItem;
82 MenuTreeViewItemSaveSelected: TMenuItem;
83 MenuSeparator1: TMenuItem;
84 MenuTreeViewItemCut: TMenuItem;
85 MenuItemSeparator898989: TMenuItem;
86 MenuTreeViewItemSeparator127u30130120983: TMenuItem;
87 MenuTreeViewItemAddNonVisual: TMenuItem;
88 MenuTreeViewItemAddBehavior: TMenuItem;
89 MenuTreeViewItemRename: TMenuItem;
90 MenuTreeViewItemAddTransform: TMenuItem;
91 MenuTreeViewItemAddUserInterface: TMenuItem;
92 MenuTreeViewItemDelete: TMenuItem;
93 MenuTreeViewItemPaste: TMenuItem;
94 MenuTreeViewItemCopy: TMenuItem;
95 MenuTreeViewItemDuplicate: TMenuItem;
96 MenuItemSeparator1: TMenuItem;
97 PanelLayoutTop: TPanel;
98 PanelLayoutTransform: TPanel;
99 PanelEventsInfo: TPanel;
100 PanelAnchors: TPanel;
101 MenuTreeView: TPopupMenu;
102 SaveDesignDialog: TCastleSaveDialog;
103 SelfAnchorsFrame: TAnchorsFrame;
104 ParentAnchorsFrame: TAnchorsFrame;
105 CheckParentSelfAnchorsEqual: TCheckBox;
106 ControlProperties: TPageControl;
107 ControlsTree: TTreeView;
108 LabelControlSelected: TLabel;
109 LabelHierarchy: TLabel;
110 PanelMiddleTop: TPanel;
111 PanelMiddle: TPanel;
112 PanelLeft: TPanel;
113 PanelRight: TPanel;
114 ButtonInteractMode: TSpeedButton;
115 ButtonSimulationPlayStop: TSpeedButton;
116 ButtonSimulationPause: TSpeedButton;
117 ButtonSelectMode: TSpeedButton;
118 ButtonTranslateMode: TSpeedButton;
119 ButtonRotateMode: TSpeedButton;
120 ButtonScaleMode: TSpeedButton;
121 SpinEditSnap: TSpinEdit;
122 Splitter1: TSplitter;
123 TabLayoutScrollBox: TScrollBox;
124 SplitterLeft: TSplitter;
125 SplitterRight: TSplitter;
126 TabAll: TTabSheet;
127 TabEvents: TTabSheet;
128 TabLayout: TTabSheet;
129 TabBasic: TTabSheet;
130 TabInfo: TTabSheet;
131 UpdateObjectInspector: TTimer;
132 procedure ActionApiReferenceOfCurrentExecute(Sender: TObject);
133 procedure ActionPlayStopExecute(Sender: TObject);
134 procedure ActionPlayStopUpdate(Sender: TObject);
135 procedure ActionSimulationPauseUnpauseExecute(Sender: TObject);
136 procedure ActionSimulationPauseUnpauseUpdate(Sender: TObject);
137 procedure ActionSimulationPlayStopExecute(Sender: TObject);
138 procedure ActionSimulationPlayStopUpdate(Sender: TObject);
139 procedure ButtonClearTranslationClick(Sender: TObject);
140 procedure ButtonResetTransformationClick(Sender: TObject);
141 procedure ButtonRotateModeClick(Sender: TObject);
142 procedure ButtonScaleModeClick(Sender: TObject);
143 procedure ButtonSelectModeClick(Sender: TObject);
144 procedure ButtonTranslateModeClick(Sender: TObject);
145 procedure CheckParentSelfAnchorsEqualChange(Sender: TObject);
146 procedure ControlsTreeAdvancedCustomDrawItem(Sender: TCustomTreeView;
147 Node: TTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage;
148 var PaintImages, DefaultDraw: Boolean);
149 procedure ControlsTreeDragDrop(Sender, Source: TObject; X, Y: Integer);
150 procedure ControlsTreeDragOver(Sender, Source: TObject; X, Y: Integer;
151 State: TDragState; var Accept: Boolean);
152 procedure ControlsTreeEditing(Sender: TObject; Node: TTreeNode;
153 var AllowEdit: Boolean);
154 procedure ControlsTreeEditingEnd(Sender: TObject; Node: TTreeNode;
155 Cancel: Boolean);
156 procedure ControlsTreeEndDrag(Sender, Target: TObject; X, Y: Integer);
157 procedure ControlsTreeSelectionChanged(Sender: TObject);
158 procedure ButtonInteractModeClick(Sender: TObject);
159 procedure EditFindInHierarchyChange(Sender: TObject);
160 procedure FrameResize(Sender: TObject);
161 procedure MenuItemAddComponentClick(Sender: TObject);
162 procedure MenuTreeViewItemCutClick(Sender: TObject);
163 procedure MenuTreeViewItemRenameClick(Sender: TObject);
164 procedure MenuTreeViewItemDeleteClick(Sender: TObject);
165 procedure MenuTreeViewItemCopyClick(Sender: TObject);
166 procedure MenuTreeViewItemDuplicateClick(Sender: TObject);
167 procedure MenuTreeViewItemPasteClick(Sender: TObject);
168 procedure MenuTreeViewItemSaveSelectedClick(Sender: TObject);
169 procedure MenuTreeViewPopup(Sender: TObject);
170 procedure ClearDesign;
171 procedure RenameSelectedItem;
172 procedure PerformUndoRedo(const UHE: TUndoHistoryElement);
173 procedure PerformRedo;
174 procedure PerformUndo;
175 procedure UpdateObjectInspectorTimer(Sender: TObject);
176 protected
177 procedure SetParent(AParent: TWinControl); override;
178 private
179 type
180 { UI layer that can intercept mouse clicks and drags. }
181 TDesignerLayer = class(TCastleUserInterface)
182 strict private
183 type
184 TUiDraggingMode = (dmNone, dmTranslate, dmResize);
185 var
186 UiPendingMove: TVector2;
187 UiDraggingMode: TUiDraggingMode;
188 ResizingHorizontal: THorizontalPosition; //< Defined only when UiDraggingMode=dmResize
189 ResizingVertical: TVerticalPosition; //< Defined only when UiDraggingMode=dmResize
190 LabelHover, LabelSelected, LabelStatistics: TCastleLabel;
191 RectHover, RectSelected, RectStatistics: TCastleRectangleControl;
192 { Should clicking inside UI rectangle start resizing (not only moving?). }
193 function IsResizing(const UI: TCastleUserInterface; const Position: TVector2;
194 out Horizontal: THorizontalPosition;
195 out Vertical: TVerticalPosition; out Hint: String): Boolean;
196 function IsResizing(const UI: TCastleUserInterface; const Position: TVector2;
197 out Horizontal: THorizontalPosition;
198 out Vertical: TVerticalPosition): Boolean;
199 public
200 Frame: TDesignFrame;
201 LayerPhysicsSimulation: TCastleUserInterface;
202 LabelPhysicsSimulationRunning: TCastleLabel;
203 LabelPhysicsSimulationPaused: TCastleLabel;
204 constructor Create(AOwner: TComponent); override;
205 function Press(const Event: TInputPressRelease): Boolean; override;
206 function Release(const Event: TInputPressRelease): Boolean; override;
207 function Motion(const Event: TInputMotion): Boolean; override;
208 procedure Render; override;
209
210 { UI under given mouse position.
211 AMousePosition is in coordinates local to TCastleControl and follows
212 CGE conventions that Y goes from bottom to top.
213
214 Note: In most cases, prefer to call HoverComponent.
215 HoverUserInterface *does not* consider transforms within TCastleViewport,
216 it will just return TCastleViewport if mouse is over it.
217
218 @param(EnterNestedDesigns If @true, we enter children loaded by TCastleDesign,
219 in TCastleDesign.Design. This should almost never be used: such children
220 are not selectable, their names may collide with names in main design etc.) }
221 function HoverUserInterface(const AMousePosition: TVector2;
222 const EnterNestedDesigns: Boolean = false): TCastleUserInterface;
223
224 { UI or transform under given mouse position.
225 AMousePosition is like for HoverUserInterface. }
226 function HoverComponent(const AMousePosition: TVector2): TCastleComponent;
227 end;
228
229 TTreeNodeMap = class(specialize TDictionary<TComponent, TTreeNode>)
230 end;
231
232 TTreeNodeSide = (tnsInside, tnsBottom, tnsTop);
233
234 TInspectorType = (itBasic, itLayout, itEvents, itAll);
235
236 var
237 Inspector: array [TInspectorType] of TCastleObjectInspector;
238 FUndoSystem: TUndoSystem;
239 PropertyEditorHook: TCastlePropertyEditorHook;
240 FDesignUrl: String;
241 FDesignRoot: TComponent;
242 { Viewport created for editing design with FDesignRoot being TCastleTransform. }
243 FDesignViewportForTransforms: TCastleViewport;
244 { Owner of all components saved/loaded to the design file.
245 Also owner of a temporary viewport for .castle-transform,
246 in general this owns everything specific to display currrent design. }
247 DesignOwner: TComponent;
248 { If design is visual (DesignRoot is TCastleUserInterface or
249 TCastleTransform) then this is non-nil and allows to visualize
250 alternative selected camera view. }
251 CameraPreview: TCameraPreview;
252 FDesignerLayer: TDesignerLayer;
253 FDesignModified: Boolean;
254 CastleControl: TCastleControl;
255 TreeNodeMap: TTreeNodeMap;
256 Mode: TMode;
257 InsideToggleModeClick: Boolean;
258 ControlsTreeNodeUnderMouse: TTreeNode;
259 ControlsTreeNodeUnderMouseSide: TTreeNodeSide;
260 PendingErrorBox: String;
261 VisualizeTransformHover: TVisualizeTransformHover;
262 VisualizeTransformSelected: TVisualizeTransformSelected;
263 CollectionPropertyEditorForm: TCollectionPropertyEditorForm;
264 DesignStateBeforePhysicsRun: String;
265 DesignModifiedBeforePhysicsRun: Boolean;
266 FCurrentViewport: TCastleViewport;
267 FCurrentViewportObserver: TFreeNotificationObserver;
268 FComponentEditorDesigner: TComponentEditorDesigner;
269 (*
270 // The TransformDesigning mechanism works, but it unused for now.
271 FTransformDesigning: TCastleTransform;
272 FTransformDesigningObserver: TFreeNotificationObserver;
273 *)
274
275 // Last selected components (with AutoSelectParents=true)
276 LastSelected: TComponentList;
277 FShowColliders: Boolean;
278 FindActive: Boolean;
279
280 { Create and add to the designed parent a new component,
281 whose type best matches currently selected file in SourceShellList.
282 May return @nil (and do nothing) if the SourceShellList does not
283 have a suitable file selected for the given parent. }
284 function ShellListAddComponent(
285 const SourceShellList: TCastleShellListView;
286 const ParentComponent: TComponent): TComponent;
287 { Returns exactly the class that will be returned by
288 ShellListAddComponent for the same arguments.
289 May return @nil exactly if ShellListAddComponent also returns @nil. }
290 function ShellListComponentClass(
291 const SourceShellList: TCastleShellListView;
292 const ParentComponent: TComponent): TComponentClass;
293
294 (*
295 // The TransformDesigning mechanism works, but it unused for now.
296
297 procedure SetTransformDesigning(const Value: TCastleTransform);
298 procedure TransformDesigningFreeNotification(const Value: TFreeNotificationObserver);
299 { For this transform we display design-time helpers (e.g. to edit joints' anchors),
300 using TCastleBehavior.DesigningBegin and TCastleBehavior.DesigningEnd. }
301 property TransformDesigning: TCastleTransform
302 read FTransformDesigning write SetTransformDesigning;
303 *)
304
305 function CameraToSynchronize(const V: TCastleViewport): TCastleCamera;
306 procedure CameraSynchronize(const Source, Target: TCastleCamera; const MakeUndo: Boolean);
307 procedure CastleControlOpen(Sender: TObject);
308 procedure CastleControlResize(Sender: TObject);
309 procedure CastleControlUpdate(Sender: TObject);
310 procedure CastleControlDragOver(Sender, Source: TObject; X, Y: Integer;
311 State: TDragState; var Accept: Boolean);
312 procedure CastleControlDragDrop(Sender, Source: TObject; X, Y: Integer);
313 procedure CollectionPropertyEditorFormUnassign;
314 function ComponentCaption(const C: TComponent): String;
315 function TreeNodeCaption(const C: TComponent): String;
316
317 { Is is allowed to drag-and-drop from ControlsTree to ControlsTree.
318 Src, Dst, SrcComponent can be @nil.
319 (But SrcComponents cannot!) }
320 function ControlsTreeAllowDrag(const Src, Dst: TTreeNode): Boolean;
321 function ControlsTreeAllowDrag(const SrcComponent: TComponent; const Dst: TTreeNode): Boolean;
322 function ControlsTreeAllowDrag(const SrcComponents: TComponentList; const Dst: TTreeNode): Boolean;
323
324 procedure FrameAnchorsChange(Sender: TObject);
325 procedure AdjustUserInterfaceAnchorsToKeepRect(const UI: TCastleUserInterface;
326 const RenderRectBeforeChange: TFloatRectangle);
327 // Save and restore selection.
328 // Careful: you can use it only if the operation between will *never* free any of them.
329 //procedure SelectionRestoreAndFree(var Selection: Classes.TList);
330 //function SelectionSave: Classes.TList;
331
332 { Get selected component from tree node.
333 Should be used directly only by GetSelected and GetSelectedComponent,
334 and everything else should look at GetSelected and GetSelectedComponent
335 to know selection.
336
337 @param(AutoSelectParents See GetSelected docs for explanation.) }
338 function SelectedFromNode(Node: TTreeNode;
339 const AutoSelectParents: Boolean = true): TComponent;
340
341 { Calculate all selected components as a list, non-nil <=> non-empty.
342
343 @param(AutoSelectParents If @true (default) then selecting a special
344 grouping tree nodes like "Behaviors" and "Non-Visual Components"
345 also implicitly selects their parent.
346
347 This is generally useful for reading operations, but undesired for
348 writing operations, see
349 https://github.com/castle-engine/castle-engine/issues/522
350 https://github.com/castle-engine/castle-engine/issues/521
351 https://github.com/castle-engine/castle-engine/issues/520
352 ).
353 }
354 procedure GetSelected(out Selected: TComponentList;
355 out SelectedCount: Integer; const AutoSelectParents: Boolean = true);
356
357 { Select given components in the hierarchy.
358 Consistently with GetSelected, that may return @nil,
359 this accepts @nil as input. }
360 procedure SetSelected(const Selected: TComponentList);
361
362 function GetSelectedUserInterface: TCastleUserInterface;
363 procedure SetSelectedUserInterface(const Value: TCastleUserInterface);
364 { If there is exactly one item selected, and it is TCastleUserInterface,
365 return it. Otherwise return nil. }
366 property SelectedUserInterface: TCastleUserInterface
367 read GetSelectedUserInterface write SetSelectedUserInterface;
368
369 function GetSelectedComponent(
370 const AutoSelectParents: Boolean = true): TComponent;
371 function GetSelectedComponentAutoSelectParents: TComponent;
372 procedure SetSelectedComponent(const Value: TComponent);
373 { If there is exactly one item selected, return it. Otherwise return nil. }
374 property SelectedComponent: TComponent
375 read GetSelectedComponentAutoSelectParents write SetSelectedComponent;
376
377 { If the selected items all have the same TCastleViewport parent,
378 return it. Otherwise return nil. }
379 function SelectedViewport: TCastleViewport;
380
381 { Look at current selection and hover and possibly change CurrentViewport,
382 calling also OnCurrentViewportChanged. }
383 procedure UpdateCurrentViewport;
384 procedure SetCurrentViewport(const Value: TCastleViewport);
385
386 { If there is exactly one item selected, and it is TCastleTransform,
387 return it. Otherwise return nil. }
388 function GetSelectedTransform: TCastleTransform;
389 procedure SetSelectedTransform(const Value: TCastleTransform);
390 property SelectedTransform: TCastleTransform
391 read GetSelectedTransform write SetSelectedTransform;
392
393 procedure InspectorBasicFilter(Sender: TObject; AEditor: TPropertyEditor;
394 var aShow: Boolean);
395 procedure InspectorLayoutFilter(Sender: TObject; AEditor: TPropertyEditor;
396 var aShow: Boolean);
397 procedure InspectorAllFilter(Sender: TObject; AEditor: TPropertyEditor;
398 var aShow: Boolean);
399 procedure MarkModified;
400 function UndoMessageModified(const Sel: TPersistent;
401 const ModifiedProperty, ModifiedValue: String; const SelectedCount: Integer): String;
402 { PropertyGridModified and PropertyEditorModified are called when
403 something changes in the design.
404 PropertyGridModified and PropertyEditorModified are both called when
405 something changes within Object Inspector basic features
406 (such as editing string, boolean, enum or numeric values)
407 In this case PropertyEditorModified usually comes first.
408 In case something changed outside of Object inspector (e.g. drag-and-drops,
409 rename components in treeview, add components, etc.)
410 only PropertyGridModified is called
411 In case a custom dialog is used to change a value
412 (e.g. a Color picker, TStrings editor, Open File dialogue, etc.)
413 then only PropertyEditorModified is called. }
414 procedure PropertyGridModified(Sender: TObject);
415 procedure PropertyEditorModified(Sender: TObject);
416 procedure PropertyGridCollectionItemClick(Sender: TObject);
417 procedure PropertyGridCollectionItemClose(Sender: TObject; var CloseAction: TCloseAction);
418 procedure PropertyGridCollectionItemAdd(Sender: TObject);
419 procedure PropertyGridCollectionItemDelete(Sender: TObject);
420 procedure PropertyGridCollectionItemMoveUp(Sender: TObject);
421 procedure PropertyGridCollectionItemMoveDown(Sender: TObject);
422
423 { Is Child selectable and visible in hierarchy. }
424 class function Selectable(const Child: TComponent): Boolean; static;
425 { Is Child deletable by user (this implies it is also selectable). }
426 function Deletable(const Child: TComponent): Boolean;
427
428 { Internal helper for UpdateDesign or ValidateHierarchy,
429 should only be used by these 2 methods. }
430 procedure ValidateOrUpdateHierarchy(const Validate: Boolean);
431
432 { Make sure the hierarchy tree (ControlsTree) reflects current DesignRoot state.
433 Add/remove tree nodes from ControlsTree as necessary.
434
435 Also set TreeNodeMap (unconditionally, i.e. it is always cleared and filled
436 from scratch by this method).
437
438 This guarantees that editor UI shows the correct state of everything. }
439 procedure UpdateDesign;
440
441 { Returns a warning and false value when hierarchy tree (ControlsTree) differs from
442 castle design hierarchy (DesignRoot). }
443 function ValidateHierarchy: Boolean;
444
445 procedure UpdateSelectedControl;
446 { Update whether TabInfo is visible and if yes -- what it contains. }
447 procedure UpdateSelectedInfo;
448 { Update anchors shown, based on UI state.
449 Updates which buttons are pressed inside 2 TAnchorFrame instances.
450 If AllowToHideParentAnchorsFrame, updates also checkbox
451 "parent and self equal" and may hide the parent anchor frame if yes. }
452 procedure UpdateAnchors(const UI: TCastleUserInterface;
453 const AllowToHideParentAnchorsFrame: Boolean);
454 { Filter property in object inspector.
455 When FilterBySection = true, then Section matters and only properties in this section
456 are displayed. }
457 procedure InspectorFilter(const Sender: TObject; const AEditor: TPropertyEditor;
458 var AShow: Boolean;
459 const FilterBySection: Boolean; const Section: TPropertySection);
460 procedure GizmoHasModifiedParent(Sender: TObject);
461 procedure GizmoStopDrag(Sender: TObject);
462 { Fix camera position, to look at Pos.XY in case of 2D games.
463 Use this before doing V.InternalCamera.AnimateTo/SetWorldView with given Pos,Dir,Up.
464
465 In case of 2D this means we should:
466
467 - Fix Pos.Z, to keep camera Z matching current run-time camera.
468 (this seems most natural and simplest camera behavior at design-time,
469 so that design-time camera uses the same Z).
470
471 - Fix Pos.XY, to account that Camera.Orthographic.Origin may <> (0.5,0.5).
472
473 Done when operating in 2D (*not* detected by navigation type, but by projection type and axis,
474 to keep this also working in Fly mode for 2D games).
475 }
476 procedure FixCamera2D(const V: TCastleViewport; var Pos: TVector3; const Dir, Up: TVector3);
477 procedure ViewportViewBox(const V: TCastleViewport; Box: TBox3D);
478 procedure CurrentViewportFreeNotification(const Sender: TFreeNotificationObserver);
479
480 { Single selected item.
481 Only non-nil when we have selected exactly one component.
482 IOW, this is always @nil if we selected zero or more than one component.
483
484 Use this when you need to know only the single selected item,
485 because the given operation cannot handle multiple selected items.
486 E.g. for rename operation.
487
488 Note:
489 Never use built-in LCL ControlsTree.Selected, which is not reliable to use
490 on a TTreeView with multi-selection possible.
491 The LCL ControlsTree.Selected problems details:
492
493 - it is not synchronized with ControlsTree.SelectionCount,
494 ControlsTree.Selections after doing "ControlsTree.Selected := nil".
495 The ControlsTree.SelectionCount may be left > 0.
496
497 - it is not synchronized with ControlsTree.SelectionCount,
498 ControlsTree.Selections after selecting multiple components with Shift and Ctrl.
499 E.g.
500 - select one tree node.
501 click on it again with Ctrl.
502 Effect: ControlsTree.Selected <> nil,
503 but ControlsTree.SelectionCount = 0.
504 - select one tree node.
505 select 3 more with Shift.
506 unselect 3 more with Ctrl.
507 Effect: ControlsTree.Selected = nil,
508 but ControlsTree.SelectionCount > 0.
509
510 - adding / removing nodes also don't seem to always synchronize them...
511
512 Note: Also never set ControlsTree.Selected.
513 Do ControlsTree.ClearSelection that makes multi-selection properly cleared.
514 }
515 function ControlsTreeOneSelected: TTreeNode;
516 function GetInspectorForActiveTab: TOIPropertyGrid;
517 function GetSavedSelection: TSavedSelection;
518 procedure RestoreSavedSelection(const S: TSavedSelection);
519 procedure MenuItemChangeClassClick(Sender: TObject);
520 procedure SetShowColliders(const AValue: Boolean);
521 { Show / hide colliders following FShowColliders setting.
522 If T = nil, updates everywhere (TODO: for now,
523 only in CurrentViewport). Otherwise updates only in T. }
524 procedure UpdateColliders(T: TCastleTransform = nil);
525
526 { Get parent of non-visual component.
527
528 Can be used on any TComponent. Parent can be TCastleComponent,
529 but it can contain any TComponent, this is important ability to store
530 in TCastleComponent.NonVisualComponents also non-CGE components.
531
532 Since there's no TCastleComponent.NonVisualParent or such, so we find parent using
533 ControlsTree knowledge.
534 Returns nil if no parent. }
535 function NonVisualComponentParent(const C: TComponent): TCastleComponent;
536
537 { Currently selected transformation, chosen more aggressively than just
538 SelectedTransform. Even selecting a behavior makes the parent current.
539 This way e.g. VisualizeTransformSelected also shows
540 the transformation of selected behavior. }
541 function CurrentTransform: TCastleTransform;
542 protected
543 procedure Notification(AComponent: TComponent; Operation: TOperation); override;
544 public
545 OnUpdateFormCaption: TNotifyEvent;
546 OnSelectionChanged: TNotifyEvent;
547 { Called always when CurrentViewport value changed. }
548 OnCurrentViewportChanged: TNotifyEvent;
549 OnProposeOpenDesign: TProposeOpenDesignEvent;
550 OnRunningToggle, OnApiReferenceOfCurrent: TNotifyEvent;
551 OnIsRunning: TBooleanEvent;
552 OnShowStatistics: TBooleanEvent;
553
554 function RenameSelectedPossible: Boolean;
555 function RenamePossible(const C: TComponent): Boolean;
556
557 constructor Create(TheOwner: TComponent); override;
558 destructor Destroy; override;
559
560 procedure SaveDesign(const Url: String);
561 { Changes DesignRoot, DesignUrl and all the associated user-interface. }
562 procedure OpenDesign(const NewDesignRoot, NewDesignOwner: TComponent;
563 NewDesignUrl: String);
564 procedure OpenDesign(const NewDesignUrl: String);
565 procedure NewDesign(const ComponentClass: TComponentClass;
566 const ComponentOnCreate: TNotifyEvent);
567
568 function FormCaption: String;
569 procedure BeforeProposeSaveDesign;
570 procedure AddComponent(const ComponentClass: TComponentClass;
571 const ComponentOnCreate: TNotifyEvent);
572 { Create and add a new component to the design.
573 @param(BaseNewComponentName Base of new name (without numeric suffix to
574 make it unique), passed to @link(ProposeComponentName).
575 Leave it empty to derive name from ComponentClass.ClassName.) }
576 function AddComponent(const ParentComponent: TComponent; const ComponentClass: TComponentClass;
577 const ComponentOnCreate: TNotifyEvent;
578 const BaseNewComponentName: String = ''): TComponent;
579 procedure DeleteComponent(const AutoSelectParents: Boolean = false);
580 { Free component C (which should be part of this designed, owned by DesignOwner)
581 and all children.
582
583 We have to delete things recursively, otherwise they would keep existing,
584 taking resources and reserving names in DesignOwner,
585 even though they would not be visible when disconnected from parent
586 hierarchy.
587
588 This does nothing if you try to free some internal component
589 (like csTransient) or the design root (which can never be freed). }
590 procedure FreeComponentRecursively(const C: TComponent);
591 procedure CopyComponent;
592 procedure PasteComponent;
593 procedure CutComponent;
594 procedure DuplicateComponent;
595
596 function AddComponentFromUrl(const AddUrl: String;
597 const ParentComponent: TComponent): TComponent;
598 function AddImported(const AddUrl: String): TComponent;
599
600 { Set UIScaling values. }
601 procedure UIScaling(const UIScaling: TUIScaling;
602 const UIReferenceWidth, UIReferenceHeight: Single);
603
604 property UndoSystem: TUndoSystem read FUndoSystem;
605 property DesignUrl: String read FDesignUrl;
606 { Root saved/loaded to component file }
607 property DesignRoot: TComponent read FDesignRoot;
608 property DesignModified: Boolean read FDesignModified;
609 procedure RecordUndo(const UndoComment: String;
610 const UndoCommentPriority: TUndoCommentPriority);
611
612 { Call after any change to the design (that changes what will be saved
613 to JSON) happened, except when this was done by user changing value
614 through Object Inspector.
615
616 This:
617 - Refreshes Object Inspector display,
618 - marks design as "modified",
619 - records undo.
620
621 @param(UndoComment Describes the change. You can pass empty String
622 to let auto-generating a sensible comment.)
623
624 @param(UndoCommentPriority How much are you sure that UndoComment
625 is the best message to describe last change.
626 This is used only when UndoComment <> '' and only when an "undo record"
627 was already stored for the current state. The given UndoComment
628 overrides the last if it has higher UndoCommentPriority.
629
630 Usually you want to pass here ucHigh, since usually you have
631 a really good knowledge about the change when calling this method.)
632
633 @param(UndoOnRelease If @true, then do not store "undo record" now,
634 instead schedule storing undo record when user releases the mouse.
635
636 This should be @true only for actions that do something on each mouse
637 move (like dragging transform or UI position/size).
638 In that case, storing "undo record" at each tiny mouse move would be
639 bad -- performance would drop during mouse move, and generating too many
640 "undo records" means that undoing them is not really comfortable.
641
642 For most operations, this is @false.)
643 }
644 procedure ModifiedOutsideObjectInspector(const UndoComment: String;
645 const UndoCommentPriority: TUndoCommentPriority; const UndoOnRelease: Boolean = false);
646
647 procedure SaveSelected;
648
649 procedure CurrentComponentApiUrl(var Url: String);
650
651 { Viewport to act on using various commands.
652
653 Chosen "aggressively" by looking at selected viewport
654 (based on selected ui or transform within viewport)
655 or viewport over which mouse hovers. We want to enable user to set current viewport
656 as easily as possible, to avoid the "selection of viewport" being an extra step
657 user needs to remember to do.
658
659 Note that this viewport may not be Selectable.
660 It may be an internal viewport (in case of .castle-transform files)
661 or a viewport inside TCastleDesign.Design (testcase when it's needed:
662 examples/physics/physics_joints_3d/ ).
663
664 @nil if none. }
665 property CurrentViewport: TCastleViewport read FCurrentViewport;
666
667 procedure ViewportViewAxis(const Dir, Up: TVector3);
668 procedure ViewportViewAll;
669 procedure ViewportViewSelected;
670 procedure ViewportSetup2D;
671 procedure ViewportToggleProjection;
672 procedure ViewportAlignViewToCamera;
673 procedure ViewportAlignCameraToView;
674
675 { Physics stuff. } { }
676 procedure SimulationPlayStop;
677 procedure SimulationPauseUnpause;
678 property ShowColliders: Boolean read FShowColliders write SetShowColliders;
679
680 procedure ReleaseAllKeysAndMouse;
681
682 procedure FocusDesign;
683 procedure ChangeMode(const NewMode: TMode);
684 procedure ShowAllJointsTools;
685 procedure HideAllJointsTools;
686
687 { Saves some editor data in subcomponent of Application for property
688 editors }
689 procedure UpdateEditorDataForPropertyEditors;
690
691 { Toggle whether the edit box to find component by name exists. }
692 procedure FindToggle;
693 { Find next, if find is active. }
694 procedure FindNext;
695 end;
696
697 implementation
698
699 {$warnings off} // do not warn about deprecated Castle2DSceneManager usage
700
701 uses
702 { Standard FPC/Lazarus units }
703 // use Windows unit with FPC 3.0.x, to get TSplitRectType enums
704 {$ifdef VER3_0} {$ifdef MSWINDOWS} Windows, {$endif} {$endif}
705 TypInfo, StrUtils, Math, Graphics, Types, Dialogs, LCLType, ObjInspStrConsts,
706 { CGE units }
707 CastleUtils, CastleComponentSerialize, CastleFileFilters, CastleGLUtils, CastleImages,
708 CastleLog, CastleProjection, CastleStringUtils, CastleTimeUtils,
709 CastleUriUtils, X3DLoad, CastleFilesUtils, CastleInternalPhysicsVisualization,
710 CastleInternalUrlUtils, CastleInternalFileMonitor,
711 { CGE unit to keep in uses clause even if they are not explicitly used by FrameDesign,
712 to register the core CGE components for (de)serialization. }
713 Castle2DSceneManager, CastleNotifications, CastleThirdPersonNavigation, CastleSoundEngine,
714 CastleBehaviors,
715 { Editor units }
716 FormProject, CastleComponentEditorDesigner;
717
718 {$warnings on}
719
720 {$R *.lfm}
721
722 {$ifdef VER3_0}
723 {$ifdef MSWINDOWS}
724 type
725 TSplitRectType = Windows.TSplitRectType;
726 const
727 srLeft = TSplitRectType.srLeft;
728 srRight = TSplitRectType.srRight;
729 srTop = TSplitRectType.srTop;
730 srBottom = TSplitRectType.srBottom;
731 {$endif}
732 {$endif}
733
734 function ParentRenderRect(const UI: TCastleUserInterface): TFloatRectangle;
735 begin
736 if UI.Parent = nil then
737 Result := FloatRectangle(UI.Container.PixelsRect)
738 else
739 Result := UI.Parent.RenderRect;
740 end;
741
742 { TDesignFrame.TDesignerLayer ------------------------------------------------ }
743
744 constructor TDesignFrame.TDesignerLayer.Create(AOwner: TComponent);
745 begin
746 inherited Create(AOwner);
747 FullSize := true;
748
749 LayerPhysicsSimulation := UserInterfaceLoad(InternalCastleDesignData + 'layer_physics_simulation.castle-user-interface', Self);
750 LayerPhysicsSimulation.Exists := false;
751 LabelPhysicsSimulationRunning := FindRequiredComponent('LabelRunning') as TCastleLabel;
752 LabelPhysicsSimulationPaused := FindRequiredComponent('LabelPaused') as TCastleLabel;
753 InsertFront(LayerPhysicsSimulation);
754
755 RectHover := TCastleRectangleControl.Create(Self);
756 RectHover.Color := Vector4(0, 0, 0, 0.25);
757 RectHover.Exists := false;
758 { LabelHover with scaling sometimes looks too tiny.
759 Also, positioning RectHover is easier without UI scaling. }
760 RectHover.EnableUIScaling := false;
761 InsertFront(RectHover);
762
763 LabelHover := TCastleLabel.Create(Self);
764 LabelHover.Anchor(hpMiddle);
765 LabelHover.Anchor(vpMiddle);
766 LabelHover.FontSize := 15;
767 LabelHover.EnableUIScaling := false;
768 RectHover.InsertFront(LabelHover);
769
770 RectSelected := TCastleRectangleControl.Create(Self);
771 RectSelected.Color := Vector4(0, 0, 0, 0.25);
772 RectSelected.Exists := false;
773 RectSelected.EnableUIScaling := false;
774 InsertFront(RectSelected);
775
776 LabelSelected := TCastleLabel.Create(Self);
777 LabelSelected.Anchor(hpMiddle);
778 LabelSelected.Anchor(vpMiddle);
779 LabelSelected.FontSize := 15;
780 LabelSelected.EnableUIScaling := false;
781 RectSelected.InsertFront(LabelSelected);
782
783 RectStatistics := TCastleRectangleControl.Create(Self);
784 RectStatistics.Color := Vector4(0, 0, 0, 0.25);
785 RectStatistics.Exists := false;
786 RectStatistics.EnableUIScaling := false;
787 RectStatistics.Anchor(hpRight, -5);
788 RectStatistics.Anchor(vpTop, -5);
789 RectStatistics.AutoSizeToChildren := true;
790 InsertFront(RectStatistics);
791
792 LabelStatistics := TCastleLabel.Create(Self);
793 LabelStatistics.Border.AllSides := 5;
794 LabelStatistics.Anchor(hpMiddle);
795 LabelStatistics.Anchor(vpMiddle);
796 LabelStatistics.FontSize := 15;
797 LabelStatistics.EnableUIScaling := false;
798 LabelStatistics.Color := White;
799 LabelStatistics.Alignment := hpRight;
800 RectStatistics.InsertFront(LabelStatistics);
801
802 ForceFallbackLook(RectStatistics);
803 end;
804
805 function TDesignFrame.TDesignerLayer.HoverUserInterface(
806 const AMousePosition: TVector2;
807 const EnterNestedDesigns: Boolean): TCastleUserInterface;
808
809 { Like TCastleUserInterface.CapturesEventsAtPosition, but
810 - ignores CapturesEvents
811 - uses RenderRectWithBorder (to be able to drag complete control)
812 - doesn't need "if the control covers the whole Container" hack. }
813 function SimpleCapturesEventsAtPosition(const UI: TCastleUserInterface;
814 const Position: TVector2; const TestWithBorder: Boolean): Boolean;
815 begin
816 if TestWithBorder then
817 Result := UI.RenderRectWithBorder.Contains(Position)
818 else
819 Result := UI.RenderRect.Contains(Position);
820 end;
821
822 { Is C selectable, or we should enter it anyway because of EnterNestedDesigns. }
823 function Enter(const Parent, C: TCastleUserInterface): Boolean;
824 begin
825 Result := TDesignFrame.Selectable(C) or
826 ( EnterNestedDesigns and
827 (Parent is TCastleDesign) and
828 (TCastleDesign(Parent).InternalDesign = C) );
829 end;
830
831 function ControlUnder(const C: TCastleUserInterface;
832 const MousePos: TVector2; const TestWithBorder: Boolean): TCastleUserInterface;
833 var
834 I: Integer;
835 begin
836 Result := nil;
837
838 { To allow selecting even controls that have bad rectangle (outside
839 of parent, which can happen, e.g. if you enlarge caption of label
840 with AutoSize), do not check C.CapturesEventsAtPosition(MousePos)
841 too early here. So the condition
842
843 and C.CapturesEventsAtPosition(MousePos)
844
845 is not present in "if" below. }
846
847 if C.Exists then
848 begin
849 { First try to find children, with TestWithBorder=false (so it doesn't detect
850 control if we merely point at its border). This allows to find controls
851 places on another control's border. }
852 for I := C.ControlsCount - 1 downto 0 do
853 if Enter(C, C.Controls[I]) then
854 begin
855 Result := ControlUnder(C.Controls[I], MousePos, false);
856 if Result <> nil then Exit;
857 end;
858
859 { Next try to find children, with TestWithBorder=true, so it tries harder
860 to find something. }
861 for I := C.ControlsCount - 1 downto 0 do
862 if Enter(C, C.Controls[I]) then
863 begin
864 Result := ControlUnder(C.Controls[I], MousePos, true);
865 if Result <> nil then Exit;
866 end;
867
868 { Eventually return yourself, C. }
869 //if C.CapturesEventsAtPosition(MousePos) then
870 if SimpleCapturesEventsAtPosition(C, MousePos, TestWithBorder) and
871 C.EditorSelectOnHover then
872 Result := C;
873 end;
874 end;
875
876 function MouseOverControl(const Control: TCastleControl): Boolean;
877 var
878 PosInClient: TPoint;
879 begin
880 PosInClient := Control.ScreenToClient(Mouse.CursorPos);
881 Result := Control.ClientRect.Contains(PosInClient);
882 end;
883
884 begin
885 Result := nil;
886 if MouseOverControl(Frame.CastleControl) then
887 begin
888 if Frame.DesignRoot is TCastleUserInterface then
889 Result := ControlUnder(Frame.DesignRoot as TCastleUserInterface, AMousePosition, true)
890 else
891 if Frame.DesignRoot is TCastleTransform then
892 Result := Frame.FDesignViewportForTransforms;
893 end;
894 end;
895
896 function TDesignFrame.TDesignerLayer.HoverComponent(const AMousePosition: TVector2): TCastleComponent;
897
898 function SelectionFromRayHit(const RayHit: TRayCollision): TCastleTransform;
899 var
900 I: Integer;
901 begin
902 // set outer-most TCastleTransformReference, if any, to show selection at TCastleTransformReference
903 for I := RayHit.Count - 1 downto 0 do
904 if (RayHit[I].Item is TCastleTransformReference) and Selectable(RayHit[I].Item) then
905 Exit(RayHit[I].Item);
906
907 { We want the inner-most TCastleTransform hit, but not anything non-selectable
908 (which means csTransient) (to avoid hitting gizmo).
909 Moreover, things that are children of csTransient should always be treated like csTransient
910 too, e.g. GizmoSelect in TInternalCastleEditorGizmo should never be returned by this.
911
912 So if there's anything non-selectable (which just means csTransient),
913 searching from outer (world),
914 then pick the selected transform right above it. }
915
916 for I := RayHit.Count - 1 downto 0 do
917 if not Selectable(RayHit[I].Item) then
918 begin
919 if I + 1 < RayHit.Count then
920 Exit(RayHit[I + 1].Item)
921 else
922 Exit(nil);
923 end;
924
925 { Nothing non-selectable (csTransient) on the list, pick the inner-most transform }
926 if RayHit.Count <> 0 then
927 Result := RayHit[0].Item
928 else
929 Result := nil;
930 end;
931
932 var
933 Viewport: TCastleViewport;
934 RayOrigin, RayDirection: TVector3;
935 RayHit: TRayCollision;
936 begin
937 { Note: We don't call here CurrentViewport.
938
939 Unlike with CurrentViewport, here we don't try to forcefully select viewport
940 (from hover or selection). If the mouse is over non-viewport, then this
941 should return non-viewport.
942
943 Also, unlike CurrentViewport,
944 we don't want to remember last hovered/selected viewport here,
945 it would be weird for user here.
946
947 Also, unlike CurrentViewport, we don't pass EnterNestedDesigns as
948 UpdateCurrentViewport does. We don't need to look for viewport that aggressive. }
949
950 Result := HoverUserInterface(AMousePosition);
951 if Result is TCastleViewport then // also checks Result <> nil
952 begin
953 Viewport := TCastleViewport(Result);
954 Viewport.PositionToRay(AMousePosition, true, RayOrigin, RayDirection);
955 RayHit := Viewport.Items.WorldRay(RayOrigin, RayDirection);
956 try
957 if RayHit <> nil then
958 Result := SelectionFromRayHit(RayHit);
959 finally FreeAndNil(RayHit) end;
960 end;
961 end;
962
963 function TDesignFrame.TDesignerLayer.IsResizing(const UI: TCastleUserInterface;
964 const Position: TVector2; out Horizontal: THorizontalPosition;
965 out Vertical: TVerticalPosition; out Hint: String): Boolean;
966 const
967 BorderDragMargin = 10;
968 var
969 R: TFloatRectangle;
970 ResizeWidth, ResizeHeight, IsTop, IsBottom, IsRight, IsLeft: Boolean;
971 ResizeDisabledReason: String;
972 begin
973 R := UI.RenderRectWithBorder;
974
975 UI.EditorAllowResize(ResizeWidth, ResizeHeight, ResizeDisabledReason);
976
977 Hint := '';
978
979 IsTop := R.TopPart(BorderDragMargin).Contains(Position);
980 IsBottom := R.BottomPart(BorderDragMargin).Contains(Position);
981 IsRight := R.RightPart(BorderDragMargin).Contains(Position);
982 IsLeft := R.LeftPart(BorderDragMargin).Contains(Position);
983
984 { the order of checking (top or bottom) matters in case of very
985 small heights. }
986 if ResizeHeight and IsTop then
987 Vertical := vpTop
988 else
989 if ResizeHeight and IsBottom then
990 Vertical := vpBottom
991 else
992 begin
993 Vertical := vpMiddle;
994 if IsTop or IsBottom then
995 Hint := ResizeDisabledReason;
996 end;
997
998 if ResizeWidth and IsRight then
999 Horizontal := hpRight
1000 else
1001 if ResizeWidth and IsLeft then
1002 Horizontal := hpLeft
1003 else
1004 begin
1005 Horizontal := hpMiddle;
1006 if IsLeft or IsRight then
1007 Hint := ResizeDisabledReason;
1008 end;
1009
1010 if Hint <> '' then
1011 Hint := UI.Name + ':' + NL + Hint;
1012
1013 Result := (Vertical <> vpMiddle) or (Horizontal <> hpMiddle);
1014 end;
1015
1016 function TDesignFrame.TDesignerLayer.IsResizing(const UI: TCastleUserInterface;
1017 const Position: TVector2; out Horizontal: THorizontalPosition;
1018 out Vertical: TVerticalPosition): Boolean;
1019 var
1020 Hint: String;
1021 begin
1022 Result := IsResizing(UI, Position, Horizontal, Vertical, Hint);
1023 end;
1024
1025 function TDesignFrame.TDesignerLayer.Press(
1026 const Event: TInputPressRelease): Boolean;
1027
1028 procedure SetSelection(const NewComponent: TComponent; const ToggleSelection: Boolean);
1029 var
1030 NewComponentNode: TTreeNode;
1031 NewSelection: TList;
1032 I: Integer;
1033 begin
1034 if ToggleSelection then
1035 begin
1036 if Frame.TreeNodeMap.TryGetValue(NewComponent, NewComponentNode) then
1037 begin
1038 if NewComponentNode.Selected then
1039 begin
1040 { Unfortunately, unselecting by setting
1041 NewComponentNode.Selected := false
1042 doesn't work. }
1043 NewSelection := TList.Create;
1044 try
1045 for I := 0 to Frame.ControlsTree.SelectionCount - 1 do
1046 if NewComponentNode <> Frame.ControlsTree.Selections[I] then
1047 NewSelection.Add(Frame.ControlsTree.Selections[I]);
1048 Frame.ControlsTree.Select(NewSelection);
1049 finally FreeAndNil(NewSelection) end;
1050 end else
1051 NewComponentNode.Selected := not NewComponentNode.Selected;
1052 end else
1053 WritelnWarning('Cannot toggle selection of "%s" because it is not found in TreeNodeMap', [
1054 NewComponent.Name
1055 ]);
1056 end
1057 else
1058 Frame.SelectedComponent := NewComponent;
1059 end;
1060
1061 var
1062 UI: TCastleUserInterface;
1063 begin
1064 Result := inherited Press(Event);
1065 if Result then Exit;
1066
1067 { Avoid handling mouse events over CameraPreview, to avoid messing with clicking
1068 on CameraPreview buttons, and using gizmos in CameraPreview viewport. }
1069 if Frame.CameraPreview.UiRoot.Exists and
1070 Frame.CameraPreview.UiRoot.RenderRectWithBorder.Contains(Event.Position) then
1071 Exit;
1072
1073 if Event.IsMouseButton(buttonLeft) then
1074 begin
1075 { Below we will always calculate correct UiDraggingMode }
1076 UiDraggingMode := dmNone;
1077
1078 if Frame.Mode <> moInteract then
1079 begin
1080 { Calculate Frame.SelectedComponent.
1081 Without shift pressed, we select before moving/resizing.
1082 With shift pressed we don't change selection.
1083 This allows to change the component without changing the selected component. }
1084 if (not (mkShift in Event.ModifiersDown)) then
1085 begin
1086 SetSelection(HoverComponent(Event.Position), mkCtrl in Event.ModifiersDown);
1087 end;
1088
1089 if Frame.Mode <> moSelect then
1090 begin
1091 UI := Frame.SelectedUserInterface;
1092 if UI <> nil then
1093 begin
1094 if IsResizing(UI, Event.Position, ResizingHorizontal, ResizingVertical) then
1095 UiDraggingMode := dmResize
1096 else
1097 UiDraggingMode := dmTranslate;
1098
1099 { Note: No need for this Exit(true) when UI = nil.
1100 In particular if we selected TCastleTransform, we should not do Exit(true),
1101 to allow gizmos to start dragging. }
1102 Exit(true);
1103 end;
1104 end;
1105
1106 UiPendingMove := TVector2.Zero;
1107 end;
1108 end;
1109 end;
1110
1111 function TDesignFrame.TDesignerLayer.Release(const Event: TInputPressRelease): Boolean;
1112 var
1113 Sel: TComponent;
1114 begin
1115 Result := inherited Press(Event);
1116 if Result then Exit;
1117
1118 { Avoid handling mouse events over CameraPreview, to avoid messing with clicking
1119 on CameraPreview buttons, and using gizmos in CameraPreview viewport. }
1120 if Frame.CameraPreview.UiRoot.Exists and
1121 Frame.CameraPreview.UiRoot.RenderRectWithBorder.Contains(Event.Position) then
1122 Exit;
1123
1124 if Event.IsMouseButton(buttonLeft) then
1125 begin
1126 UiDraggingMode := dmNone;
1127
1128 { Note, that we may want to have better comment message here }
1129 if Frame.UndoSystem.ScheduleRecordUndoOnRelease then
1130 begin
1131 Sel := Frame.GetSelectedComponent;
1132 if Sel <> nil then
1133 Frame.RecordUndo('Drag''n''drop ' + Sel.Name, ucHigh)
1134 else
1135 Frame.RecordUndo('Drag''n''drop', ucHigh);
1136 end;
1137 end;
1138 end;
1139
1140 function TDesignFrame.TDesignerLayer.Motion(const Event: TInputMotion): Boolean;
1141
1142 { Grow the rectangle from the appropriate sides, following
1143 ResizingHorizontal/Vertical field values. }
1144 function ResizeRect(const R: TFloatRectangle; const Move: TVector2): TFloatRectangle;
1145 begin
1146 Result := R;
1147 case ResizingHorizontal of
1148 hpLeft : Result := Result.GrowLeft(-Move.X);
1149 hpRight: Result := Result.GrowRight(Move.X);
1150 end;
1151 case ResizingVertical of
1152 vpBottom: Result := Result.GrowBottom(-Move.Y);
1153 vpTop : Result := Result.GrowTop(Move.Y);
1154 end;
1155 end;
1156
1157 function DragAllowed(const UI: TCastleUserInterface; const Move: TVector2): Boolean;
1158 var
1159 CurrentRect, ResultingRect, ParentR: TFloatRectangle;
1160 begin
1161 CurrentRect := UI.RenderRectWithBorder;
1162 case UiDraggingMode of
1163 dmTranslate: ResultingRect := CurrentRect.Translate(Move);
1164 dmResize : ResultingRect := ResizeRect(CurrentRect, Move);
1165 end;
1166 ParentR := ParentRenderRect(UI);
1167 { Only allow movement/resize if control will not go outside of parent,
1168 unless it was already outside.
1169
1170 Note that we limit to the parent rect *without border*,
1171 that is: we don't allow to move control over a border of the parent.
1172 This makes sense, since FullSize and WidthFraction = 1 keep the control
1173 within the parent rect *without border* too.
1174 }
1175 Result := (not ParentR.Contains(CurrentRect)) or
1176 ParentR.Contains(ResultingRect);
1177 end;
1178
1179 procedure ApplyDrag(const UI: TCastleUserInterface; X, Y: Single);
1180 const
1181 MinWidth = 10;
1182 MinHeight = 10;
1183 begin
1184 if not DragAllowed(UI, Vector2(X, Y)) then Exit;
1185 case UiDraggingMode of
1186 dmTranslate:
1187 begin
1188 UI.Translation := UI.Translation + Vector2(X, Y);
1189 end;
1190 dmResize:
1191 begin
1192 case ResizingHorizontal of
1193 hpLeft:
1194 begin
1195 // do not allow to set UI.Width < MinWidth, by limiting X
1196 if UI.Width - X < MinWidth then
1197 X := UI.Width - MinWidth;
1198 UI.Width := UI.Width - X;
1199
1200 case UI.HorizontalAnchorSelf of
1201 hpLeft : UI.Translation := UI.Translation + Vector2(X, 0);
1202 hpMiddle: UI.Translation := UI.Translation + Vector2(X / 2, 0);
1203 //hpRight : UI.Translation := no need to change
1204 end;
1205 end;
1206 hpRight:
1207 begin
1208 // do not allow to set UI.Width < MinWidth, by limiting X
1209 if UI.Width + X < MinWidth then
1210 X := MinWidth - UI.Width;
1211 UI.Width := UI.Width + X;
1212
1213 case UI.HorizontalAnchorSelf of
1214 // hpLeft : UI.Translation := no need to change
1215 hpMiddle: UI.Translation := UI.Translation + Vector2(X / 2, 0);
1216 hpRight : UI.Translation := UI.Translation + Vector2(X, 0);
1217 end;
1218 end;
1219 end;
1220 case ResizingVertical of
1221 vpBottom:
1222 begin
1223 // do not allow to set UI.Height < MinHeight, by limiting Y
1224 if UI.Height - Y < MinHeight then
1225 Y := UI.Height - MinHeight;
1226 UI.Height := UI.Height - Y;
1227
1228 case UI.VerticalAnchorSelf of
1229 vpBottom: UI.Translation := UI.Translation + Vector2(0, Y);
1230 vpMiddle: UI.Translation := UI.Translation + Vector2(0, Y / 2);
1231 //vpTop : UI.Translation := no need to change
1232 end;
1233 end;
1234 vpTop:
1235 begin
1236 // do not allow to set UI.Height < MinHeight, by limiting Y
1237 if UI.Height + Y < MinHeight then
1238 Y := MinHeight - UI.Height;
1239 UI.Height := UI.Height + Y;
1240
1241 case UI.VerticalAnchorSelf of
1242 //vpBottom: UI.Translation := no need to change
1243 vpMiddle: UI.Translation := UI.Translation + Vector2(0, Y / 2);
1244 vpTop : UI.Translation := UI.Translation + Vector2(0, Y);
1245 end;
1246 end;
1247 end;
1248 end;
1249 end;
1250
1251 { We pass UndoOnRelease = true to defer recording Undo until Release is called
1252 to avoid recording Undo on every user Motion event.
1253 In this case UndoComment and UndoPriority do not matter,
1254 they will be replaced by appropriate values on Release. }
1255 Frame.ModifiedOutsideObjectInspector('', ucLow, true); // UndoComment doesn't matter here
1256 end;
1257
1258 function ResizingCursor(const H: THorizontalPosition;
1259 const V: TVerticalPosition): TMouseCursor;
1260 begin
1261 case H of
1262 hpLeft:
1263 case V of
1264 vpBottom: Result := mcResizeBottomLeft;
1265 vpMiddle: Result := mcResizeLeft;
1266 vpTop : Result := mcResizeTopLeft;
1267 end;
1268 hpMiddle:
1269 case V of
1270 vpBottom: Result := mcResizeBottom;
1271 vpMiddle: raise EInternalError.Create('No resizing, cannot determine cursor');
1272 vpTop : Result := mcResizeTop;
1273 end;
1274 hpRight:
1275 case V of
1276 vpBottom: Result := mcResizeBottomRight;
1277 vpMiddle: Result := mcResizeRight;
1278 vpTop : Result := mcResizeTopRight;
1279 end;
1280 end;
1281 end;
1282
1283 procedure UpdateCursor;
1284 var
1285 WouldResizeHorizontal: THorizontalPosition;
1286 WouldResizeVertical: TVerticalPosition;
1287 NewCursor: TMouseCursor;
1288 Hint: String;
1289 HoverC: TCastleComponent;
1290 begin
1291 Hint := '';
1292 if Frame.Mode = moInteract then
1293 NewCursor := mcDefault
1294 else
1295 case UiDraggingMode of
1296 dmNone:
1297 begin
1298 // calculate cursor based on what would happen if you Press
1299 HoverC := HoverComponent(Event.Position);
1300 if HoverC is TCastleUserInterface then
1301 begin
1302 if IsResizing(HoverC as TCastleUserInterface, Event.Position,
1303 WouldResizeHorizontal, WouldResizeVertical, Hint) then
1304 begin
1305 NewCursor := ResizingCursor(
1306 WouldResizeHorizontal, WouldResizeVertical);
1307 end else
1308 NewCursor := mcHand;
1309 end else
1310 NewCursor := mcDefault;
1311 end;
1312 dmTranslate:
1313 NewCursor := mcHand;
1314 dmResize:
1315 NewCursor := ResizingCursor(ResizingHorizontal, ResizingVertical);
1316 end;
1317 Frame.CastleControl.Container.OverrideCursor := NewCursor;
1318 Frame.CastleControl.Hint := Hint;
1319 Frame.CastleControl.ShowHint := Hint <> '';
1320 end;
1321
1322 procedure UpdateHoverComponent;
1323 var
1324 HoverC: TCastleComponent;
1325 begin
1326 if Frame.Mode <> moInteract then
1327 begin
1328 HoverC := HoverComponent(Event.Position); // may also return nil
1329 if HoverC is TCastleTransform then
1330 Frame.VisualizeTransformHover.Parent := TCastleTransform(HoverC)
1331 else
1332 Frame.VisualizeTransformHover.Parent := nil;
1333 end else
1334 Frame.VisualizeTransformHover.Parent := nil;
1335 end;
1336
1337 { Sometimes, trying to drag (translate/resize) UI,
1338 should actually drag the UI's parent (or parent's parent...).
1339 This happens when UI has FullSize,
1340 or it is within a group that auto-aligns children.
1341
1342 The DragAllowed is such case would block some actions on UI,
1343 and it is intuitive to perform them on parent.
1344
1345 TODO: This has hardcoded logic for FullSize and group cases.
1346 There should be a virtual method instead like
1347 TCastleUserInterface.EditorDragParent(UiDraggingMode)
1348 TCastleUserInterface.EditorDragMeInsteadOfChild(UiDraggingMode)
1349 }
1350 procedure ChangeDraggedUI(var UI: TCastleUserInterface);
1351 begin
1352 if (UiDraggingMode in [dmResize, dmTranslate]) and
1353 UI.EffectiveFullSize and
1354 (UI.Parent <> nil) then
1355 begin
1356 UI := UI.Parent;
1357 ChangeDraggedUI(UI); // act recursively if necessary, to choose parent's parent...
1358 end;
1359
1360 if (UiDraggingMode in [dmResize, dmTranslate]) and
1361 (UI.Parent <> nil) and
1362 { When the parent uses AutoSizeToChildren on a single child, then the effect is similar
1363 as it child had FullSize. }
1364 UI.Parent.AutoSizeToChildren and
1365 (UI.Parent.ControlsCount = 1) and
1366 {$warnings off} // looking at deprecated Left, Bottom to keep them working
1367 (UI.Left = 0) and
1368 (UI.Bottom = 0) and
1369 {$warnings on}
1370 TVector2.PerfectlyEquals(UI.Translation, TVector2.Zero) then
1371 begin
1372 UI := UI.Parent;
1373 ChangeDraggedUI(UI); // act recursively if necessary, to choose parent's parent...
1374 end;
1375
1376 if (UiDraggingMode in [dmTranslate]) and
1377 (UI.Parent <> nil) and
1378 ( (UI.Parent is TCastleHorizontalGroup) or
1379 (UI.Parent is TCastleVerticalGroup) ) then
1380 begin
1381 UI := UI.Parent;
1382 ChangeDraggedUI(UI); // act recursively if necessary, to choose parent's parent...
1383 end;
1384 end;
1385
1386 var
1387 UI: TCastleUserInterface;
1388 Move: TVector2;
1389 Snap: Single;
1390 begin
1391 Result := inherited Motion(Event);
1392 if Result then Exit;
1393
1394 { Avoid handling mouse events over CameraPreview, to avoid messing with clicking
1395 on CameraPreview buttons, and using gizmos in CameraPreview viewport. }
1396 if Frame.CameraPreview.UiRoot.Exists and
1397 Frame.CameraPreview.UiRoot.RenderRectWithBorder.Contains(Event.Position) then
1398 Exit;
1399
1400 { in case user released mouse button, but the event didn't reach us for some reason
1401 (maybe can happen e.g. if you Alt+Tab during dragging?),
1402 reset UiDraggingMode. }
1403 if (UiDraggingMode <> dmNone) and
1404 (not (buttonLeft in Event.Pressed)) then
1405 UiDraggingMode := dmNone;
1406
1407 if (Frame.Mode <> moInteract) and
1408 (UiDraggingMode <> dmNone) then
1409 begin
1410 UI := Frame.SelectedUserInterface;
1411 if UI <> nil then
1412 begin
1413 ChangeDraggedUI(UI);
1414
1415 Move := (Event.Position - Event.OldPosition) / UI.UIScale;
1416
1417 Snap := Frame.SpinEditSnap.Value;
1418 if Snap <> 0 then
1419 begin
1420 UiPendingMove += Move;
1421 while Abs(UiPendingMove.X) >= Snap do
1422 begin
1423 ApplyDrag(UI, Sign(UiPendingMove.X) * Snap, 0);
1424 UiPendingMove.X := UiPendingMove.X - Sign(UiPendingMove.X) * Snap;
1425 end;
1426 while Abs(UiPendingMove.Y) >= Snap do
1427 begin
1428 ApplyDrag(UI, 0, Sign(UiPendingMove.Y) * Snap);
1429 UiPendingMove.Y := UiPendingMove.Y - Sign(UiPendingMove.Y) * Snap;
1430 end;
1431 end else
1432 begin
1433 ApplyDrag(UI, Move.X, Move.Y);
1434 end;
1435
1436 Exit(true);
1437 end;
1438 end;
1439
1440 if not InternalDesignMouseLook then
1441 { do not override cursor when InternalDesignMouseLook,
1442 to allow mouse look to hide cursor. }
1443 UpdateCursor;
1444
1445 UpdateHoverComponent;
1446 end;
1447
1448 procedure TDesignFrame.TDesignerLayer.Render;
1449
1450 procedure UpdateAttachedLabel(const UI: TCastleUserInterface;
1451 const UIRect: TFloatRectangle;
1452 const Lab: TCastleLabel; const Rect: TCastleRectangleControl;
1453 const LabelColor: TCastleColor);
1454 begin
1455 { Show additional UI to show selected UI.
1456 While these labels can be helpful, they often obscure important UI
1457 (even the one you're trying to edit) so it is also causing trouble.
1458
1459 After some experimenting, we only show them on components with zero size.
1460 This allows to e.g. know where is new TCastleVertical/HorizontalGroup
1461 (as it is selected right after addition, and has zero size since has
1462 no children, and AutoSize=true).
1463 }
1464 if (UI <> nil) and
1465 (
1466 (UI.EffectiveWidth = 0) or
1467 (UI.EffectiveHeight = 0)
1468 ) then
1469 begin
1470 Lab.Caption := Frame.ComponentCaption(UI);
1471 Lab.Color := LabelColor;
1472
1473 Rect.Exists := true;
1474 Rect.Width := Lab.EffectiveWidth + 6;
1475 Rect.Height := Lab.EffectiveHeight + 6;
1476 { Place in left-top corner. Because:
1477 - We want left-xxx corner, this way if the label is cut off,
1478 at least the beginning looks OK.
1479 - We don't want left-bottom corner, as that's where child controls
1480 are placed by default, so the text would be over them too often. }
1481 Rect.Anchor(hpLeft, Max(0, UIRect.Left));
1482 Rect.Anchor(vpBottom, UIRect.Top);
1483
1484 if Rect.RenderRect.Top > Rect.Container.PixelsHeight then
1485 // put Rect inside UI, otherwise it would be offscreen
1486 Rect.Anchor(vpTop, vpBottom, Min(Rect.Container.PixelsHeight, UIRect.Top));
1487 end else
1488 Rect.Exists := false;
1489 end;
1490
1491 function StatisticsToString: String;
1492 begin
1493 Result := 'FPS: ' + Container.Fps.ToString;
1494 if Frame.CurrentViewport <> nil then
1495 Result := Result + NL +
1496 'Viewport "' + Frame.CurrentViewport.Name + '":' + NL +
1497 Frame.CurrentViewport.Statistics.ToString;
1498 end;
1499
1500 var
1501 SelectedUI, HoverUI: TCastleUserInterface;
1502 SelectedUIRect, HoverUIRect: TFloatRectangle;
1503 begin
1504 inherited;
1505
1506 SelectedUI := Frame.SelectedUserInterface;
1507 if SelectedUI <> nil then
1508 begin
1509 SelectedUIRect := SelectedUI.RenderRectWithBorder;
1510 DrawRectangleOutline(SelectedUIRect, White);
1511 DrawRectangleOutline(SelectedUIRect.Grow(-1), Black);
1512 end;
1513
1514 HoverUI := HoverUserInterface(Container.MousePosition);
1515 if HoverUI <> nil then
1516 begin
1517 HoverUIRect := HoverUI.RenderRectWithBorder;
1518 DrawRectangleOutline(HoverUIRect, Vector4(1, 1, 0, 0.75));
1519
1520 // TODO: for now hide, too confusing in case of auto-sized label/button
1521 {
1522 if not UI.EffectiveFullSize then
1523 begin
1524 // show desired Width / Height, useful e.g. for TCastleImageControl
1525 R.Width := UI.Width * UI.UIScale;
1526 R.Height := UI.Height * UI.UIScale;
1527 DrawRectangleOutline(R, Vector4(1, 1, 0, 0.25));
1528 end;
1529 }
1530 end;
1531
1532 { Note: HoverUI is in practice never visible now,
1533 as UpdateAttachedLabel makes it visible only for components with size zero.
1534 This code can be simplified, to remove HoverUI, LabelHover, RectHover
1535 -- once we're sure that showing "hover" is a useless idea at some point. }
1536 if (HoverUI <> nil) and (HoverUI = SelectedUI) then
1537 begin
1538 UpdateAttachedLabel(SelectedUI, SelectedUIRect, LabelSelected, RectSelected,
1539 ColorHoverAndSelected);
1540 // make sure to hide RectHover in this case
1541 UpdateAttachedLabel(nil, TFloatRectangle.Empty, LabelHover, RectHover, Black);
1542 end else
1543 begin
1544 UpdateAttachedLabel(SelectedUI, SelectedUIRect, LabelSelected, RectSelected,
1545 ColorSelected);
1546 UpdateAttachedLabel(HoverUI, HoverUIRect, LabelHover, RectHover,
1547 ColorHover);
1548
1549 { Improve special case, when both RectSelected and RectHover would
1550 be displayed on top of each other. In this case,
1551 shift the RectHover (as the more often changing one). }
1552 if RectSelected.Exists and
1553 RectHover.Exists and
1554 (RectSelected.RenderRect.Bottom = RectHover.RenderRect.Bottom) and
1555 (RectSelected.RenderRect.Left = RectHover.RenderRect.Left ) then
1556 begin
1557 RectHover.Translation := RectHover.Translation - Vector2(0, RectSelected.EffectiveHeight);
1558 end;
1559 end;
1560
1561 RectStatistics.Exists := Frame.OnShowStatistics();
1562 if RectStatistics.Exists then
1563 begin
1564 LabelStatistics.Caption := StatisticsToString;
1565 end;
1566 end;
1567
1568 { TDesignFrame --------------------------------------------------------------- }
1569
1570 constructor TDesignFrame.Create(TheOwner: TComponent);
1571
1572 function CommonInspectorCreate: TCastleObjectInspector;
1573 begin
1574 Result := TCastleObjectInspector.Create(Self);
1575 Result.PropertyEditorHook := PropertyEditorHook;
1576 Result.Align := alClient;
1577 Result.OnModified := @PropertyGridModified;
1578 Result.CheckboxForBoolean := true;
1579 Result.PreferredSplitterX := 150;
1580 Result.ValueFont.Bold := true;
1581 Result.ShowGutter := false;
1582 Result.ReadOnlyColor := clWindowText;
1583
1584 if UseIconsAndColorsForDarkTheme then
1585 begin
1586 Result.GutterColor := $9EFFFF;
1587 Result.ValueFont.Color := $9EFFFF;
1588 Result.SubPropertiesColor := clWindowText;
1589 Result.ReferencesColor := $9EFFFF;
1590 end;
1591 end;
1592 begin
1593 inherited;
1594
1595 LastSelected := TComponentList.Create(false);
1596
1597 PropertyEditorHook := TCastlePropertyEditorHook.Create(Self);
1598
1599 FComponentEditorDesigner := TConcreteEditorDesigner.Create(Self, PropertyEditorHook);
1600
1601 FUndoSystem := TUndoSystem.Create(Self);
1602
1603 Inspector[itBasic] := CommonInspectorCreate;
1604 Inspector[itBasic].Parent := TabBasic;
1605 Inspector[itBasic].OnEditorFilter := @InspectorBasicFilter;
1606 Inspector[itBasic].Filter := tkProperties;
1607
1608 Inspector[itLayout] := CommonInspectorCreate;
1609 Inspector[itLayout].Parent := TabLayout;
1610 Inspector[itLayout].OnEditorFilter := @InspectorLayoutFilter;
1611 Inspector[itLayout].Filter := tkProperties;
1612 Inspector[itLayout].Align := alBottom;
1613 Inspector[itLayout].AnchorToNeighbour(akTop, 0, PanelLayoutTop);
1614
1615 Inspector[itAll] := CommonInspectorCreate;
1616 Inspector[itAll].OnEditorFilter := @InspectorAllFilter;
1617 Inspector[itAll].Parent := TabAll;
1618 Inspector[itAll].Filter := tkProperties;
1619
1620 Inspector[itEvents] := CommonInspectorCreate;
1621 Inspector[itEvents].Parent := TabEvents;
1622 Inspector[itEvents].Filter := tkMethods;
1623 Inspector[itEvents].AnchorToNeighbour(akTop, 0, PanelEventsInfo);
1624
1625 CastleControl := TCastleControl.Create(Self);
1626 CastleControl.AutoFocus := true; // needed on Windows to receive AWSD, Ctrl+Z...
1627 CastleControl.Align := alClient;
1628 {$warnings off} // TODO: upgrade it
1629 CastleControl.OnResize := @CastleControlResize;
1630 CastleControl.OnOpen := @CastleControlOpen;
1631 CastleControl.OnUpdate := @CastleControlUpdate;
1632 {$warnings on}
1633 CastleControl.OnDragOver := @CastleControlDragOver;
1634 CastleControl.OnDragDrop := @CastleControlDragDrop;
1635 CastleControl.Parent := PanelMiddle; // set Parent last, following https://wiki.freepascal.org/LCL_Tips#Set_the_Parent_as_last
1636
1637 {$ifdef DEBUG_GIZMO_PICK}
1638 TCastleControl.MainControl := CastleControl;
1639 {$endif DEBUG_GIZMO_PICK}
1640
1641 FDesignerLayer := TDesignerLayer.Create(Self);
1642 FDesignerLayer.Frame := Self;
1643 CastleControl.Controls.InsertFront(FDesignerLayer);
1644
1645 // It's too easy to change it visually and forget, so we set it from code
1646 ControlProperties.ActivePage := TabBasic;
1647
1648 TreeNodeMap := TTreeNodeMap.Create;
1649
1650 SelfAnchorsFrame.OnAnchorChange := @FrameAnchorsChange;
1651 ParentAnchorsFrame.OnAnchorChange := @FrameAnchorsChange;
1652
1653 VisualizeTransformHover := TVisualizeTransformHover.Create(Self);
1654 VisualizeTransformSelected := TVisualizeTransformSelected.Create(Self);
1655 VisualizeTransformSelected.OnParentModified := @GizmoHasModifiedParent;
1656 VisualizeTransformSelected.OnGizmoStopDrag := @GizmoStopDrag;
1657
1658 SaveDesignDialog.InitialDir := UriToFilenameSafe(ApplicationDataOverride);
1659
1660 TabInfo.TabVisible := false;
1661
1662 ChangeMode(moTranslate); // most expected default
1663
1664 BuildComponentsMenu(
1665 MenuTreeViewItemAddUserInterface,
1666 MenuTreeViewItemAddTransform,
1667 MenuTreeViewItemAddBehavior,
1668 MenuTreeViewItemAddNonVisual,
1669 @MenuItemAddComponentClick);
1670 BuildComponentsMenu(
1671 MenuItemChangeClassUserInterface,
1672 MenuItemChangeClassTransform,
1673 MenuItemChangeClassBehavior,
1674 MenuItemChangeClassNonVisual,
1675 @MenuItemChangeClassClick);
1676
1677 FCurrentViewportObserver := TFreeNotificationObserver.Create(Self);
1678 FCurrentViewportObserver.OnFreeNotification := {$ifdef FPC}@{$endif} CurrentViewportFreeNotification;
1679
1680 // needed to set right action state maybe lazarus bug?
1681 ActionSimulationPauseUnpause.Update;
1682
1683 (*
1684 // The TransformDesigning mechanism works, but it unused for now.
1685 FTransformDesigningObserver := TFreeNotificationObserver.Create(Self);
1686 FTransformDesigningObserver.OnFreeNotification := {$ifdef FPC}@{$endif} TransformDesigningFreeNotification;
1687 *)
1688 UpdateEditorDataForPropertyEditors;
1689
1690 FindActive := false;
1691 SetEnabledVisible(EditFindInHierarchy, FindActive);
1692 end;
1693
1694 destructor TDesignFrame.Destroy;
1695 var
1696 F: TCollectionPropertyEditorForm;
1697 begin
1698 FreeAndNil(TreeNodeMap);
1699 FreeAndNil(CameraPreview);
1700 FreeAndNil(FComponentEditorDesigner);
1701 FreeAndNil(LastSelected);
1702
1703 if CollectionPropertyEditorForm <> nil then
1704 begin
1705 F := CollectionPropertyEditorForm;
1706 CollectionPropertyEditorFormUnassign;
1707 F.Close;
1708 end;
1709
1710 inherited Destroy;
1711 end;
1712
1713 procedure TDesignFrame.CollectionPropertyEditorFormUnassign;
1714 begin
1715 if CollectionPropertyEditorForm <> nil then
1716 begin
1717 // unassign our callbacks from the form, as this TDesignFrame instance will no longer be valid
1718 CollectionPropertyEditorForm.OnClose := nil;
1719 CollectionPropertyEditorForm.CollectionListBox.OnClick := nil;
1720 CollectionPropertyEditorForm.AddButton.OnClick := nil;
1721 CollectionPropertyEditorForm.DeleteButton.OnClick := nil;
1722 CollectionPropertyEditorForm.MoveUpButton.OnClick := nil;
1723 CollectionPropertyEditorForm.MoveDownButton.OnClick := nil;
1724 CollectionPropertyEditorForm.RemoveFreeNotification(Self);
1725 CollectionPropertyEditorForm := nil;
1726 end;
1727 end;
1728
1729 procedure TDesignFrame.Notification(AComponent: TComponent; Operation: TOperation);
1730 begin
1731 inherited;
1732 if (Operation = opRemove) and (AComponent = CollectionPropertyEditorForm) then
1733 CollectionPropertyEditorFormUnassign;
1734 end;
1735
1736 procedure TDesignFrame.SaveDesign(const Url: String);
1737 begin
1738 if DesignRoot is TCastleUserInterface then
1739 UserInterfaceSave(TCastleUserInterface(DesignRoot), Url)
1740 else
1741 if DesignRoot is TCastleTransform then
1742 TransformSave(TCastleTransform(DesignRoot), Url)
1743 else
1744 ComponentSave(DesignRoot, Url);
1745 FDesignModified := false;
1746 FDesignUrl := Url; // after successfull save
1747 OnUpdateFormCaption(Self);
1748 end;
1749
1750 procedure TDesignFrame.ClearDesign;
1751 begin
1752 // ControlsTree.Items.Clear; // do not clear, we will always rebuild ControlsTree to just apply differences
1753
1754 ControlsTree.ClearSelection; // TODO: for now we reset selection, though maybe we could preserve it in some cases
1755
1756 UpdateSelectedControl;
1757 //CastleControl.Controls.Clear; // don't clear it, leave DesignerLayer
1758 FDesignRoot := nil;
1759 FreeAndNil(CameraPreview);
1760
1761 // this actually frees everything inside DesignRoot
1762 FreeAndNil(DesignOwner);
1763 end;
1764
1765 procedure TDesignFrame.PerformUndoRedo(const UHE: TUndoHistoryElement);
1766 var
1767 NewDesignOwner, NewDesignRoot: TComponent;
1768 InspectorType: TInspectorType;
1769 LoadInfo: TInternalComponentLoadInfo;
1770 begin
1771 for InspectorType in TInspectorType do
1772 Inspector[InspectorType].SaveChanges;
1773
1774 LoadInfo := TInternalComponentLoadInfo.Create;
1775 try
1776 LoadInfo.PreserveDataAcrossUndo := DesignOwner;
1777
1778 NewDesignOwner := TComponent.Create(Self);
1779 NewDesignRoot := InternalStringToComponent(UHE.Data, NewDesignOwner, LoadInfo);
1780 OpenDesign(NewDesignRoot, NewDesignOwner, FDesignUrl);
1781 finally FreeAndNil(LoadInfo) end;
1782
1783 RestoreSavedSelection(UHE.Selection);
1784 end;
1785
1786 function TDesignFrame.GetInspectorForActiveTab: TOIPropertyGrid;
1787 var
1788 InspectorType: TInspectorType;
1789 begin
1790 for InspectorType in TInspectorType do
1791 begin
1792 if Inspector[InspectorType].Parent = ControlProperties.ActivePage then
1793 Exit(Inspector[InspectorType]);
1794 end;
1795 Result := nil;
1796 end;
1797
1798 function TDesignFrame.GetSavedSelection: TSavedSelection;
1799 var
1800 SelectedC: TComponent;
1801 ActiveInspector: TOIPropertyGrid;
1802 begin
1803 SelectedC := GetSelectedComponent;
1804 { In case of modifying subcomponent, like TCastleViewport.Items,
1805 the currently selected component is not owned by whole design owner,
1806 so it will not be later found by name in RestoreSavedSelection. }
1807 if (SelectedC <> nil) and
1808 (SelectedC.Owner = DesignOwner) then
1809 Result.SelectedComponent := SelectedC.Name
1810 else
1811 Result.SelectedComponent := '';
1812
1813 if (CurrentViewport <> nil) and
1814 (CurrentViewport.Owner = DesignOwner) then
1815 Result.CurrentViewport := CurrentViewport.Name
1816 else
1817 Result.CurrentViewport := '';
1818
1819 Result.TabIndex := ControlProperties.TabIndex;
1820
1821 ActiveInspector := GetInspectorForActiveTab;
1822 if ActiveInspector <> nil then
1823 Result.ItemIndex := ActiveInspector.ItemIndex
1824 else
1825 Result.ItemIndex := -1;
1826 end;
1827
1828 procedure TDesignFrame.RestoreSavedSelection(const S: TSavedSelection);
1829 var
1830 C: TComponent;
1831 V: TCastleViewport;
1832 ActiveInspector: TOIPropertyGrid;
1833 begin
1834 if S.SelectedComponent <> '' then
1835 begin
1836 C := DesignOwner.FindComponent(S.SelectedComponent);
1837 if C = nil then
1838 begin
1839 WritelnLog('Cannot restore selection, as component "%s" no longer exists. This is normal if e.g. stopping physics removes an object added during physics simulation.', [
1840 S.SelectedComponent
1841 ]);
1842 end else
1843 begin
1844 SetSelectedComponent(C);
1845
1846 { Restore object inspector state only if we could restore SelectedComponent,
1847 as object inspector should show the selected component. }
1848 if S.ItemIndex >= 0 then
1849 begin
1850 ControlProperties.TabIndex := S.TabIndex;
1851
1852 ActiveInspector := GetInspectorForActiveTab;
1853 if ActiveInspector <> nil then
1854 ActiveInspector.SetItemIndexAndFocus(S.ItemIndex)
1855 else
1856 WritelnWarning('Cannot restore selection inspector ItemIndex, because inspector not found');
1857 end;
1858 end;
1859 end;
1860
1861 if S.CurrentViewport <> '' then
1862 begin
1863 { We restore CurrentViewport, otherwise stopping physics would set CurrentViewport
1864 to nil if it was previously made non-nil because of hovering over a viewport
1865 (and not selecting viewport or something inside viewport). }
1866 C := DesignOwner.FindComponent(S.CurrentViewport);
1867 if (C = nil) or not (C is TCastleViewport) then
1868 begin
1869 WritelnLog('Cannot restore CurrentViewport, as viewport "%s" no longer exists or is no longer a TCastleViewport.', [
1870 S.CurrentViewport
1871 ]);
1872 end else
1873 begin
1874 V := C as TCastleViewport;
1875 SetCurrentViewport(V);
1876 { Note: This will also update FShowColliders on viewport,
1877 so e.g. Stop of physics will keep showing colliders. }
1878 end;
1879 end;
1880
1881 { After restoring design, reliably focus the CastleControl,
1882 not the edit box of some property
1883 (which is optionally done by ActiveInspector.SetItemIndexAndFocus above).
1884 This allows using our general shortcuts, like Ctrl+Z, reliably after RestoreSavedSelection,
1885 in particular you can use Ctrl+Z after Ctrl+Z. }
1886 FocusDesign;
1887 end;
1888
1889 procedure TDesignFrame.PerformRedo;
1890 begin
1891 PerformUndoRedo(UndoSystem.Redo);
1892 end;
1893
1894 procedure TDesignFrame.PerformUndo;
1895 begin
1896 {//save current edited value and
1897 if not UndoSystem.IsRedoPossible then
1898 begin
1899 RecordUndo;
1900 UndoSystem.Undo;
1901 end;}
1902 PerformUndoRedo(UndoSystem.Undo);
1903 end;
1904
1905 procedure TDesignFrame.UpdateObjectInspectorTimer(Sender: TObject);
1906 //var
1907 // InspectorType: TInspectorType;
1908 begin
1909 { In many cases, properties may change but property editor doesn't reflect it.
1910 E.g.
1911 - TCastleTransform changes by ExposeTransforms mechanism
1912 - Caption changes because you modified Name, and they used to match.
1913 The only universal solution to make OI up-to-date seems to be to just
1914 occasionally refresh it. }
1915
1916 // TODO: This is not good, it breaks editing within object inspector, resets cursor
1917 //for InspectorType in TInspectorType do
1918 // Inspector[InspectorType].RefreshPropertyValues;
1919 end;
1920
1921 procedure TDesignFrame.OpenDesign(const NewDesignRoot, NewDesignOwner: TComponent;
1922 NewDesignUrl: String);
1923
1924 { Note: NewDesignUrl parameter is *not* const.
1925
1926 Because OpenDesign uses ClearDesign which destroys some components,
1927 and one of these components may be the owner of AnsiString with NewDesignUrl.
1928 So we have to keep refcount of NewDesignUrl,
1929 otherwise ClearDesign could free NewDesignUrl and then all its
1930 refences are invalid pointers, and OnUpdateFormCaption will crash.
1931
1932 Testcase: Open any UI state design that uses TCastleDesign, click
1933 "Open Referenced Design".
1934 In this case, TCastleDesignComponentEditor.ExecuteVerb passes
1935 TCastleDesign.URL and NewDesignUrl, and ClearDesign removes this
1936 TCastleDesign instance.
1937 }
1938
1939 { Initialize TCastleViewport that is internal, and used to edit
1940 .castle-transform. It requires some special considerations,
1941 as it needs a good camera/navigation, but also user cannot modify them,
1942 and they are not saved to .castle-transform. }
1943 procedure InitializeDesignViewportForTransforms(const V: TCastleViewport);
1944 var
1945 APos, ADir, AUp, AGravityUp: TVector3;
1946 begin
1947 { This Name is user-visible: if user selects anything in viewport,
1948 we show CurrentViewport.Name in header. }
1949 V.Name := 'InternalViewport';
1950 V.Transparent := true;
1951 V.FullSize := true;
1952
1953 { Add headlight to design-time camera this way.
1954 Note that doing "V.Items.UseHeadLight := hlOn" would not have a desired
1955 effect, as this headlight would be done only from runtime camera,
1956 which we don't care about in this case. }
1957 V.InternalCamera.Add(TCastleDirectionalLight.Create(NewDesignOwner));
1958
1959 CameraViewpointForWholeScene(V.Items.BoundingBox, 2, 1, false, true,
1960 APos, ADir, AUp, AGravityUp);
1961 V.InternalCamera.SetWorldView(APos, ADir, AUp);
1962 V.InternalCamera.GravityUp := AGravityUp;
1963 end;
1964
1965 var
1966 //LabelNonVisualHint: TCastleLabel;
1967 DesignRootVisual: Boolean;
1968 begin
1969 ClearDesign;
1970
1971 { We use CastleControl.Controls.InsertBack here, to keep DesignerLayer
1972 in the front. }
1973
1974 DesignRootVisual :=
1975 (NewDesignRoot is TCastleUserInterface) or
1976 (NewDesignRoot is TCastleTransform);
1977
1978 if DesignRootVisual then
1979 begin
1980 CameraPreview := TCameraPreview.Create(nil, NewDesignOwner);
1981 CastleControl.Controls.InsertBack(CameraPreview.UiRoot);
1982 end;
1983
1984 if NewDesignRoot is TCastleUserInterface then
1985 begin
1986 CastleControl.Controls.InsertBack(NewDesignRoot as TCastleUserInterface);
1987 Assert(DesignRootVisual);
1988 end else
1989 if NewDesignRoot is TCastleTransform then
1990 begin
1991 FDesignViewportForTransforms := TCastleViewport.Create(NewDesignOwner);
1992 FDesignViewportForTransforms.Items.Add(NewDesignRoot as TCastleTransform);
1993 { Do this after adding NewDesignRoot, as it wants good Items.BoundingBox }
1994 InitializeDesignViewportForTransforms(FDesignViewportForTransforms);
1995 CastleControl.Controls.InsertBack(FDesignViewportForTransforms);
1996 Assert(DesignRootVisual);
1997 end else
1998 begin
1999 { This is normal situation for non-visual components. }
2000 (*
2001 LabelNonVisualHint := TCastleLabel.Create(NewDesignOwner);
2002 LabelNonVisualHint.Caption := 'This design does not contain any visual components.' + NL +
2003 'The root of this design has class:' + NL +
2004 NL +
2005 NewDesignRoot.ClassName;
2006 LabelNonVisualHint.Anchor(hpMiddle);
2007 LabelNonVisualHint.Anchor(vpMiddle);
2008 LabelNonVisualHint.FontSize := 40;
2009 CastleControl.Controls.InsertBack(LabelNonVisualHint);
2010 *)
2011 Assert(not DesignRootVisual);
2012 end;
2013
2014 SetEnabledVisible(CastleControl, DesignRootVisual);
2015 SetEnabledVisible(PanelMiddleTop, DesignRootVisual);
2016
2017 // set background to gray
2018 CastleControl.Container.BackgroundColor := Vector4(0.5, 0.5, 0.5, 1);
2019
2020 // replace DesignXxx variables, once loading successfull
2021 FDesignRoot := NewDesignRoot;
2022 FDesignUrl := NewDesignUrl;
2023 DesignOwner := NewDesignOwner;
2024 FDesignModified := DesignUrl = ''; // when opening '', mark new hierarchy modified
2025
2026 // Allows object inspectors to find matching components, e.g. when editing Viewport.Items.MainScene
2027 PropertyEditorHook.LookupRoot := DesignOwner;
2028 PropertyEditorHook.AddHandlerModified(@PropertyEditorModified);
2029
2030 UpdateDesign;
2031 OnUpdateFormCaption(Self);
2032 end;
2033
2034 procedure TDesignFrame.OpenDesign(const NewDesignUrl: String);
2035 var
2036 NewDesignRoot, NewDesignOwner: TComponent;
2037 Mime: String;
2038 begin
2039 NewDesignOwner := TComponent.Create(Self);
2040
2041 try
2042 Mime := UriMimeType(NewDesignUrl);
2043 if Mime = 'text/x-castle-user-interface' then
2044 NewDesignRoot := UserInterfaceLoad(NewDesignUrl, NewDesignOwner)
2045 else
2046 if Mime = 'text/x-castle-transform' then
2047 NewDesignRoot := TransformLoad(NewDesignUrl, NewDesignOwner)
2048 else
2049 if Mime = 'text/x-castle-component' then
2050 NewDesignRoot := ComponentLoad(NewDesignUrl, NewDesignOwner)
2051 else
2052 raise Exception.CreateFmt('Unrecognized file extension %s (MIME type %s)',
2053 [ExtractFileExt(NewDesignUrl), Mime]);
2054 except
2055 { Testcase: try to load using UserInterfaceLoad a file
2056 that has TCastleTransform inside. UserInterfaceLoad makes EInvalidCast. }
2057 on E: Exception do
2058 begin
2059 E.Message := 'Error when loading ' + UriDisplay(NewDesignUrl) + ': ' + E.Message;
2060 raise;
2061 end;
2062 end;
2063
2064 UndoSystem.ClearUndoHistory;
2065
2066 OpenDesign(NewDesignRoot, NewDesignOwner, NewDesignUrl);
2067
2068 RecordUndo('Open design', High(TUndoCommentPriority)); // Technically this is impossible to see this Undo comment
2069 end;
2070
2071 function TDesignFrame.FormCaption: String;
2072 var
2073 DesignName: String;
2074 begin
2075 // calculate DesignName
2076 if DesignUrl <> '' then
2077 DesignName := ExtractUriName(DesignUrl)
2078 else
2079 if DesignRoot is TCastleTransform then
2080 DesignName := 'New Transform'
2081 else
2082 if DesignRoot is TCastleUserInterface then
2083 DesignName := 'New User Interface'
2084 else
2085 // generic, should not happen now
2086 DesignName := 'New Component';
2087 Result := '[' + Iff(DesignModified, '*', '') + DesignName + '] ';
2088 end;
2089
2090 procedure TDesignFrame.BeforeProposeSaveDesign;
2091 var
2092 InspectorType: TInspectorType;
2093 begin
2094 { call SaveChanges to be sure to have good DesignModified value.
2095 Otherwise when editing e.g. TCastleButton.Caption,
2096 you can press F9 and have DesignModified = false,
2097 because PropertyGridModified doesn't occur because we actually
2098 press "tab" to focus another control. }
2099 for InspectorType in TInspectorType do
2100 Inspector[InspectorType].SaveChanges;
2101 end;
2102
2103 procedure TDesignFrame.AddComponent(const ComponentClass: TComponentClass;
2104 const ComponentOnCreate: TNotifyEvent);
2105 var
2106 ParentComponent: TComponent;
2107 begin
2108 // calculate ParentComponent
2109 ParentComponent := GetSelectedComponent;
2110 { User can use "Add Behavior" when another TCastleBehavior is selected,
2111 it means to insert into the parent TCastleTransform.
2112 E.g. usecase: add collider when rigid body is selected. }
2113 if ComponentClass.InheritsFrom(TCastleBehavior) and
2114 (ParentComponent is TCastleBehavior) then
2115 begin
2116 ParentComponent := TCastleBehavior(ParentComponent).Parent;
2117 end;
2118 { If nothing was selected, add to DesignRoot }
2119 if ParentComponent = nil then
2120 ParentComponent := DesignRoot;
2121
2122 AddComponent(ParentComponent, ComponentClass, ComponentOnCreate);
2123 end;
2124
2125 function TDesignFrame.AddComponent(const ParentComponent: TComponent;
2126 const ComponentClass: TComponentClass;
2127 const ComponentOnCreate: TNotifyEvent;
2128 const BaseNewComponentName: String): TComponent;
2129
2130 function CreateComponent: TComponent;
2131 begin
2132 Result := ComponentClass.Create(DesignOwner) as TComponent;
2133 if Assigned(ComponentOnCreate) then // call ComponentOnCreate ASAP after constructor
2134 ComponentOnCreate(Result);
2135 Result.Name := ProposeComponentName(ComponentClass, DesignOwner, BaseNewComponentName);
2136 end;
2137
2138 procedure FinishAddingComponent(const NewComponent: TComponent);
2139 begin
2140 UpdateDesign;
2141 SelectedComponent := NewComponent; // select after adding, makes it natural to edit
2142 ModifiedOutsideObjectInspector('Add ' + NewComponent.Name + ' to ' + ParentComponent.Name, ucHigh);
2143 end;
2144
2145 procedure AutoCreateRigidBody(const Collider: TCastleCollider; const ParentComponent: TCastleTransform);
2146 var
2147 RBody: TCastleRigidBody;
2148 begin
2149 RBody := AddComponent(ParentComponent, TCastleRigidBody, nil) as TCastleRigidBody;
2150 if Collider.Mode2D then
2151 RBody.Setup2D;
2152 end;
2153
2154 function AddToTransform(const ParentComponent: TCastleTransform): TComponent;
2155 begin
2156 if ComponentClass.InheritsFrom(TCastleTransform) then
2157 begin
2158 Result := CreateComponent;
2159 ParentComponent.Add(Result as TCastleTransform);
2160 FinishAddingComponent(Result);
2161 end else
2162 if ComponentClass.InheritsFrom(TCastleUserInterface) then
2163 begin
2164 raise Exception.Create(Format('Cannot add TCastleUserInterface descendant (%s) when the parent is a TCastleTransform descendant (%s). Select a parent that descends from TCastleUserInterface.',
2165 [ComponentClass.ClassName, ParentComponent.ClassName]))
2166 end else
2167 if ComponentClass.InheritsFrom(TCastleBehavior) then
2168 begin
2169 Result := CreateComponent;
2170 ParentComponent.AddBehavior(Result as TCastleBehavior);
2171 try
2172 { Show colliders on newly added component }
2173 if (Result is TCastleCollider) and FShowColliders then
2174 UpdateColliders(ParentComponent);
2175 { If component is TCastleMeshCollider try to set Scene property to parent }
2176 if (Result is TCastleMeshCollider) and ParentComponent.HasColliderMesh then
2177 (Result as TCastleMeshCollider).Mesh := ParentComponent;
2178 (*
2179 // The TransformDesigning mechanism works, but it unused for now.
2180 { When creating new behavior under selected transform, call DesigningBegin.
2181 This way temporary anchors appear immediately on newly added physics joint. }
2182 if ParentComponent = TransformDesigning then
2183 (Result as TCastleBehavior).DesigningBegin;
2184 *)
2185 { auto-create TCastleRigidBody after adding collider }
2186 if (Result is TCastleCollider) and
2187 (ParentComponent.FindBehavior(TCastleRigidBody) = nil) then
2188 AutoCreateRigidBody(TCastleCollider(Result), ParentComponent);
2189 finally
2190 FinishAddingComponent(Result);
2191 end;
2192 end else
2193 begin
2194 Result := CreateComponent;
2195 ParentComponent.AddNonVisualComponent(Result);
2196 FinishAddingComponent(Result);
2197 end;
2198 end;
2199
2200 function AddToUserInterface(const ParentComponent: TCastleUserInterface): TComponent;
2201 begin
2202 if ComponentClass.InheritsFrom(TCastleUserInterface) then
2203 begin
2204 Result := CreateComponent;
2205 ParentComponent.InsertFront(Result as TCastleUserInterface);
2206 FinishAddingComponent(Result);
2207 end else
2208 if ComponentClass.InheritsFrom(TCastleTransform) then
2209 begin
2210 raise Exception.Create(Format('Cannot add TCastleTransform descendant (%s) when the parent is a TCastleUserInterface descendant (%s). Select a parent that descends from TCastleTransform, for example select Viewport.Items.',
2211 [ComponentClass.ClassName, ParentComponent.ClassName]))
2212 end else
2213 if ComponentClass.InheritsFrom(TCastleBehavior) then
2214 begin
2215 raise Exception.Create(Format('Cannot add TCastleBehavior descendant (%s) when the parent is a TCastleUserInterface descendant (%s). Select a parent that descends from TCastleTransform, like TCastleTransform itself or TCastleScene.',
2216 [ComponentClass.ClassName, ParentComponent.ClassName]))
2217 end else
2218 begin
2219 Result := CreateComponent;
2220 ParentComponent.AddNonVisualComponent(Result);
2221 FinishAddingComponent(Result);
2222 end;
2223 end;
2224
2225 function AddToComponent(const ParentComponent: TCastleComponent): TComponent;
2226 begin
2227 { Note that, technically,
2228 we could add TCastleUserInterface/TCastleTransform/TCastleBehavior
2229 to non-visual components list.
2230 But this would be confusing, so we disallow it in editor. }
2231 if ComponentClass.InheritsFrom(TCastleUserInterface) then
2232 begin
2233 raise Exception.Create(Format('To add TCastleUserInterface descendant (%s), select a parent that descends from TCastleUserInterface.',
2234 [ComponentClass.ClassName, ParentComponent.ClassName]))
2235 end else
2236 if ComponentClass.InheritsFrom(TCastleTransform) then
2237 begin
2238 raise Exception.Create(Format('To add TCastleTransform descendant (%s), select a parent that descends from TCastleTransform, for example select Viewport.Items.',
2239 [ComponentClass.ClassName, ParentComponent.ClassName]))
2240 end else
2241 if ComponentClass.InheritsFrom(TCastleBehavior) then
2242 begin
2243 raise Exception.Create(Format('To add TCastleBehavior descendant (%s), select a parent that descends from TCastleTransform, like TCastleTransform itself or TCastleScene.',
2244 [ComponentClass.ClassName, ParentComponent.ClassName]))
2245 end else
2246 begin
2247 Result := CreateComponent;
2248 ParentComponent.AddNonVisualComponent(Result);
2249 FinishAddingComponent(Result);
2250 end;
2251 end;
2252
2253 begin
2254 { Cancel editing the component name, when adding a component.
2255 See https://trello.com/c/IC6NQx0X/59-bug-adding-a-component-to-a-component-that-is-being-currently-renamed-triggers-and-exception . }
2256 if ControlsTreeOneSelected <> nil then
2257 ControlsTreeOneSelected.EndEdit(true);
2258
2259 if ParentComponent is TCastleUserInterface then
2260 begin
2261 Exit(AddToUserInterface(TCastleUserInterface(ParentComponent)));
2262 end else
2263 if ParentComponent is TCastleTransform then
2264 begin
2265 Exit(AddToTransform(TCastleTransform(ParentComponent)));
2266 end else
2267 if ParentComponent is TCastleComponent then
2268 begin
2269 Exit(AddToComponent(ParentComponent as TCastleComponent));
2270 end else
2271 raise Exception.Create(Format('Cannot add to the parent of class %s, select other parent before adding.',
2272 [ParentComponent.ClassName]))
2273 end;
2274
2275 procedure TDesignFrame.FreeComponentRecursively(const C: TComponent);
2276
2277 procedure FreeNonVisualChildren(const C: TCastleComponent);
2278 var
2279 I: Integer;
2280 begin
2281 for I := C.NonVisualComponentsCount - 1 downto 0 do
2282 if Deletable(C.NonVisualComponents[I]) then
2283 FreeComponentRecursively(C.NonVisualComponents[I]);
2284 end;
2285
2286 procedure FreeTransformChildren(const T: TCastleTransform);
2287 var
2288 I: Integer;
2289 begin
2290 for I := T.Count - 1 downto 0 do
2291 if Deletable(T[I]) then
2292 FreeComponentRecursively(T[I]);
2293 end;
2294
2295 procedure FreeBehaviorChildren(const T: TCastleTransform);
2296 var
2297 I: Integer;
2298 begin
2299 for I := T.BehaviorsCount - 1 downto 0 do
2300 if Deletable(T.Behaviors[I]) then
2301 FreeComponentRecursively(T.Behaviors[I]);
2302 end;
2303
2304 procedure FreeUiChildren(const C: TCastleUserInterface);
2305 var
2306 I: Integer;
2307 begin
2308 for I := C.ControlsCount - 1 downto 0 do
2309 if Deletable(C.Controls[I]) then
2310 FreeComponentRecursively(C.Controls[I]);
2311 end;
2312
2313 begin
2314 if not Deletable(C) then
2315 Exit;
2316
2317 { Check this assertion after Deletable check, as it may be invalid
2318 e.g. for gizmos that are csTransient. }
2319 Assert(C.Owner = DesignOwner);
2320
2321 if C is TCastleComponent then
2322 begin
2323 FreeNonVisualChildren(TCastleComponent(C));
2324 if C is TCastleTransform then
2325 begin
2326 FreeBehaviorChildren(TCastleTransform(C));
2327 FreeTransformChildren(TCastleTransform(C));
2328 end else
2329 if C is TCastleUserInterface then
2330 begin
2331 FreeUiChildren(TCastleUserInterface(C));
2332 if C is TCastleViewport then
2333 begin
2334 FreeBehaviorChildren(TCastleViewport(C).Items);
2335 FreeTransformChildren(TCastleViewport(C).Items);
2336 end;
2337 end;
2338 end;
2339 { Remove designing objects before delete behavior }
2340 // if C is TCastleBehavior then
2341 // TCastleBehavior(C).DesigningEnd;
2342 C.Free;
2343
2344 UpdateDesign;
2345 end;
2346
2347 procedure TDesignFrame.DeleteComponent(const AutoSelectParents: Boolean = false);
2348
2349 { Explain to user why C cannot be deleted.
2350 We know that Deletable(C) = false at this point. }
2351 function ReasonWhyNotDeletable(const C: TComponent): String;
2352 var
2353 ReasonStart: String;
2354 begin
2355 ReasonStart := 'Cannot remove "' + C.Name + '":' + NL + NL;
2356
2357 // This analyzes some conditions of Deletable and Selectable
2358 if C is TCastleToolTransform then
2359 Exit(ReasonStart + 'This is a temporary (tool) component, helpful to edit something, but it is not part of the final design. Use "Hide Joint Tools" to hide it.');
2360 if csTransient in C.ComponentStyle then
2361 Exit(ReasonStart + 'This is an internal component, you should not be able to even select it.');
2362 if csSubComponent in C.ComponentStyle then
2363 Exit(ReasonStart + 'This is a subcomponent, and subcomponents cannot be removed because owner depends that they always exist.');
2364 if C = DesignRoot then
2365 Exit(ReasonStart + 'This is the root component of the design. Design must always have a root component. You can only change it to something else using "Change Class".');
2366
2367 // Shorter error message, if we don't know any specific reason
2368 Result := 'Cannot remove "' + C.Name + '".';
2369 end;
2370
2371 function FirstDeletableComponent(const List: TComponentList): TComponent;
2372 var
2373 I: Integer;
2374 begin
2375 for I := 0 to List.Count - 1 do
2376 if Deletable(List[I]) then
2377 Exit(List[I]);
2378 Result := nil;
2379 end;
2380
2381 var
2382 Selected: TComponentList;
2383 SelectedCount: Integer;
2384 C: TComponent;
2385 UndoSummary: String;
2386 begin
2387 GetSelected(Selected, SelectedCount, AutoSelectParents);
2388 try
2389 if SelectedCount <> 0 then // check this, otherwise Selected may be nil
2390 begin
2391 if SelectedCount = 1 then
2392 UndoSummary := Selected[0].Name
2393 else
2394 UndoSummary := SelectedCount.ToString + ' components';
2395
2396 if (SelectedCount = 1) and not Deletable(Selected[0]) then
2397 begin
2398 { In this case we will not remove anything.
2399 Be vocal to user to explain "why", e.g. why root components cannot be removed. }
2400 ErrorBox(ReasonWhyNotDeletable(Selected[0]));
2401 Exit;
2402 end;
2403
2404 { We depend on the fact TComponentList observes freed items,
2405 and removes them automatically.
2406 This way also freeing something that frees something else
2407 should work (although we don't really need it now,
2408 DesignOwner owns everything). }
2409
2410 repeat
2411 C := FirstDeletableComponent(Selected);
2412 if C <> nil then
2413 FreeComponentRecursively(C)
2414 else
2415 Break;
2416 until false;
2417
2418 { call this after UpdateDesign, otherwise tree is not ready,
2419 and events caused by ModifiedOutsideObjectInspector may expect it is. }
2420 ModifiedOutsideObjectInspector('Delete ' + UndoSummary, ucHigh);
2421 end;
2422 finally FreeAndNil(Selected) end;
2423 end;
2424
2425 procedure TDesignFrame.CopyComponent;
2426 const
2427 { For copying, copying auto-parent is not intuitive,
2428 see https://github.com/castle-engine/castle-engine/issues/522 . }
2429 AutoSelectParents = false;
2430 var
2431 Sel: TComponent;
2432 begin
2433 Sel := GetSelectedComponent(AutoSelectParents);
2434 if (Sel <> nil) and
2435 (not (csSubComponent in Sel.ComponentStyle)) then
2436 begin
2437 Clipboard.AsText := ComponentToString(Sel)
2438 end else
2439 begin
2440 ErrorBox('Select exactly one component, that is not a subcomponent, to copy');
2441 end;
2442 end;
2443
2444 procedure TDesignFrame.PasteComponent;
2445
2446 procedure FinishAddingComponent(const NewComponent: TComponent);
2447 begin
2448 UpdateDesign;
2449 SelectedComponent := NewComponent; // select after adding, makes it natural to edit
2450 ModifiedOutsideObjectInspector('Paste ' + NewComponent.Name, ucHigh);
2451 end;
2452
2453 var
2454 Selected: TComponentList;
2455 SelectedCount: Integer;
2456 ParentComponent, NewComponent: TComponent;
2457 begin
2458 try
2459 NewComponent := StringToComponent(Clipboard.AsText, DesignOwner);
2460 except
2461 on E: Exception do
2462 begin
2463 ErrorBox('Cliboard doesn''t seem to contain a copied component.' + NL + NL +
2464 'Trying to deserialize it failed with the error:' + NL + NL +
2465 ExceptMessage(E));
2466 Exit;
2467 end;
2468 end;
2469
2470 // calculate ParentComponent
2471 GetSelected(Selected, SelectedCount);
2472 try
2473 if SelectedCount = 1 then
2474 ParentComponent := Selected.First
2475 else
2476 ParentComponent := DesignRoot;
2477 finally FreeAndNil(Selected) end;
2478
2479 if NewComponent is TCastleUserInterface then
2480 begin
2481 if not (ParentComponent is TCastleUserInterface) then
2482 begin
2483 ErrorBox('Clipboard contains a TCastleUserInterface instance, you need to select a TCastleUserInterface as a parent before doing "Paste Component"');
2484 FreeAndNil(NewComponent);
2485 Exit;
2486 end;
2487 (ParentComponent as TCastleUserInterface).InsertFront(NewComponent as TCastleUserInterface);
2488 FinishAddingComponent(NewComponent);
2489 end else
2490 if NewComponent is TCastleTransform then
2491 begin
2492 if not (ParentComponent is TCastleTransform) then
2493 begin
2494 ErrorBox('Clipboard contains a TCastleTransform instance, you need to select a TCastleTransform as a parent before doing "Paste Component"');
2495 FreeAndNil(NewComponent);
2496 Exit;
2497 end;
2498 (ParentComponent as TCastleTransform).Add(NewComponent as TCastleTransform);
2499 FinishAddingComponent(NewComponent);
2500 end else
2501 if NewComponent is TCastleBehavior then
2502 begin
2503 if not (ParentComponent is TCastleTransform) then
2504 begin
2505 ErrorBox('Clipboard contains a TCastleTransform instance, you need to select a TCastleTransform as a parent before doing "Paste Component"');
2506 FreeAndNil(NewComponent);
2507 Exit;
2508 end;
2509 (ParentComponent as TCastleTransform).AddBehavior(NewComponent as TCastleBehavior);
2510 FinishAddingComponent(NewComponent);
2511 end else
2512 begin
2513 ErrorBox(Format('Clipboard contains an instance of %s class, cannot insert it into the design',
2514 [NewComponent.ClassName]));
2515 FreeAndNil(NewComponent);
2516 end;
2517 end;
2518
2519 procedure TDesignFrame.CutComponent;
2520 const
2521 { For deletion, better to not select parent to avoid removing too much.
2522 See https://github.com/castle-engine/castle-engine/issues/521 . }
2523 AutoSelectParents = false;
2524 var
2525 Sel: TComponent;
2526 begin
2527 Sel := GetSelectedComponent(AutoSelectParents);
2528 if (Sel <> nil) and
2529 (not (csSubComponent in Sel.ComponentStyle)) then
2530 begin
2531 Clipboard.AsText := ComponentToString(Sel);
2532 DeleteComponent(AutoSelectParents);
2533 end else
2534 begin
2535 ErrorBox('Select exactly one component, that is not a subcomponent, to copy');
2536 end;
2537 end;
2538
2539 function TDesignFrame.NonVisualComponentParent(const C: TComponent): TCastleComponent;
2540 var
2541 CNode: TTreeNode;
2542 ParentComp: TComponent;
2543 begin
2544 if not TreeNodeMap.TryGetValue(C, CNode) then
2545 raise EInternalError.Create('Cannot get parent of non-visual component: we cannot find the node in ControlsTree');
2546
2547 // This can happen if C is root component in design
2548 if CNode.Parent = nil then
2549 Exit(nil);
2550
2551 { Note: SelectedFromNode will automatically lookup higher parent,
2552 in case parent is special "Non-visual component" text node. }
2553 ParentComp := SelectedFromNode(CNode.Parent);
2554 if ParentComp = nil then
2555 raise EInternalError.Create('Cannot get parent of non-visual component: parent node not a regular component');
2556
2557 if not (ParentComp is TCastleComponent) then
2558 raise EInternalError.Create('Cannot get parent of non-visual component: parent is TComponent but not TCastleComponent');
2559
2560 Result := ParentComp as TCastleComponent;
2561 end;
2562
2563 procedure TDesignFrame.DuplicateComponent;
2564
2565 procedure FinishAddingComponent(const NewComponent: TComponent);
2566 var
2567 OldComponentName: String;
2568 begin
2569 OldComponentName := SelectedComponent.Name;
2570 UpdateDesign;
2571 SelectedComponent := NewComponent; // select after adding, makes it natural to edit
2572 ModifiedOutsideObjectInspector('Duplicate ' + OldComponentName + '->' + NewComponent.Name, ucHigh);
2573 end;
2574
2575 procedure DuplicateUserInterface(const Selected: TCastleUserInterface);
2576 var
2577 ParentComp, NewComp: TCastleUserInterface;
2578 ComponentString: String;
2579 InsertIndex: Integer;
2580 begin
2581 ParentComp := Selected.Parent;
2582 if ParentComp = nil then
2583 begin
2584 ErrorBox('To duplicate, select component with exactly one parent');
2585 Exit;
2586 end;
2587 ComponentString := ComponentToString(Selected);
2588 NewComp := StringToComponent(ComponentString, DesignOwner) as TCastleUserInterface;
2589 InsertIndex := ParentComp.IndexOfControl(Selected);
2590 ParentComp.InsertControl(InsertIndex + 1, NewComp);
2591 FinishAddingComponent(NewComp);
2592 end;
2593
2594 procedure DuplicateTransform(const Selected: TCastleTransform);
2595 var
2596 ParentComp, NewComp: TCastleTransform;
2597 ComponentString: String;
2598 InsertIndex: Integer;
2599 begin
2600 ParentComp := Selected.Parent;
2601 if ParentComp = nil then
2602 begin
2603 ErrorBox('To duplicate, select component with exactly one parent');
2604 Exit;
2605 end;
2606 ComponentString := ComponentToString(Selected);
2607 NewComp := StringToComponent(ComponentString, DesignOwner) as TCastleTransform;
2608 InsertIndex := ParentComp.List.IndexOf(Selected);
2609 ParentComp.Insert(InsertIndex + 1, NewComp);
2610 FinishAddingComponent(NewComp);
2611 end;
2612
2613 procedure DuplicateNonVisualComponent(const Selected: TCastleComponent);
2614 var
2615 ParentComp, NewComp: TCastleComponent;
2616 ComponentString: String;
2617 InsertIndex: Integer;
2618 begin
2619 ParentComp := NonVisualComponentParent(Selected);
2620 if ParentComp = nil then
2621 begin
2622 ErrorBox('To duplicate, select component with exactly one parent');
2623 Exit;
2624 end;
2625 ComponentString := ComponentToString(Selected);
2626 NewComp := StringToComponent(ComponentString, DesignOwner) as TCastleComponent;
2627 InsertIndex := ParentComp.NonVisualComponentsIndexOf(Selected);
2628 ParentComp.InsertNonVisualComponent(InsertIndex + 1, NewComp);
2629 FinishAddingComponent(NewComp);
2630 end;
2631
2632 var
2633 Sel: TComponent;
2634 begin
2635 Sel := SelectedComponent;
2636
2637 if (Sel <> nil) and
2638 (not (csSubComponent in Sel.ComponentStyle)) then
2639 begin
2640 if Sel is TCastleUserInterface then
2641 DuplicateUserInterface(Sel as TCastleUserInterface)
2642 else
2643 if Sel is TCastleTransform then
2644 DuplicateTransform(Sel as TCastleTransform)
2645 else
2646 if Sel is TCastleComponent then
2647 DuplicateNonVisualComponent(Sel as TCastleComponent)
2648 else
2649 ErrorBox('To duplicate, select TCastleUserInterface, TCastleTransform or TCastleComponent component');
2650 end else
2651 ErrorBox('To duplicate, select exactly one component that is not a subcomponent');
2652 end;
2653
2654 function TDesignFrame.SelectedViewport: TCastleViewport;
2655
2656 { Return viewport indicated by T, or @nil if none. }
2657 function ViewportOfTransform(const T: TCastleTransform): TCastleViewport;
2658 begin
2659 if T.World <> nil then
2660 Result := T.World.Owner as TCastleViewport
2661 else
2662 Result := nil;
2663 end;
2664
2665 { Return viewport indicated by B, or @nil if none. }
2666 function ViewportOfBehavior(const B: TCastleBehavior): TCastleViewport;
2667 begin
2668 if B.Parent <> nil then
2669 Result := ViewportOfTransform(B.Parent)
2670 else
2671 Result := nil;
2672 end;
2673
2674 { Return viewport indicated by C, or @nil if none. }
2675 function ViewportOfComponent(const C: TComponent): TCastleViewport;
2676 var
2677 ViewportChild: TCastleUserInterface;
2678 begin
2679 Result := nil;
2680
2681 if C is TCastleViewport then
2682 begin
2683 Result := C as TCastleViewport;
2684 end else
2685 if C is TCastleUserInterface then
2686 begin
2687 { When hovering over TCastleNavigation, or TCastleTouchNavigation,
2688 or really any UI as viewport child -> select viewport. }
2689 ViewportChild := C as TCastleUserInterface;
2690 if {ViewportChild.FullSize and} (ViewportChild.Parent is TCastleViewport) then
2691 begin
2692 Result := ViewportChild.Parent as TCastleViewport;
2693 end;
2694 end else
2695 if C is TCastleTransform then
2696 Result := ViewportOfTransform(C as TCastleTransform)
2697 else
2698 if C is TCastleBehavior then
2699 Result := ViewportOfBehavior(C as TCastleBehavior);
2700 end;
2701
2702 var
2703 Selected: TComponentList;
2704 SelectedCount, I: Integer;
2705 NewResult: TCastleViewport;
2706 begin
2707 Result := nil;
2708
2709 GetSelected(Selected, SelectedCount);
2710 try
2711 for I := 0 to SelectedCount - 1 do
2712 begin
2713 NewResult := ViewportOfComponent(Selected[I]);
2714
2715 if NewResult <> nil then
2716 begin
2717 if (Result <> nil) and (Result <> NewResult) then
2718 Exit(nil); // multiple viewports selected
2719 Result := NewResult;
2720 end;
2721 end;
2722 finally FreeAndNil(Selected) end;
2723 end;
2724
2725 procedure TDesignFrame.UIScaling(const UIScaling: TUIScaling;
2726 const UIReferenceWidth, UIReferenceHeight: Single);
2727 begin
2728 CastleControl.Container.UIScaling := UIScaling;
2729 CastleControl.Container.UIReferenceWidth := UIReferenceWidth;
2730 CastleControl.Container.UIReferenceHeight := UIReferenceHeight;
2731 end;
2732
2733 procedure TDesignFrame.CurrentComponentApiUrl(var Url: String);
2734
2735 function InspectorTypeFromActiveControl(const C: TWinControl;
2736 out InspectorType: TInspectorType): Boolean;
2737 begin
2738 for InspectorType in TInspectorType do
2739 if Inspector[InspectorType] = C then
2740 Exit(true);
2741
2742 if C.Parent <> nil then
2743 Exit(InspectorTypeFromActiveControl(C.Parent, InspectorType));
2744
2745 Result := false;
2746 end;
2747
2748 { If a property of the SelectedComponent is now focused
2749 in one of our object inspectors, return property name. }
2750 function SelectedProperty(out PropertyInstance: TObject;
2751 out PropertyName, PropertyNameForLink: String): Boolean;
2752 var
2753 ParentForm: TCustomForm;
2754 InspectorType: TInspectorType;
2755 ActiveRow: TOIPropertyGridRow;
2756 begin
2757 ParentForm := GetParentForm(Self);
2758 if (ParentForm.ActiveControl <> nil) and
2759 InspectorTypeFromActiveControl(ParentForm.ActiveControl, InspectorType) and
2760 (Inspector[InspectorType].GetActiveRow <> nil) then
2761 begin
2762 ActiveRow := Inspector[InspectorType].GetActiveRow;
2763 PropertyInstance := ActiveRow.Editor.GetComponent(0);
2764
2765 PropertyName := ActiveRow.Editor.GetPropInfo^.Name;
2766
2767 { Why do we need PropertyNameForLink, sometimes different than PropertyName?
2768
2769 Our TVectorXxxPersistent, TCastleColorPersistent property editors
2770 modify the GetName (returned by "ActiveRow.Name" here)
2771 to remove "Persistent" suffix.
2772 And in their case, we want to link to the version without "Persistent"
2773 suffix.
2774
2775 But we need to use the version with "Persistent" for GetPropInfo
2776 as only "XxxPersistent" is published and actually available using RTTI,
2777 so we also return real PropertyName.
2778
2779 For other properties (without "persistent" suffix)
2780 the PropertyNameForLink is equal to PropertyName.
2781 This way we avoid using weird names set by property editors, like "Angle W",
2782 for links. }
2783 if IsSuffix('persistent', PropertyName, true) then
2784 PropertyNameForLink := ActiveRow.Name
2785 else
2786 PropertyNameForLink := PropertyName;
2787 Result := true;
2788 end else
2789 Result := false;
2790 end;
2791
2792 function GetFirstSelected: TComponent;
2793 var
2794 Selected: TComponentList;
2795 SelectedCount: Integer;
2796 begin
2797 Result := SelectedComponent;
2798
2799 { In case multiple components are selected, try to return something non-nil:
2800 namely return the 1st component. This makes pressing F1 when a property is selected
2801 with multiple components sensible. They usually have equal class. }
2802 if Result = nil then
2803 begin
2804 GetSelected(Selected, SelectedCount);
2805 try
2806 if SelectedCount >= 1 then
2807 Result := Selected[0];
2808 finally FreeAndNil(Selected) end;
2809 end;
2810 end;
2811
2812 var
2813 C: TComponent;
2814 PropertyInstance: TObject;
2815 PropertyName, PropertyNameForLink: String;
2816 begin
2817 C := GetFirstSelected;
2818 if C <> nil then
2819 begin
2820 { We do not use C for PropertyInstance, because in case of property
2821 in SubComponent, PropertyInstance needs to be <> nil.
2822 For example if you click F1 when being over "Blending" inside
2823 TCastleScene.RenderOptions. }
2824 if SelectedProperty(PropertyInstance, PropertyName, PropertyNameForLink) then
2825 Url := ApiReference(PropertyInstance, PropertyName, PropertyNameForLink)
2826 else
2827 Url := ApiReference(C, '', '');
2828 end;
2829 end;
2830
2831 procedure TDesignFrame.UpdateCurrentViewport;
2832 var
2833 NewCurrentViewport: TCastleViewport;
2834 HoverUi: TCastleUserInterface;
2835 begin
2836 { try SelectedViewport }
2837 NewCurrentViewport := SelectedViewport;
2838
2839 if NewCurrentViewport = nil then
2840 begin
2841 { try HoverUserInterface as TCastleViewport }
2842 HoverUi := FDesignerLayer.HoverUserInterface(CastleControl.MousePosition, true);
2843 if HoverUi is TCastleViewport then // also checks HoverUi <> nil
2844 NewCurrentViewport := TCastleViewport(HoverUi)
2845 else
2846 { try HoverUserInterface as TCastleViewport child, like TCastleNavigation, TCastleTouchNavigation }
2847 if (HoverUi <> nil) and (HoverUi.Parent is TCastleViewport) then // also checks HoverUi.Parent <> nil
2848 NewCurrentViewport := TCastleViewport(HoverUi.Parent);
2849 end;
2850
2851 if NewCurrentViewport <> nil then
2852 SetCurrentViewport(NewCurrentViewport);
2853 { otherwise keep using FCurrentViewport we had so far }
2854 end;
2855
2856 procedure TDesignFrame.SetCurrentViewport(const Value: TCastleViewport);
2857 begin
2858 if FCurrentViewport <> Value then
2859 begin
2860 FCurrentViewport := Value;
2861 FCurrentViewportObserver.Observed := Value;
2862 { After changing CurrentViewport, show colliders on new viewport.
2863 TODO: It would be better if toggling this checkbox
2864 set them already properly on all viewports. }
2865 if Value <> nil then
2866 UpdateColliders;
2867 if Assigned(OnCurrentViewportChanged) then
2868 OnCurrentViewportChanged(Self);
2869 end;
2870 end;
2871
2872 procedure TDesignFrame.CurrentViewportFreeNotification(
2873 const Sender: TFreeNotificationObserver);
2874 begin
2875 FCurrentViewport := nil;
2876 if Assigned(OnCurrentViewportChanged) then
2877 OnCurrentViewportChanged(Self);
2878 end;
2879
2880 const
2881 CameraTransitionTime = 0.25;
2882
2883 procedure TDesignFrame.ViewportViewAxis(const Dir, Up: TVector3);
2884 var
2885 V: TCastleViewport;
2886 Box: TBox3D;
2887 Distance: Single;
2888 NewPos: TVector3;
2889 begin
2890 V := CurrentViewport;
2891 if V = nil then Exit;
2892 if V.Items = nil then Exit;
2893
2894 Box := V.Items.BoundingBox;
2895 if Box.IsEmpty then Exit;
2896
2897 Distance := PointsDistance(V.InternalCamera.WorldTranslation, Box.Center);
2898 NewPos := Box.Center - Dir * Distance;
2899 FixCamera2D(V, NewPos, Dir, Up);
2900 V.InternalCamera.AnimateTo(NewPos, Dir, Up, CameraTransitionTime);
2901 end;
2902
2903 procedure TDesignFrame.FixCamera2D(const V: TCastleViewport; var Pos: TVector3; const Dir, Up: TVector3);
2904 begin
2905 if (V.InternalCamera.ProjectionType = ptOrthographic) and
2906 TVector3.Equals(Dir, Vector3(0, 0, -1)) and
2907 TVector3.Equals(Up, Vector3(0, 1, 0)) then
2908 begin
2909 if V.Camera <> nil then
2910 Pos.Z := V.Camera.Translation.Z
2911 else
2912 Pos.Z := Default2DCameraZ;
2913
2914 Pos.X := Pos.X - (0.5 - V.InternalCamera.Orthographic.Origin.X) * V.InternalCamera.Orthographic.EffectiveRect.Width;
2915 Pos.Y := Pos.Y - (0.5 - V.InternalCamera.Orthographic.Origin.Y) * V.InternalCamera.Orthographic.EffectiveRect.Height;
2916 end;
2917 end;
2918
2919 procedure TDesignFrame.ViewportViewBox(const V: TCastleViewport; Box: TBox3D);
2920 var
2921 APos, ADir, AUp: TVector3;
2922 IntersectionDistance: Single;
2923 begin
2924 // in particular, condition below means we don't do anything if no TCastleTransform selected
2925 if not Box.IsEmpty then
2926 begin
2927 V.InternalCamera.GetWorldView(APos, ADir, AUp);
2928
2929 { Convert Box to use maximum size in all 3 dimensions.
2930 This results in better camera view for boxes mostly flat in 1 dimension. }
2931 Box := Box3DAroundPoint(Box.Center, Box.Size.Max);
2932 if not Box.TryRayClosestIntersection(IntersectionDistance, Box.Center, -ADir) then
2933 begin
2934 { TryRayClosestIntersection may return false for box with size zero
2935 (though not observed in practice),
2936 only then ray from Box.Center may not hit one of box walls. }
2937 IntersectionDistance := 1;
2938 WritelnWarning('Ray from box center didn''t hit any of box walls');
2939 end;
2940 APos := Box.Center - ADir * IntersectionDistance * 2;
2941
2942 { Older version of this routine was doing:
2943
2944 CameraViewpointForWholeScene(Box, 2, 1, false, true,
2945 APos, ADir, AUp, AGravityUp);
2946
2947 New version only modifies the camera position, preserving existing
2948 dir, up. This is more flexible for movement by key shortcuts,
2949 and consistent with
2950 - Blender home
2951 - Unity F
2952 - Godot O
2953 }
2954
2955 FixCamera2D(V, APos, ADir, AUp);
2956 V.InternalCamera.AnimateTo(APos, ADir, AUp, CameraTransitionTime);
2957 end;
2958 end;
2959
2960 procedure TDesignFrame.ViewportViewAll;
2961 var
2962 V: TCastleViewport;
2963 begin
2964 V := CurrentViewport;
2965 if V = nil then Exit;
2966
2967 if V.Items <> nil then
2968 ViewportViewBox(V, V.Items.BoundingBox);
2969 end;
2970
2971 procedure TDesignFrame.ViewportViewSelected;
2972
2973 { Determine selected TCastleTransform based on selected component, or @nil.
2974 This routine treats selecting a behavior just like selecting a transform,
2975 so that pressing F on behavior works. }
2976 function TransformFromSelected(const C: TComponent): TCastleTransform;
2977 begin
2978 if C is TCastleTransform then
2979 Result := TCastleTransform(C)
2980 else
2981 if C is TCastleBehavior then
2982 Result := TCastleBehavior(C).Parent
2983 else
2984 Result := nil;
2985 end;
2986
2987 var
2988 Selected: TComponentList;
2989 SelectedCount, I: Integer;
2990 SelectedBox: TBox3D;
2991 V: TCastleViewport;
2992 T: TCastleTransform;
2993 begin
2994 V := CurrentViewport;
2995 if V = nil then Exit;
2996
2997 SelectedBox := TBox3D.Empty;
2998
2999 GetSelected(Selected, SelectedCount);
3000 try
3001 for I := 0 to SelectedCount - 1 do
3002 begin
3003 T := TransformFromSelected(Selected[I]);
3004 if (T <> nil) and
3005 (T.World = V.Items) then
3006 SelectedBox := SelectedBox + T.WorldBoundingBox;
3007 end;
3008 finally FreeAndNil(Selected) end;
3009
3010 ViewportViewBox(V, SelectedBox);
3011 end;
3012
3013 function TDesignFrame.ComponentCaption(const C: TComponent): String;
3014
3015 function ClassCaption(const C: TClass): String;
3016 begin
3017 Result := C.ClassName;
3018
3019 // hide some internal classes by instead displaying ancestor name
3020 // No point in doing this now
3021 // if C = Txxx then
3022 // Result := ClassCaption(C.ClassParent);
3023 end;
3024
3025 begin
3026 Result := C.Name + ' (' + ClassCaption(C.ClassType) + ')';
3027 end;
3028
3029 function TDesignFrame.TreeNodeCaption(const C: TComponent): String;
3030 begin
3031 Result := C.Name;
3032 end;
3033
3034 procedure TDesignFrame.CastleControlResize(Sender: TObject);
3035 //var
3036 // CalculatedUIScale: Single;
3037 // H, CalculatedUIScaleStr: String;
3038 begin
3039 // TODO: where to display UI scaling effect nicely?
3040 {
3041 // trick to get private TCastleContainer.FCalculatedUIScale
3042 CalculatedUIScale := (1 / CastleControl.Container.UnscaledWidth) *
3043 CastleControl.Container.Width;
3044 CalculatedUIScaleStr := IntToStr(Round(CalculatedUIScale * 100)) + '%';
3045
3046 LabelUIScaling.Caption := CalculatedUIScaleStr;
3047 case CastleControl.Container.UIScaling of
3048 usNone : H := 'No user interface scaling';
3049 usEncloseReferenceSize: H := Format('User interface scaling in effect: window must enclose a reference size of %f x %f.' + NL,
3050 [CastleControl.Container.UIReferenceWidth,
3051 CastleControl.Container.UIReferenceHeight]);
3052 usEncloseReferenceSizeAutoOrientation:...
3053 usFitReferenceSize : H := Format('User interface scaling in effect: window must fit inside a reference size of %f x %f.' + NL,
3054 [CastleControl.Container.UIReferenceWidth,
3055 CastleControl.Container.UIReferenceHeight]);
3056 usExplicitScale : H := Format('User interface scaling in effect: explicit scale %f.' + NL,
3057 [CastleControl.Container.UIExplicitScale]);
3058 usDpiScale : H := Format('User interface scaling in effect: scale to follow DPI (pixels per inch). DPI detected now is %f.' + NL,
3059 [CastleControl.Container.Dpi]);
3060 else raise EInternalError.Create('CastleControl.Container.UIScaling?');
3061 end;
3062 if CastleControl.Container.UIScaling <> usNone then
3063 begin
3064 H := Format(H +
3065 'Actual window size is %d x %d.' + NL +
3066 'Calculated scale is %s, which simulates surface of size %f x %f.',
3067 [CastleControl.Container.Width,
3068 CastleControl.Container.Height,
3069 CalculatedUIScaleStr,
3070 CastleControl.Container.UnscaledWidth,
3071 CastleControl.Container.UnscaledHeight]);
3072 end;
3073 LabelUIScaling.Hint := H;
3074 }
3075 end;
3076
3077 procedure TDesignFrame.CastleControlOpen(Sender: TObject);
3078
3079 procedure ReadSettings;
3080 var
3081 SettingsUrl: String;
3082 begin
3083 SettingsUrl := 'castle-data:/CastleSettings.xml';
3084 if UriFileExists(SettingsUrl) then
3085 try
3086 CastleControl.Container.LoadSettings(SettingsUrl);
3087 except
3088 on E: Exception do
3089 begin
3090 { Showing a message box (using ErrorBox, which calls LCL MessageDlg)
3091 from CastleControl.OnOpen (after OpenGL context is initialized)
3092 is not reliable.
3093
3094 - WinAPI widgetset: works OK.
3095 - GTK widgetset: shows an empty message box (seems like the rendered text
3096 is invisible), and shows GTK error in the console
3097 (castle-editor:6999): Gtk-CRITICAL **: 21:23:50.518: IA__gtk_widget_realize: assertion 'GTK_WIDGET_ANCHORED (widget) || GTK_IS_INVISIBLE (widget)' failed
3098
3099 To workaround this, we set PendingErrorBox field here,
3100 instead of showing ErrorBox immediately.
3101 }
3102 PendingErrorBox := SAppendPart(PendingErrorBox, NL,
3103 'An error occurred when reading the CastleSettings.xml file in your project:' +
3104 NL + NL + ExceptMessage(E));
3105 { and continue, this way you can still open a project with broken
3106 CastleSettings.xml }
3107 end;
3108 end;
3109 end;
3110
3111 begin
3112 ReadSettings;
3113 end;
3114
3115 procedure TDesignFrame.CastleControlUpdate(Sender: TObject);
3116
3117 function ViewportDebugInfo(const V: TCastleViewport): String;
3118
3119 function CameraDirectionStr: String;
3120 begin
3121 { This detection matches TProjectForm.ActionViewport*Execute methods in CGE editor. }
3122 if TVector3.Equals(V.InternalCamera.Direction, Vector3(0, -1, 0)) then
3123 Result := 'Top '
3124 else
3125 if TVector3.Equals(V.InternalCamera.Direction, Vector3(0, 1, 0)) then
3126 Result := 'Bottom '
3127 else
3128 if TVector3.Equals(V.InternalCamera.Direction, Vector3(0, 0, -1)) then
3129 Result := 'Front '
3130 else
3131 if TVector3.Equals(V.InternalCamera.Direction, Vector3(0, 0, 1)) then
3132 Result := 'Back '
3133 else
3134 if TVector3.Equals(V.InternalCamera.Direction, Vector3(1, 0, 0)) then
3135 Result := 'Left '
3136 else
3137 if TVector3.Equals(V.InternalCamera.Direction, Vector3(-1, 0, 0)) then
3138 Result := 'Right '
3139 else
3140 Result := '';
3141 end;
3142
3143 function ProjectionStr: String;
3144 begin
3145 Result := ProjectionTypeToStr(V.InternalCamera.ProjectionType);
3146 end;
3147
3148 function DesignNavigationStr: String;
3149 const
3150 Names: array [TInternalDesignNavigationType] of String = ('Fly', 'Examine', '2D');
3151 begin
3152 if not V.InternalDesignManipulation then
3153 begin
3154 WritelnWarning('Viewport not in design mode, but selected (submit a bug): %s', [V.Name]);
3155 Exit;
3156 end;
3157 Result := Names[V.InternalDesignNavigationType];
3158 { // speed is now shown using a label displayed by TCastleWalkNavigationDesign
3159 if V.InternalDesignNavigationType = dnFly then
3160 Result := Result + Format(' (speed %f)', [
3161 (V.InternalDesignNavigation as TCastleWalkNavigation).MoveSpeed
3162 ]);
3163 }
3164 end;
3165
3166 begin
3167 Result := V.Name + ': ' + CameraDirectionStr + ProjectionStr + ' ' + NL +
3168 DesignNavigationStr;
3169 end;
3170
3171 (*
3172 Unused debug routine to dump current selection of ControlsTree,
3173 derived from various properties.
3174
3175 procedure DebugControlsTreeSelection;
3176 var
3177 S: String;
3178 I: Integer;
3179 begin
3180 S := '';
3181
3182 if ControlsTree.Selected <> nil then
3183 S := S + 'Selected non-nil: ' + ControlsTree.Selected.Text + LineEnding
3184 else
3185 S := S + 'Selected nil' + LineEnding;
3186
3187 if ControlsTreeOneSelected <> nil then
3188 S := S + 'OneSelected non-nil: ' + ControlsTreeOneSelected.Text + LineEnding
3189 else
3190 S := S + 'OneSelected nil' + LineEnding;
3191
3192 S := S + 'SelectionCount: ' + IntToStr(ControlsTree.SelectionCount) + LineEnding;
3193
3194 for I := 0 to ControlsTree.SelectionCount - 1 do
3195 S := S + IntToStr(I) + ': ' + ControlsTree.Selections[I].Text + LineEnding;
3196
3197 LabelTreeDEbug.Caption := S;
3198 end;
3199 *)
3200
3201 var
3202 SavedErrorBox: String;
3203 begin
3204 { process PendingErrorBox }
3205 if PendingErrorBox <> '' then
3206 begin
3207 SavedErrorBox := PendingErrorBox;
3208 { Clear PendingErrorBox *before* doing ErrorBox, as on WinAPI,
3209 the CastleControlUpdate will keep occurring underneath the box,
3210 and we would spawn ~infinite number of ErrorBox.
3211 This can happen e.g. in case of invalid CastleSettings.xml file,
3212 that sets PendingErrorBox. }
3213 PendingErrorBox := '';
3214 ErrorBox(SavedErrorBox);
3215 end;
3216
3217 if InternalCastleDesignInvalidate then
3218 begin
3219 UpdateDesign;
3220 //WritelnWarning('CGE needed to explicitly tell editor to refresh hierarchy');
3221 ModifiedOutsideObjectInspector('', ucLow);
3222 end;
3223
3224 { Hide some tabs if they don't contain anything. }
3225 TabLayout.TabVisible :=
3226 (Inspector[itLayout].RowCount <> 0) or
3227 PanelLayoutTransform.Visible or
3228 PanelAnchors.Visible;
3229 TabEvents.TabVisible :=
3230 (Inspector[itEvents].RowCount <> 0);
3231
3232 { If necessary, reset OverrideCursor modified by UpdateCursor, to allow mouse look to hide cursor }
3233 if InternalDesignMouseLook then
3234 CastleControl.Container.OverrideCursor := mcDefault;
3235
3236 UpdateCurrentViewport;
3237
3238 LabelViewport.Visible := FCurrentViewport <> nil;
3239 if FCurrentViewport <> nil then
3240 LabelViewport.Caption := ViewportDebugInfo(FCurrentViewport);
3241
3242 FDesignerLayer.LayerPhysicsSimulation.Exists := CastleApplicationMode in [appSimulation, appSimulationPaused];
3243 FDesignerLayer.LabelPhysicsSimulationRunning.Exists := CastleApplicationMode = appSimulation;
3244 FDesignerLayer.LabelPhysicsSimulationPaused.Exists := CastleApplicationMode = appSimulationPaused;
3245 end;
3246
3247 procedure TDesignFrame.CastleControlDragOver(Sender, Source: TObject; X,
3248 Y: Integer; State: TDragState; var Accept: Boolean);
3249 var
3250 SourceShellList: TCastleShellListView;
3251 UI: TCastleUserInterface;
3252 ParentComponent: TComponent;
3253 begin
3254 Accept := false;
3255 if Source is TCastleShellListView then
3256 begin
3257 SourceShellList := TCastleShellListView(Source);
3258 UI := FDesignerLayer.HoverUserInterface(Vector2(X, CastleControl.Height - Y));
3259 if (UI is TCastleViewport) and not (ssShift in GetKeyShiftState) then
3260 ParentComponent := TCastleViewport(UI).Items
3261 else
3262 ParentComponent := UI;
3263 if ParentComponent = nil then // may happen because UI was nil
3264 Exit;
3265
3266 Accept := ShellListComponentClass(SourceShellList, ParentComponent) <> nil;
3267 end;
3268 end;
3269
3270 procedure TDesignFrame.CastleControlDragDrop(Sender, Source: TObject; X, Y: Integer);
3271
3272 { Calculate 3D position of a TCastleTransform created by drag-and-drop on a vieport. }
3273 function DropPosition(const Viewport: TCastleViewport; out DropPos: TVector3): Boolean;
3274 var
3275 RayOrigin, RayDirection: TVector3;
3276 RayHit: TRayCollision;
3277 Distance: Single;
3278 OldPickable: Boolean;
3279 PlaneZ: Single;
3280 Cam: TCastleCamera;
3281 begin
3282 Result := true;
3283
3284 Cam := Viewport.InternalCamera;
3285 if Cam = nil then
3286 begin
3287 WritelnWarning('Cannot drop on the viewport %s, as it has no camera (not even a design-time camera)', [
3288 Viewport.Name
3289 ]);
3290 Exit(false);
3291 end;
3292
3293 { Make gizmos not pickable when looking for new scene position,
3294 because ray can hit on gizmo. }
3295 OldPickable := VisualizeTransformSelected.Pickable;
3296 try
3297 VisualizeTransformSelected.Pickable := false;
3298 Viewport.PositionToRay(Vector2(X, CastleControl.Height - Y), true, RayOrigin, RayDirection);
3299 RayHit := Viewport.Items.WorldRay(RayOrigin, RayDirection);
3300 finally
3301 VisualizeTransformSelected.Pickable := OldPickable;
3302 end;
3303
3304 if (RayHit = nil) and (Cam.ProjectionType = ptOrthographic) then
3305 begin
3306 { In the past, we used to calculate this as
3307 "(Cam.EffectiveProjectionNear + Cam.EffectiveProjectionFar) / 2".
3308
3309 But now that we auto-calculate projection, the above "smart" calculation is
3310 - unnecessary (projection will adjust to new item)
3311 - often results in weird values (as projection near/far are often "around zero"
3312 but usually their average is not exactly zero, as users expect zero).
3313 }
3314 PlaneZ := 0;
3315 if not TrySimplePlaneRayIntersection(DropPos, 2, PlaneZ, RayOrigin, RayDirection) then
3316 Exit(false); // camera direction parallel to 3D plane with Z = constant
3317 end else
3318 begin
3319 if RayHit <> nil then
3320 begin
3321 Distance := RayHit.Distance;
3322 FreeAndNil(RayHit);
3323 end else
3324 begin
3325 { If we don't hit any other scene set Distance to default value. }
3326 Distance := 10;
3327 end;
3328 DropPos := RayOrigin + (RayDirection * Distance);
3329
3330 { In case of 2D game move scene a little closser to camera }
3331 if Cam.ProjectionType = ptOrthographic then
3332 DropPos := DropPos - Cam.Direction;
3333 end;
3334 end;
3335
3336 var
3337 SourceShellList: TCastleShellListView;
3338 ParentComponent, NewComponent: TComponent;
3339 NewComponentClass: TComponentClass;
3340 UI: TCastleUserInterface;
3341 Viewport: TCastleViewport;
3342 DropPosition2D: TVector2;
3343 DropPos: TVector3;
3344 Transform: TCastleTransform;
3345 begin
3346 if Source is TCastleShellListView then
3347 begin
3348 SourceShellList := TCastleShellListView(Source);
3349 DropPosition2D := Vector2(X, CastleControl.Height - Y);
3350
3351 { calculate ParentComponent and UI }
3352 if DesignRoot is TCastleTransform then
3353 begin
3354 { When we edit .castle-transform design, then the parent to drop must be DesignRoot.
3355 Not the Viewport, not even Viewport.Items -- only things inside DesignRoot
3356 are the hierarchy edited by user. }
3357 ParentComponent := DesignRoot;
3358 Assert(FDesignViewportForTransforms <> nil);
3359 UI := FDesignViewportForTransforms;
3360 end else
3361 begin
3362 UI := FDesignerLayer.HoverUserInterface(DropPosition2D);
3363 if (UI is TCastleViewport) and not (ssShift in GetKeyShiftState) then
3364 ParentComponent := TCastleViewport(UI).Items
3365 else
3366 ParentComponent := UI;
3367 end;
3368
3369 if ParentComponent = nil then // may happen because UI was nil
3370 Exit;
3371
3372 NewComponentClass := ShellListComponentClass(SourceShellList, ParentComponent);
3373 if NewComponentClass = nil then
3374 Exit;
3375
3376 if NewComponentClass.InheritsFrom(TCastleTransform) then
3377 begin
3378 if not (UI is TCastleViewport) then
3379 begin
3380 WritelnWarning('Cannot drag-and-drop %s on UI %s', [
3381 NewComponentClass.ClassName,
3382 UI.ClassName
3383 ]);
3384 Exit;
3385 end;
3386 Viewport := TCastleViewport(UI);
3387
3388 if not DropPosition(Viewport, DropPos) then
3389 begin
3390 WritelnWarning('Cannot drag-and-drop %s on viewport, cannot determine drop position', [
3391 NewComponentClass.ClassName
3392 ]);
3393 Exit;
3394 end;
3395
3396 { We can assume that ShellListAddComponent creates non-nil,
3397 and TCastleTransform, because ShellListComponentClass
3398 returned non-nil TCastleTransform descendant. }
3399 Transform := ShellListAddComponent(SourceShellList, ParentComponent) as TCastleTransform;
3400 Transform.Translation := DropPos;
3401 WritelnLog('Dropped transform %s:%s into viewport %s at translation %s', [
3402 Transform.Name,
3403 Transform.ClassName,
3404 Viewport.Name,
3405 DropPos.ToString
3406 ]);
3407 end else
3408 if NewComponentClass.InheritsFrom(TCastleUserInterface) then
3409 begin
3410 NewComponent := ShellListAddComponent(SourceShellList, ParentComponent);
3411 if (NewComponent is TCastleUserInterface) and
3412 (ParentComponent is TCastleUserInterface) then
3413 begin
3414 TCastleUserInterface(NewComponent).Translation :=
3415 TCastleUserInterface(ParentComponent).ContainerToLocalPosition(DropPosition2D, true);
3416 end;
3417 end else
3418 begin
3419 WritelnWarning('Cannot drag-and-drop %s on UI %s', [
3420 NewComponentClass.ClassName,
3421 UI.ClassName
3422 ]);
3423 end;
3424 end;
3425 end;
3426
3427 const
3428 LoadUiDesign_FileFilters = 'CGE User Interace Design (*.castle-user-interface)|*.castle-user-interface';
3429 LoadTransformDesign_FileFilters = 'CGE Transform Design (*.castle-transform)|*.castle-transform';
3430
3431 function TDesignFrame.ShellListComponentClass(const SourceShellList: TCastleShellListView;
3432 const ParentComponent: TComponent): TComponentClass;
3433 var
3434 SelectedFileName: String;
3435 SelectedUrl: String;
3436 PreferTransform: Boolean;
3437 begin
3438 Result := nil;
3439 PreferTransform := ParentComponent is TCastleTransform;
3440
3441 { SourceShellList.Selected may be nil, testcase:
3442 - open any project (empty from template is OK)
3443 - create new design using menu item
3444 (looks like this step is necessary into tricking LCL that we're
3445 in the middle of drag-and-drop on GTK?)
3446 - double-click on some design file in data/ by double-clicking
3447 - mouse over the design -> without this check, would have access violation
3448 due to TDesignFrame.CastleControlDragOver being called with
3449 ShellList.Selected = nil. }
3450
3451 if SourceShellList.Selected <> nil then
3452 begin
3453 SelectedFileName := SourceShellList.GetPathFromItem(SourceShellList.Selected);
3454 SelectedUrl := MaybeUseDataProtocol(FilenameToUriSafe(SelectedFileName));
3455
3456 if LoadImage_FileFilters.Matches(SelectedUrl) then
3457 begin
3458 if PreferTransform then
3459 Result := TCastleImageTransform
3460 else
3461 Result := TCastleImageControl;
3462 end else
3463 // check LoadTiledMap_FileFilters before LoadScene_FileFilters, since *.tmx matches both
3464 if TFileFilterList.Matches(LoadTiledMap_FileFilters, SelectedUrl) then
3465 Result := TCastleTiledMap
3466 else
3467 if TFileFilterList.Matches(LoadScene_FileFilters, SelectedUrl) then
3468 Result := TCastleScene
3469 else
3470 if TFileFilterList.Matches(LoadSound_FileFilters, SelectedUrl) then
3471 Result := TCastleTransform // ShellListAddComponent creates TCastleTransform with TCastleSoundSource behavior
3472 else
3473 if TFileFilterList.Matches(LoadUiDesign_FileFilters, SelectedUrl) then
3474 Result := TCastleDesign
3475 else
3476 if TFileFilterList.Matches(LoadTransformDesign_FileFilters, SelectedUrl) then
3477 Result := TCastleTransformDesign;
3478 end;
3479 end;
3480
3481 function TDesignFrame.ShellListAddComponent(const SourceShellList: TCastleShellListView;
3482 const ParentComponent: TComponent): TComponent;
3483 var
3484 SelectedFileName, SelectedUrl: String;
3485 begin
3486 Result := nil;
3487 if SourceShellList.Selected <> nil then
3488 begin
3489 SelectedFileName := SourceShellList.GetPathFromItem(SourceShellList.Selected);
3490 SelectedUrl := MaybeUseDataProtocol(FilenameToUriSafe(SelectedFileName));
3491 Result := AddComponentFromUrl(SelectedUrl, ParentComponent);
3492 end;
3493 end;
3494
3495 function TDesignFrame.AddComponentFromUrl(const AddUrl: String;
3496 const ParentComponent: TComponent): TComponent;
3497 var
3498 BaseNameFromUrl: String;
3499
3500 function AddImageTransform(const Url: String): TCastleImageTransform;
3501 begin
3502 Result := AddComponent(ParentComponent, TCastleImageTransform, nil,
3503 'Image' + BaseNameFromUrl) as TCastleImageTransform;
3504 Result.Url := Url;
3505 end;
3506
3507 function AddImageControl(const Url: String): TCastleImageControl;
3508 begin
3509 Result := AddComponent(ParentComponent, TCastleImageControl, nil,
3510 'Image' + BaseNameFromUrl) as TCastleImageControl;
3511 Result.Url := Url;
3512 end;
3513
3514 function AddScene(const Url: String): TCastleScene;
3515 begin
3516 Result := AddComponent(ParentComponent, TCastleScene, nil,
3517 'Scene' + BaseNameFromUrl) as TCastleScene;
3518 Result.Url := Url;
3519 end;
3520
3521 function AddTiledMap(const Url: String): TCastleTiledMap;
3522 begin
3523 Result := AddComponent(ParentComponent, TCastleTiledMap, nil,
3524 'TiledMap' + BaseNameFromUrl) as TCastleTiledMap;
3525 Result.Url := Url;
3526 end;
3527
3528 function AddSound(const Url: String): TCastleTransform;
3529 var
3530 SoundSource: TCastleSoundSource;
3531 Sound: TCastleSound;
3532 begin
3533 Result := AddComponent(ParentComponent, TCastleTransform, nil,
3534 'Transform' + BaseNameFromUrl) as TCastleTransform;
3535 SoundSource := AddComponent(Result, TCastleSoundSource, nil,
3536 'SoundSource' + BaseNameFromUrl) as TCastleSoundSource;
3537 Sound := AddComponent(SoundSource, TCastleSound, nil,
3538 'Sound' + BaseNameFromUrl) as TCastleSound;
3539 Sound.Url := Url;
3540 SoundSource.Sound := Sound;
3541 end;
3542
3543 function AddUiDesign(const Url: String): TCastleDesign;
3544 begin
3545 Result := AddComponent(ParentComponent, TCastleDesign, nil,
3546 'Design' + BaseNameFromUrl) as TCastleDesign;
3547 Result.Url := Url;
3548 end;
3549
3550 function AddTransformDesign(const Url: String): TCastleTransformDesign;
3551 begin
3552 Result := AddComponent(ParentComponent, TCastleTransformDesign, nil,
3553 'Design' + BaseNameFromUrl) as TCastleTransformDesign;
3554 Result.Url := Url;
3555 end;
3556
3557 var
3558 PreferTransform: Boolean;
3559 begin
3560 Result := nil;
3561 PreferTransform := ParentComponent is TCastleTransform;
3562 BaseNameFromUrl := GetBaseNameFromUrl(AddUrl);
3563 if LoadImage_FileFilters.Matches(AddUrl) then
3564 begin
3565 if PreferTransform then
3566 Result := AddImageTransform(AddUrl)
3567 else
3568 Result := AddImageControl(AddUrl);
3569 end else
3570 if TFileFilterList.Matches(LoadTiledMap_FileFilters, AddUrl) then
3571 Result := AddTiledMap(AddUrl)
3572 else
3573 if TFileFilterList.Matches(LoadScene_FileFilters, AddUrl) then
3574 Result := AddScene(AddUrl)
3575 else
3576 if TFileFilterList.Matches(LoadSound_FileFilters, AddUrl) then
3577 Result := AddSound(AddUrl)
3578 else
3579 if TFileFilterList.Matches(LoadUiDesign_FileFilters, AddUrl) then
3580 Result := AddUiDesign(AddUrl)
3581 else
3582 if TFileFilterList.Matches(LoadTransformDesign_FileFilters, AddUrl) then
3583 Result := AddTransformDesign(AddUrl);
3584
3585 { Warn if URL file, which can happen if you drag-and-drop from
3586 e.g. project top-level instead of "data".
3587 This is likely a mistake, and want to communicate to user why. }
3588 if (Result <> nil) and
3589 (UriProtocol(AddUrl) = 'file') then
3590 WarningBox(Format('Added component has URL pointing to a local filename: "%s".' + NL +
3591 NL +
3592 'This will likely not work when you open the project on another computer.' + NL +
3593 NL +
3594 'We advise to instead place all data files in "data" subdirectory and reference them using "castle-data:/" URLs.', [
3595 AddUrl
3596 ]
3597 ));
3598 end;
3599
3600 function TDesignFrame.AddImported(const AddUrl: String): TComponent;
3601 var
3602 ParentComponent: TComponent;
3603 begin
3604 ParentComponent := SelectedComponent;
3605
3606 { If AddUrl makes sense only with parent being TCastleTransform,
3607 try to use CurrentViewport.Items as parent.
3608 This way we "try harder" to find a parent that allows to drop
3609 given item. }
3610 if (not (ParentComponent is TCastleTransform)) and
3611 (CurrentViewport <> nil) and
3612 (
3613 // AddUrl can only be loaded to TCastleScene?
3614 ( TFileFilterList.Matches(LoadScene_FileFilters, AddUrl) and
3615 (not LoadImage_FileFilters.Matches(AddUrl)) ) or
3616 // AddUrl can only be loaded to TCastleTransformDesign?
3617 (TFileFilterList.Matches(LoadTransformDesign_FileFilters, AddUrl))
3618 ) then
3619 ParentComponent := CurrentViewport.Items;
3620
3621 if ParentComponent = nil then
3622 raise Exception.CreateFmt('Cannot add imported component "%s".' + NL + NL + 'First select a valid parent in the design, usually a TCastleViewport or TCastleTransform.', [
3623 UriDisplay(AddUrl)
3624 ]);
3625
3626 Result := AddComponentFromUrl(AddUrl, ParentComponent);
3627 end;
3628
3629 procedure TDesignFrame.SetShowColliders(const AValue: Boolean);
3630 begin
3631 if FShowColliders <> AValue then
3632 begin
3633 FShowColliders := AValue;
3634 UpdateColliders;
3635 end;
3636 end;
3637
3638 procedure TDesignFrame.MenuItemChangeClassClick(Sender: TObject);
3639 var
3640 NewDesignOwner, NewDesignRoot, Sel: TComponent;
3641 LoadInfo: TInternalComponentLoadInfo;
3642 R: TRegisteredComponent;
3643 SavedSelection: TSavedSelection;
3644 begin
3645 Sel := SelectedComponent;
3646 Assert(Sel <> nil); // menu item should be disabled otherwise
3647
3648 R := TRegisteredComponent(Pointer((Sender as TComponent).Tag));
3649
3650 if Sel.ClassType = R.ComponentClass then
3651 begin
3652 ErrorBox(Format('Component "%s" already has class "%s", no change is necessary.', [
3653 Sel.Name,
3654 Sel.ClassName
3655 ]));
3656 Exit;
3657 end;
3658
3659 if YesNoBox('Change Component Class',
3660 Format('Changing component class is a potentially dangerous operation. All the properties you set in the current class that don''t exist in new class will be simply discarded.' + NL +
3661 NL +
3662 'Are you sure you want to change class of component "%s" from "%s" to "%s"?', [
3663 Sel.Name,
3664 Sel.ClassName,
3665 R.ComponentClass.ClassName
3666 ])) then
3667 begin
3668 SavedSelection := GetSavedSelection;
3669
3670 LoadInfo := TInternalComponentLoadInfo.Create;
3671 try
3672 LoadInfo.ChangeClassName := Sel.Name;
3673 LoadInfo.ChangeClassClass := R.ComponentClass;
3674
3675 { To change class, we reload whole design, this way
3676 all references to Sel.Name will remain correct. }
3677
3678 NewDesignOwner := TComponent.Create(Self);
3679 NewDesignRoot := InternalStringToComponent(ComponentToString(DesignRoot), NewDesignOwner, LoadInfo);
3680 OpenDesign(NewDesignRoot, NewDesignOwner, FDesignUrl);
3681 finally FreeAndNil(LoadInfo) end;
3682
3683 RestoreSavedSelection(SavedSelection);
3684
3685 { We use ucHigh, otherwise when changing light source type
3686 we'd have older comment "Change OlderComponentName".
3687 Note: We still need this ModifiedOutsideObjectInspector call,
3688 otherwise change "Change OlderComponentName" doesn't happen and there's
3689 no undo / no modified flag after this operation. }
3690 ModifiedOutsideObjectInspector('Change Class To ' + R.ComponentClass.ClassName, ucHigh);
3691 end;
3692 end;
3693
3694 procedure TDesignFrame.InspectorFilter(const Sender: TObject;
3695 const AEditor: TPropertyEditor; var AShow: Boolean;
3696 const FilterBySection: Boolean; const Section: TPropertySection);
3697 var
3698 PropertyName: String;
3699 Instance: TPersistent;
3700 begin
3701 AShow := false;
3702
3703 if AEditor.GetPropInfo = nil then
3704 Exit;
3705
3706 PropertyName := AEditor.GetPropInfo^.Name;
3707
3708 if (AEditor.GetInstProp <> nil) and
3709 (AEditor.GetInstProp^.Instance <> nil) then
3710 begin
3711 Instance := AEditor.GetInstProp^.Instance;
3712 if Instance is TComponent then
3713 begin
3714 { Early exit: never show Name on components not owned by DesignOwner.
3715 Such components are subcomponents of something,
3716 like Camera.Perspective, and their Name is
3717 - shown weird (with dot, like 'Camera1.Perspective')
3718 - not useful to edit (we don't really want to allow editing it,
3719 you cannot search for such component later with DesignedComponent
3720 anyway, and the name must be unique within the owner -- better
3721 to leave it unedited) }
3722 if (PropertyName = 'Name') and
3723 (not RenamePossible(TComponent(Instance))) then
3724 Exit;
3725
3726 { Hide editing transformation of TCastleAbstractRootTransform,
3727 as it makes very unintuitive behavior because desing-time camera is also
3728 a child of it, so e.g. moving Viewport.Items seems to do nothing
3729 (TODO: but it breaks how mouse look works -- it should not;
3730 but still we'd hide these properties anyway, even once we fix mouse look
3731 in this case). }
3732 if (Instance is TCastleAbstractRootTransform) and
3733 ( (PropertyName = 'CenterPersistent') or
3734 (PropertyName = 'ScaleOrientationPersistent') or
3735 (PropertyName = 'RotationPersistent') or
3736 (PropertyName = 'ScalePersistent') or
3737 (PropertyName = 'TranslationPersistent') or
3738 (PropertyName = 'DirectionPersistent') or
3739 (PropertyName = 'UpPersistent')
3740 ) then
3741 Exit;
3742
3743 if FilterBySection and (Instance is TCastleComponent) then
3744 begin
3745 AShow := Section in TCastleComponent(Instance).PropertySections(PropertyName);
3746 end else
3747 begin
3748 AShow := true;
3749 end;
3750 end else
3751 begin
3752 { Show=true when Instance is some non-TComponent class used for subcomponents,
3753 like TBorder, TCastleImagePersistent... }
3754 AShow := true;
3755 end;
3756 end;
3757 end;
3758
3759 procedure TDesignFrame.GizmoHasModifiedParent(Sender: TObject);
3760 begin
3761 { Same comment as in Apply Drag:
3762 UndoOnRelease = true here means that we don't record the actual undo
3763 but defer it to GizmoStopDrag event }
3764 ModifiedOutsideObjectInspector('', ucLow, true); // UndoComment doesn't matter here
3765 end;
3766
3767 procedure TDesignFrame.GizmoStopDrag(Sender: TObject);
3768 begin
3769 if UndoSystem.ScheduleRecordUndoOnRelease then
3770 RecordUndo('Transform ' + (Sender as TVisualizeTransformSelected).Parent.Name +
3771 ' with Gizmo', ucHigh);
3772 end;
3773
3774 procedure TDesignFrame.InspectorBasicFilter(Sender: TObject;
3775 AEditor: TPropertyEditor; var aShow: Boolean);
3776 begin
3777 InspectorFilter(Sender, AEditor, AShow, true, psBasic);
3778 end;
3779
3780 procedure TDesignFrame.InspectorLayoutFilter(Sender: TObject;
3781 AEditor: TPropertyEditor; var aShow: Boolean);
3782 begin
3783 InspectorFilter(Sender, AEditor, AShow, true, psLayout);
3784 end;
3785
3786 procedure TDesignFrame.InspectorAllFilter(Sender: TObject;
3787 AEditor: TPropertyEditor; var aShow: Boolean);
3788 begin
3789 InspectorFilter(Sender, AEditor, AShow, false, {Section doesn't matter here}psBasic);
3790 end;
3791
3792 function TDesignFrame.UndoMessageModified(const Sel: TPersistent;
3793 const ModifiedProperty, ModifiedValue: String; const SelectedCount: Integer): String;
3794 const
3795 { Unreadable chars are defined like in SReplaceChars.
3796 Note they include newlines, we don't want to include newlines in undo description,
3797 as it would make menu item look weird (actually multiline on GTK2). }
3798 UnreadableChars = [Low(AnsiChar) .. Pred(' '), #128 .. High(AnsiChar)];
3799 var
3800 ToValue: String;
3801 begin
3802 if (Length(ModifiedValue) < 24) and (CharsPos(UnreadableChars, ModifiedValue) = 0) then
3803 ToValue := ' to ' + ModifiedValue
3804 else
3805 ToValue := '';
3806
3807 { Right now, when SelectedCount = 1 then we know that Sel <> nil
3808 (but it is better to not depend on it).
3809 But it may not be TComponent, in case when changing property like X
3810 of TCastleVector3Persistent. }
3811 if (SelectedCount = 1) and
3812 (Sel is TComponent) then
3813 Result := 'Change ' + TComponent(Sel).Name + '.' + ModifiedProperty + ToValue
3814 else
3815 if SelectedCount > 1 then
3816 Result := 'Change ' + ModifiedProperty + ToValue + ' in multiple components'
3817 else
3818 Result := 'Change ' + ModifiedProperty + ToValue;
3819 end;
3820
3821 procedure TDesignFrame.PropertyGridModified(Sender: TObject);
3822
3823 { Do a subset of work that UpdateSelectedControl also does:
3824 update UI to reflect the current state of selected object,
3825 when the properties of the selected object possibly changed
3826 (but the selected object stays the same -- otherwise
3827 UpdateSelectedControl would do the full job.)
3828
3829 It also updates ControlsTree,
3830 in case you changed the TComponent.Name. }
3831 procedure UpdateSelectedControlModified;
3832 var
3833 Sel: TComponent;
3834 SelUI: TCastleUserInterface;
3835 SelNode: TTreeNode;
3836 begin
3837 // This checks we have selected *exactly one* component.
3838 Sel := SelectedComponent;
3839
3840 if Sel <> nil then
3841 begin
3842 // update also LabelControlSelected
3843 LabelControlSelected.Caption := 'Selected:' + NL + ComponentCaption(Sel);
3844
3845 if Sel is TCastleUserInterface then
3846 begin
3847 SelUI := Sel as TCastleUserInterface;
3848 UpdateAnchors(SelUI, true);
3849 end;
3850
3851 { Note that we use TreeNodeMap to find SelNode,
3852 not just assume that SelNode := ControlsTree.Selected.
3853 That is because in case of special tree items "Behaviors" or "Non-Visual Components",
3854 the ControlsTree.Selected could be different. }
3855 if TreeNodeMap.TryGetValue(Sel, SelNode) then
3856 SelNode.Text := TreeNodeCaption(Sel);
3857 end;
3858
3859 UpdateSelectedInfo;
3860 end;
3861
3862 procedure DoRecordUndo;
3863 var
3864 Selected: TComponentList;
3865 Sel: TComponent;
3866 SelectedCount: Integer;
3867 begin
3868 GetSelected(Selected, SelectedCount);
3869 try
3870 if SelectedCount = 0 then
3871 begin
3872 // Something has changed, but we don't know what exactly. Let's rebuild everything to be safe.
3873 UpdateDesign;
3874 RecordUndo('', ucLow); // We're recording a generic Undo message
3875 end else
3876 begin
3877 if SelectedCount = 1 then
3878 Sel := Selected[0]
3879 else
3880 Sel := nil;
3881
3882 if Sender is TOICustomPropertyGrid then
3883 begin
3884 RecordUndo(
3885 UndoMessageModified(Sel, TOICustomPropertyGrid(Sender).GetActiveRow.Name,
3886 TOICustomPropertyGrid(Sender).CurrentEditValue, SelectedCount),
3887 ucHigh);
3888 end else
3889 { Sender is nil when PropertyGridModified is called
3890 by ModifiedOutsideObjectInspector. }
3891 if Sel <> nil then // so SelectedCount = 1
3892 RecordUndo('Change ' + Sel.Name, ucLow)
3893 else
3894 begin
3895 // we handled SelectedCount = 0 or 1 above
3896 Assert(SelectedCount > 1);
3897 RecordUndo('Change multiple components', ucLow)
3898 end;
3899 end;
3900 finally FreeAndNil(Selected) end;
3901 end;
3902
3903 begin
3904 UpdateSelectedControlModified;
3905
3906 { When UndoSystem.ScheduleRecordUndoOnRelease we ignore changes,
3907 otherwise we would record an undo for every OnMotion of dragging. }
3908 if not UndoSystem.ScheduleRecordUndoOnRelease then
3909 DoRecordUndo;
3910
3911 MarkModified;
3912 end;
3913
3914 procedure TDesignFrame.PropertyEditorModified(Sender: TObject);
3915
3916 { Call Invalidate on all Object Inspectors.
3917 This way editing a single property (like X to 10 of TCastleTransform.Translation)
3918 and pressing Enter immediately updates the vector value of it too
3919 (so it shows e.g. "0 0 10"). }
3920 procedure InvalidateInspectors;
3921 var
3922 It: TInspectorType;
3923 begin
3924 for It in TInspectorType do
3925 Inspector[It].Invalidate;
3926 end;
3927
3928 var
3929 Sel: TPersistent;
3930 begin
3931 InvalidateInspectors;
3932
3933 if Sender is TPropertyEditor then
3934 begin
3935 if TPropertyEditor(Sender).PropCount = 1 then
3936 Sel := TPropertyEditor(Sender).GetComponent(0)
3937 else
3938 Sel := nil;
3939 RecordUndo(
3940 UndoMessageModified(Sel, TPropertyEditor(Sender).GetName,
3941 TPropertyEditor(Sender).GetValue, TPropertyEditor(Sender).PropCount),
3942 ucHigh);
3943
3944 { Need to set modified flag.
3945 PropertyGridModified also does this, but not everything causes PropertyGridModified,
3946 e.g. setting URL property (done by TPropertyEditor.SetStrValue that calls
3947 TPropertyEditor.Modified) only results in PropertyEditorModified call. }
3948 MarkModified;
3949 end else
3950 raise EInternalError.Create('PropertyEditorModified can only be called with TPropertyEditor as a Sender.');
3951 end;
3952
3953 procedure TDesignFrame.PropertyGridCollectionItemClick(Sender: TObject);
3954 var
3955 SelectionForOI: TPersistentSelectionList;
3956 InspectorType: TInspectorType;
3957 Ed: TCollectionPropertyEditorForm;
3958 ListBox: TListBox;
3959 begin
3960 SelectionForOI := TPersistentSelectionList.Create;
3961 try
3962 ListBox := Sender as TListBox;
3963 if ListBox.ItemIndex >= 0 then
3964 begin
3965 Ed := ListBox.Parent as TCollectionPropertyEditorForm;
3966 SelectionForOI.Add(Ed.Collection.Items[ListBox.ItemIndex]);
3967 for InspectorType in TInspectorType do
3968 Inspector[InspectorType].Selection := SelectionForOI;
3969 end;
3970 finally FreeAndNil(SelectionForOI) end;
3971 end;
3972
3973 procedure TDesignFrame.PropertyGridCollectionItemClose(Sender: TObject; var CloseAction: TCloseAction);
3974 begin
3975 UpdateSelectedControl;
3976 end;
3977
3978 procedure TDesignFrame.PropertyGridCollectionItemAdd(Sender: TObject);
3979 begin
3980 ((Sender as TToolButton).Parent.Parent as TCollectionPropertyEditorForm).actAddExecute(Sender);
3981 RecordUndo('Add item', ucLow);
3982 end;
3983
3984 procedure TDesignFrame.PropertyGridCollectionItemDelete(Sender: TObject);
3985 begin
3986 ((Sender as TToolButton).Parent.Parent as TCollectionPropertyEditorForm).actDelExecute(Sender);
3987 RecordUndo('Delete item', ucLow);
3988 end;
3989
3990 procedure TDesignFrame.PropertyGridCollectionItemMoveUp(Sender: TObject);
3991 var
3992 FakeSender: TComponent;
3993 begin
3994 FakeSender := TComponent.Create(nil);
3995 try
3996 { This is a weird decision. It depends on sender's name to determine if
3997 it should move item up or move item down }
3998 FakeSender.Name := 'actMoveUp';
3999 ((Sender as TToolButton).Parent.Parent as TCollectionPropertyEditorForm).actMoveUpDownExecute(FakeSender);
4000 RecordUndo('Move item up', ucLow);
4001 finally
4002 FreeAndNil(FakeSender);
4003 end;
4004 end;
4005
4006 procedure TDesignFrame.PropertyGridCollectionItemMoveDown(Sender: TObject);
4007 var
4008 FakeSender: TComponent;
4009 begin
4010 FakeSender := TComponent.Create(nil);
4011 try
4012 { This is a weird decision. It depends on sender's name to determine if
4013 it should move item up or move item down }
4014 FakeSender.Name := 'actMoveDown';
4015 ((Sender as TToolButton).Parent.Parent as TCollectionPropertyEditorForm).actMoveUpDownExecute(FakeSender);
4016 RecordUndo('Move item down', ucLow);
4017 finally
4018 FreeAndNil(FakeSender);
4019 end;
4020 end;
4021
4022 procedure TDesignFrame.UpdateEditorDataForPropertyEditors;
4023 begin
4024 if PropertyEditorHook <> nil then
4025 begin
4026 PropertyEditorHook.InspectorAreaOnScreen.Left := ProjectForm.Left +
4027 Left + PanelRight.Left;
4028 PropertyEditorHook.InspectorAreaOnScreen.Top := ProjectForm.Top +
4029 Top + PanelRight.Top + ControlProperties.Top + 10;
4030 PropertyEditorHook.InspectorAreaOnScreen.Width := ControlProperties.Width;
4031 PropertyEditorHook.InspectorAreaOnScreen.Height := ControlProperties.Height;
4032 end;
4033 end;
4034
4035 procedure TDesignFrame.RecordUndo(const UndoComment: String;
4036 const UndoCommentPriority: TUndoCommentPriority);
4037 var
4038 StartTimer: TTimerResult;
4039 begin
4040 StartTimer := Timer;
4041 UndoSystem.RecordUndo(ComponentToString(FDesignRoot), GetSavedSelection, UndoComment, UndoCommentPriority);
4042 UndoSystem.DoLog('Undo "%s" recorded in %fs.', [UndoComment, StartTimer.ElapsedTime]);
4043 end;
4044
4045 procedure TDesignFrame.SaveSelected;
4046 var
4047 ComponentToSave: TComponent;
4048 begin
4049 ComponentToSave := SelectedComponent;
4050 if ComponentToSave = nil then
4051 begin
4052 ErrorBox('Select exactly one component to save');
4053 Exit;
4054 end;
4055
4056 PrepareSaveDesignDialog(SaveDesignDialog, ComponentToSave);
4057 SaveDesignDialog.Url := '';
4058 if SaveDesignDialog.Execute then
4059 begin
4060 if ComponentToSave is TCastleUserInterface then
4061 UserInterfaceSave(TCastleUserInterface(ComponentToSave), SaveDesignDialog.Url)
4062 else
4063 if ComponentToSave is TCastleTransform then
4064 TransformSave(TCastleTransform(ComponentToSave), SaveDesignDialog.Url)
4065 else
4066 ComponentSave(ComponentToSave, SaveDesignDialog.Url);
4067 end;
4068 end;
4069
4070 procedure TDesignFrame.MarkModified;
4071 begin
4072 // mark modified
4073 FDesignModified := true;
4074 OnUpdateFormCaption(Self);
4075 end;
4076
4077 class function TDesignFrame.Selectable(const Child: TComponent): Boolean;
4078 begin
4079 { Note: When changing conditions here, consider also updating ReasonWhyNotDeletable,
4080 that explains to user *why* something is not deletable (not being selectable
4081 also makes it not deletable). }
4082
4083 { csTransient reason:
4084
4085 Do not show in hierarchy the TCastleDesign loaded hierarchy,
4086 as it will not be saved.
4087 Same for TCastleCheckbox children.
4088 Consequently, do not allow to select stuff inside.
4089
4090 However, show TCastleToolTransform, even though it is csTransient.
4091 We want to allow selecting joint tools.
4092 }
4093 // Define this to inspect all transformations, including internal (gizmos)
4094 {.$define EDITOR_DEBUG_TRANSFORMS}
4095 {$ifdef EDITOR_DEBUG_TRANSFORMS}
4096 Result := true;
4097 {$else}
4098 Result := (not (csTransient in Child.ComponentStyle)) or (Child is TCastleToolTransform);
4099 {$endif}
4100 end;
4101
4102 function TDesignFrame.Deletable(const Child: TComponent): Boolean;
4103 begin
4104 { Note: When changing conditions here, consider also updating ReasonWhyNotDeletable,
4105 that explains to user *why* something is not deletable. }
4106
4107 Result := Selectable(Child) and
4108 (not (csSubComponent in Child.ComponentStyle)) and
4109 (Child <> DesignRoot) and (not (Child is TCastleToolTransform));
4110 end;
4111
4112 type
4113 EHierarchyValidationFailed = class(Exception);
4114 const
4115 ValidationError = 'Hierarchy view desynchronized with CGE internal hierarchy. 1. Please submit a bug, this should never happen. 2. To workaround it for now, save and reopen the design file.';
4116
4117 procedure TDesignFrame.ValidateOrUpdateHierarchy(const Validate: Boolean);
4118 var
4119 NodesToExpand: TObjectList;
4120
4121 { Make sure that given parent, at given index, has given child.
4122 Return this child (TTreeNode),
4123 and increase IndexInParent by 1.
4124
4125 Parent may be nil, indicating the root of ControlsTree.
4126 (It's a bit uncomfortable, but there's no single "root" node for
4127 ControlsTree. At the top level there is TTreeNodes, which is already
4128 a list.)
4129
4130 In case of Validate = false: if there is a mismatch,
4131 it fixes the mismatch by adding a new child.
4132 But it assumes that Parent has at least IndexInParent-1 children,
4133 i.e. all previous children (with smaller IndexInParent) are matching.
4134
4135 In case of Validate = true: if there is a mismatch,
4136 raises EHierarchyValidationFailed. }
4137 function EnsureChildNodeIs(const Parent: TTreeNode; var IndexInParent: Integer;
4138 const ChildNodeCaption: String; const ChildNodeData: Pointer): TTreeNode;
4139 var
4140 Valid, NextIsValid: Boolean;
4141 begin
4142 if Parent = nil then
4143 begin
4144 Assert(ControlsTree.Items.TopLvlCount >= IndexInParent);
4145 Valid := (ControlsTree.Items.TopLvlCount > IndexInParent) and
4146 (ControlsTree.Items.TopLvlItems[IndexInParent].Text = ChildNodeCaption) and
4147 (ControlsTree.Items.TopLvlItems[IndexInParent].Data = ChildNodeData);
4148 NextIsValid := (ControlsTree.Items.TopLvlCount > IndexInParent + 1) and
4149 (ControlsTree.Items.TopLvlItems[IndexInParent + 1].Text = ChildNodeCaption) and
4150 (ControlsTree.Items.TopLvlItems[IndexInParent + 1].Data = ChildNodeData);
4151 end else
4152 begin
4153 Assert(Parent.Count >= IndexInParent);
4154 Valid := (Parent.Count > IndexInParent) and
4155 (Parent.Items[IndexInParent].Text = ChildNodeCaption) and
4156 (Parent.Items[IndexInParent].Data = ChildNodeData);
4157 NextIsValid := (Parent.Count > IndexInParent + 1) and
4158 (Parent.Items[IndexInParent + 1].Text = ChildNodeCaption) and
4159 (Parent.Items[IndexInParent + 1].Data = ChildNodeData);
4160 end;
4161
4162 // observe this log after delete/add operation
4163 {
4164 WritelnLog('Child node %s valid? %s', [
4165 ChildNodeCaption,
4166 BoolToStr(Valid, true)
4167 ]);
4168 }
4169
4170 if Valid then
4171 begin
4172 if Parent = nil then
4173 Result := ControlsTree.Items.TopLvlItems[IndexInParent]
4174 else
4175 Result := Parent.Items[IndexInParent];
4176 end else
4177 begin
4178 if Validate then
4179 begin
4180 raise EHierarchyValidationFailed.Create(ValidationError);
4181 end;
4182
4183 // now we know Validate = false
4184
4185 if NextIsValid then
4186 begin
4187 // delete the IndexInParent child of Parent and we will be OK
4188 if Parent = nil then
4189 begin
4190 ControlsTree.Items.Delete(ControlsTree.Items.TopLvlItems[IndexInParent]);
4191 Result := ControlsTree.Items.TopLvlItems[IndexInParent];
4192 end else
4193 begin
4194 ControlsTree.Items.Delete(Parent.Items[IndexInParent]);
4195 Result := Parent.Items[IndexInParent];
4196 end;
4197 end else
4198 begin
4199 { insert new child at position IndexInParent to Parent.
4200
4201 Looks like TTreeNode doesn't give nice API to Insert at specified
4202 position into an indicated parent. But we can just remove
4203 all excessive nodes -- they are all likely invalid at this point. }
4204
4205 if Parent = nil then
4206 begin
4207 while ControlsTree.Items.TopLvlCount > IndexInParent do
4208 ControlsTree.Items.Delete(ControlsTree.Items.TopLvlItems[IndexInParent]);
4209 Assert(IndexInParent = ControlsTree.Items.TopLvlCount); // this should be true if previous children were valid
4210 end else
4211 begin
4212 while Parent.Count > IndexInParent do
4213 ControlsTree.Items.Delete(Parent.Items[IndexInParent]);
4214 Assert(IndexInParent = Parent.Count); // this should be true if previous children were valid
4215 end;
4216
4217 // this works for Parent = nil or non-nil
4218 Result := ControlsTree.Items.AddChildObject(Parent, ChildNodeCaption, ChildNodeData);
4219
4220 { Expand newly added nodes.
4221 Note that we cannot call now Result.Expand(true),
4222 because Result has no children and calling Expand() on it does nothing. }
4223 if not Validate then
4224 NodesToExpand.Add(Result);
4225 end;
4226 end;
4227
4228 Assert(Result.Text = ChildNodeCaption);
4229 Assert(Result.Data = ChildNodeData);
4230 Inc(IndexInParent);
4231 end;
4232
4233 { Make sure given Parent node has *at most* ParentCount children.
4234
4235 In case of Validate = false: if there is a mismatch,
4236 it removes excessive children.
4237
4238 In case of Validate = true: if there is a mismatch,
4239 raises EHierarchyValidationFailed. }
4240 procedure EnsureChildrenNodesCount(const Parent: TTreeNode; const ParentCount: Integer);
4241 var
4242 Valid: Boolean;
4243 begin
4244 if Parent = nil then
4245 begin
4246 Valid := ControlsTree.Items.TopLvlCount <= ParentCount;
4247 end else
4248 begin
4249 Valid := Parent.Count <= ParentCount;
4250 end;
4251
4252 if not Valid then
4253 begin
4254 if Validate then
4255 begin
4256 raise EHierarchyValidationFailed.Create(ValidationError);
4257 end;
4258
4259 // now we know Validate = false
4260
4261 if Parent = nil then
4262 begin
4263 while ControlsTree.Items.TopLvlCount > ParentCount do
4264 ControlsTree.Items.Delete(ControlsTree.Items.TopLvlItems[ParentCount]);
4265 end else
4266 begin
4267 while Parent.Count > ParentCount do
4268 ControlsTree.Items.Delete(Parent.Items[ParentCount]);
4269 end;
4270 end;
4271 end;
4272
4273 { Update TreeNodeMap, mapping components -> to their corresponding tree node.
4274 Ignored when Validate = false. }
4275 procedure UpdateTreeNodeMap(const C: TComponent; const Node: TTreeNode);
4276 begin
4277 if not Validate then
4278 TreeNodeMap.AddOrSetValue(C, Node);
4279 end;
4280
4281 { Add given component, and its children in C.NonVisualComponents }
4282 function AddNonVisualComponent(const Parent: TTreeNode; var IndexInParent: Integer; const C: TComponent): TTreeNode;
4283 var
4284 S: String;
4285 Child: TComponent;
4286 ChildrenNodesCount: Integer;
4287 begin
4288 S := TreeNodeCaption(C);
4289 Result := EnsureChildNodeIs(Parent, IndexInParent, S, C);
4290 UpdateTreeNodeMap(C, Result);
4291
4292 if C is TCastleComponent then
4293 begin
4294 ChildrenNodesCount := 0;
4295 for Child in TCastleComponent(C).NonVisualComponentsEnumerate do
4296 if Selectable(Child) then
4297 AddNonVisualComponent(Result, ChildrenNodesCount, Child);
4298 EnsureChildrenNodesCount(Result, ChildrenNodesCount);
4299 end;
4300 end;
4301
4302 { If C has some NonVisualComponents, then create a tree item
4303 'Non-Visual Components' and add them to it. }
4304 function AddNonVisualComponentsSection(const Parent: TTreeNode; var IndexInParent: Integer; const C: TCastleComponent): TTreeNode;
4305 var
4306 Child: TComponent;
4307 ChildrenNodesCount: Integer;
4308 begin
4309 if C.NonVisualComponentsCount <> 0 then
4310 begin
4311 Result := EnsureChildNodeIs(Parent, IndexInParent, 'Non-Visual Components', nil);
4312
4313 ChildrenNodesCount := 0;
4314 for Child in C.NonVisualComponentsEnumerate do
4315 if Selectable(Child) then
4316 AddNonVisualComponent(Result, ChildrenNodesCount, Child);
4317 EnsureChildrenNodesCount(Result, ChildrenNodesCount);
4318 end;
4319 end;
4320
4321 { If T has some Behaviors, then create a tree item
4322 'Behaviors' and add them to it. }
4323 function AddBehaviorsSection(const Parent: TTreeNode; var IndexInParent: Integer; const T: TCastleTransform): TTreeNode;
4324 var
4325 Child: TCastleBehavior;
4326 ChildrenNodesCount: Integer;
4327 begin
4328 if T.BehaviorsCount <> 0 then
4329 begin
4330 Result := EnsureChildNodeIs(Parent, IndexInParent, 'Behaviors', nil);
4331
4332 ChildrenNodesCount := 0;
4333 for Child in T.BehaviorsEnumerate do
4334 if Selectable(Child) then
4335 AddNonVisualComponent(Result, ChildrenNodesCount, Child);
4336 EnsureChildrenNodesCount(Result, ChildrenNodesCount);
4337 end;
4338 end;
4339
4340 { Add given transform, and its children
4341 (transform children, T.NonVisualComponents, T.Behaviors). }
4342 function AddTransform(const Parent: TTreeNode; var IndexInParent: Integer; const T: TCastleTransform): TTreeNode;
4343 var
4344 S: String;
4345 I, ChildrenNodesCount: Integer;
4346 begin
4347 S := TreeNodeCaption(T);
4348 Result := EnsureChildNodeIs(Parent, IndexInParent, S, T);
4349 UpdateTreeNodeMap(T, Result);
4350
4351 ChildrenNodesCount := 0;
4352 AddNonVisualComponentsSection(Result, ChildrenNodesCount, T);
4353 AddBehaviorsSection(Result, ChildrenNodesCount, T);
4354
4355 for I := 0 to T.Count - 1 do
4356 if Selectable(T[I]) then
4357 AddTransform(Result, ChildrenNodesCount, T[I]);
4358
4359 EnsureChildrenNodesCount(Result, ChildrenNodesCount);
4360 end;
4361
4362 { Add given UI control, and its children. }
4363 function AddControl(const Parent: TTreeNode; var IndexInParent: Integer; const C: TCastleUserInterface): TTreeNode;
4364 var
4365 S: String;
4366 I, ChildrenNodesCount: Integer;
4367 Viewport: TCastleViewport;
4368 begin
4369 S := TreeNodeCaption(C);
4370 Result := EnsureChildNodeIs(Parent, IndexInParent, S, C);
4371 UpdateTreeNodeMap(C, Result);
4372
4373 ChildrenNodesCount := 0;
4374 AddNonVisualComponentsSection(Result, ChildrenNodesCount, C);
4375
4376 for I := 0 to C.ControlsCount - 1 do
4377 begin
4378 if Selectable(C.Controls[I]) then
4379 AddControl(Result, ChildrenNodesCount, C.Controls[I]);
4380 end;
4381
4382 if C is TCastleViewport then
4383 begin
4384 Viewport := TCastleViewport(C);
4385 if Selectable(Viewport.Items) then
4386 AddTransform(Result, ChildrenNodesCount, Viewport.Items);
4387 end;
4388 EnsureChildrenNodesCount(Result, ChildrenNodesCount);
4389 end;
4390
4391 var
4392 ChildrenNodesCount: Integer;
4393 O: Pointer;
4394 begin
4395 if not Validate then
4396 NodesToExpand := TObjectList.Create(false)
4397 else
4398 NodesToExpand := nil;
4399 try
4400 ChildrenNodesCount := 0;
4401 if DesignRoot is TCastleUserInterface then
4402 AddControl(nil, ChildrenNodesCount, DesignRoot as TCastleUserInterface)
4403 else
4404 if DesignRoot is TCastleTransform then
4405 AddTransform(nil, ChildrenNodesCount, DesignRoot as TCastleTransform)
4406 else
4407 if DesignRoot <> nil then
4408 AddNonVisualComponent(nil, ChildrenNodesCount, DesignRoot);
4409 EnsureChildrenNodesCount(nil, ChildrenNodesCount);
4410
4411 if not Validate then
4412 begin
4413 for O in NodesToExpand do
4414 begin
4415 { Expand also parent.
4416 Reason: we want the parent (which is a node that existed before) to expand,
4417 to show newly added child.
4418
4419 Testcase:
4420 - add TCastleTransformDesign, with no children, with URL pointing to something,
4421 - and then use "Edit (Copy Here) Referenced Design".
4422 - the TCastleTransformDesign is initially added and without any children in the hierarchy.
4423 It gets a call to "Expand(false)", but it doesn't actually do anything it seems.
4424 - later, we add some children to TCastleTransformDesign.
4425 The children are on NodesToExpand list, but not the TCastleTransformDesign itself.
4426 So calling Expand(false) on children does not make them visible,
4427 as TCastleTransformDesign is collapsed.
4428 - So we need to access parent to expand that TCastleTransformDesign.
4429 }
4430 if TTreeNode(O).Parent <> nil then
4431 TTreeNode(O).Parent.Expand(false);
4432
4433 TTreeNode(O).Expand(false); // no need for recurse=true, because we will call this on children too
4434 end;
4435 end;
4436 finally
4437 FreeAndNil(NodesToExpand);
4438 end;
4439 end;
4440
4441 procedure TDesignFrame.UpdateDesign;
4442
4443 { Set ControlsTree selection to given components.
4444 Selected may be @nil indicating "select nothing". }
4445 procedure ControlsTreeSetSelection(const Selected: TComponentList);
4446 var
4447 SelectedNodes: TList; // TTreeNode list
4448 SelectedNode: TTreeNode;
4449 I: Integer;
4450 begin
4451 if (Selected <> nil) and
4452 (Selected.Count <> 0) then
4453 begin
4454 SelectedNodes := TList.Create;
4455 try
4456 for I := 0 to Selected.Count - 1 do
4457 if TreeNodeMap.TryGetValue(Selected[I], SelectedNode) then
4458 SelectedNodes.Add(SelectedNode);
4459 ControlsTree.Select(SelectedNodes);
4460 finally FreeAndNil(SelectedNodes) end;
4461 end else
4462 ControlsTree.ClearSelection;
4463 end;
4464
4465 begin
4466 { Note that we cannot do GetSelected now to save current selection state.
4467 At this point, our tree may contain invalid pointers.
4468 Imagine that we just deleted a (selected) hinge component,
4469 that also freed related anchor (TCastleTransform).
4470 Neither hinge component, nor anchor (TCastleTransform), exist anymore.
4471 So we just use LastSelected to restore. }
4472
4473 // temporarily disable events, as some pointers in ControlsTree data are invalid now
4474 ControlsTree.OnSelectionChanged := nil;
4475
4476 TreeNodeMap.Clear; // ValidateOrUpdateHierarchy(false) will fill TreeNodeMap
4477
4478 ValidateOrUpdateHierarchy(false);
4479
4480 { Restore selection.
4481 Without this (if we would clear selection like ControlsTree.ClearSelection),
4482 selecting physics joint would not work,
4483 as selecting it would reset selection making it unselected again. }
4484 ControlsTreeSetSelection(LastSelected);
4485
4486 // restore events
4487 ControlsTree.OnSelectionChanged := @ControlsTreeSelectionChanged;
4488
4489 InternalCastleDesignInvalidate := false;
4490
4491 { Note that this sets (maybe changes to nil if unselected) TransformDesigning,
4492 calling some DesigningBegin / DesigningEnd.
4493 They in turn may create / destroy something, and set
4494 InternalCastleDesignInvalidate := true and it shoud cause UpdateDesign again.
4495 It actually should not happen anymore (because we save/restore selection,
4496 so TransformDesigning should remain the same) but better be secure from it. }
4497 UpdateSelectedControl;
4498 end;
4499
4500 function TDesignFrame.ValidateHierarchy: Boolean;
4501 begin
4502 try
4503 ValidateOrUpdateHierarchy(true);
4504 Result := true;
4505 except
4506 on E: EHierarchyValidationFailed do
4507 begin
4508 Result := false;
4509 WritelnWarning(E.Message);
4510 end;
4511 end;
4512 end;
4513
4514 function TDesignFrame.SelectedFromNode(Node: TTreeNode;
4515 const AutoSelectParents: Boolean): TComponent;
4516 begin
4517 // This should never be called with Node = nil
4518 Assert(Node <> nil);
4519
4520 { In case of special tree items "Behaviors" or "Non-Visual Components",
4521 treat parent as selected. }
4522 if AutoSelectParents then
4523 begin
4524 if Node.Data = nil then
4525 begin
4526 Node := Node.Parent;
4527 if Node = nil then
4528 begin
4529 WritelnWarning('No parent of special node (without the associated TComponent), this should not happen');
4530 Exit(nil);
4531 end;
4532 if Node.Data = nil then
4533 begin
4534 WritelnWarning('Parent of special node (without the associated TComponent) also has no associated TComponent, this should not happen');
4535 Exit(nil);
4536 end;
4537 end;
4538 Assert(Node.Data <> nil);
4539 end;
4540
4541 if Node.Data = nil then
4542 begin
4543 Assert(not AutoSelectParents); // possible only if AutoSelectParents=false
4544 Exit(nil);
4545 end;
4546
4547 Assert(TObject(Node.Data) is TComponent); // we only store nil or TComponent instance in Node.Data
4548 Result := TComponent(Node.Data);
4549 end;
4550
4551 procedure TDesignFrame.SetSelected(const Selected: TComponentList);
4552 var
4553 NewSelectedNodes: TList;
4554 NewNode: TTreeNode;
4555 C: TComponent;
4556 begin
4557 NewSelectedNodes := TList.Create;
4558 try
4559 if Selected <> nil then
4560 for C in Selected do
4561 if TreeNodeMap.TryGetValue(C, NewNode) then
4562 NewSelectedNodes.Add(NewNode);
4563 ControlsTree.Select(NewSelectedNodes);
4564 finally FreeAndNil(NewSelectedNodes) end;
4565 end;
4566
4567 procedure TDesignFrame.GetSelected(out Selected: TComponentList;
4568 out SelectedCount: Integer; const AutoSelectParents: Boolean);
4569
4570 { This implementation is synchronized with GetSelectedComponent closely,
4571 as GetSelectedComponent needs to do something similar. }
4572
4573 var
4574 I: Integer;
4575 C: TComponent;
4576 begin
4577 Selected := nil;
4578
4579 for I := 0 to ControlsTree.SelectionCount - 1 do
4580 begin
4581 C := SelectedFromNode(ControlsTree.Selections[I], AutoSelectParents);
4582 if C <> nil then
4583 begin
4584 if Selected = nil then
4585 Selected := TComponentList.Create(false);
4586 { Avoid duplicates that could occur if you select a component
4587 and special tree item "Behaviors" or "Non-Visual Components" within. }
4588 if Selected.IndexOf(C) = -1 then
4589 Selected.Add(C);
4590 end;
4591 end;
4592
4593 if Selected <> nil then
4594 begin
4595 SelectedCount := Selected.Count;
4596 // LastSelected only reflects state with AutoSelectParents=true
4597 if AutoSelectParents then
4598 LastSelected.Assign(Selected);
4599 end else
4600 begin
4601 SelectedCount := 0;
4602 // LastSelected only reflects state with AutoSelectParents=true
4603 if AutoSelectParents then
4604 LastSelected.Clear;
4605 end;
4606 end;
4607
4608 function TDesignFrame.GetSelectedUserInterface: TCastleUserInterface;
4609 var
4610 C: TComponent;
4611 begin
4612 C := GetSelectedComponent;
4613 if C is TCastleUserInterface then
4614 Result := TCastleUserInterface(C)
4615 else
4616 Result := nil;
4617 end;
4618
4619 procedure TDesignFrame.SetSelectedUserInterface(const Value: TCastleUserInterface);
4620 begin
4621 SelectedComponent := Value;
4622 end;
4623
4624 function TDesignFrame.GetSelectedTransform: TCastleTransform;
4625 var
4626 C: TComponent;
4627 begin
4628 C := GetSelectedComponent;
4629 if C is TCastleTransform then
4630 Result := TCastleTransform(C)
4631 else
4632 Result := nil;
4633 end;
4634
4635 procedure TDesignFrame.SetSelectedTransform(const Value: TCastleTransform);
4636 begin
4637 SelectedComponent := Value;
4638 end;
4639
4640 function TDesignFrame.GetSelectedComponentAutoSelectParents: TComponent;
4641 begin
4642 Result := GetSelectedComponent(true);
4643 end;
4644
4645 function TDesignFrame.GetSelectedComponent(const AutoSelectParents: Boolean): TComponent;
4646
4647 { This implementation is synchronized with GetSelected closely.
4648
4649 Naive version (using GetSelected to create TComponentList,
4650 that also registers notifications -- so it has some cost) is defined below,
4651 and you can use Assert to make sure it is equal to the optimized one.
4652 But it is commented out now, as the editor just uses debug mode now always,
4653 for simplicity -- as there are no practical points when it needs optimization.
4654 *This* optimization is also not practical, i.e. not proven by any test. }
4655
4656 {
4657 function GetSelectedComponentNaive: TComponent;
4658 var
4659 Selected: TComponentList;
4660 SelectedCount: Integer;
4661 begin
4662 GetSelected(Selected, SelectedCount, AutoSelectParents);
4663 try
4664 if SelectedCount = 1 then
4665 Result := Selected[0]
4666 else
4667 Result := nil;
4668 finally FreeAndNil(Selected) end;
4669 end;
4670 }
4671
4672 var
4673 I: Integer;
4674 C: TComponent;
4675 begin
4676 Result := nil;
4677
4678 for I := 0 to ControlsTree.SelectionCount - 1 do
4679 begin
4680 C := SelectedFromNode(ControlsTree.Selections[I], AutoSelectParents);
4681 if C <> nil then
4682 begin
4683 if Result <> nil then
4684 begin
4685 if Result <> C then
4686 begin
4687 { more than one component selected -> exit nil, do not update LastSelected }
4688 // Assert(nil = GetSelectedComponentNaive);
4689 Exit(nil);
4690 end;
4691 { else C is the same thing as already selected
4692 (possible when you select both the component and its special child like "Behaviors"),
4693 so do nothing }
4694 end else
4695 { at least one component is selected }
4696 Result := C;
4697 end;
4698 end;
4699
4700 // LastSelected only reflects state with AutoSelectParents=true
4701 if AutoSelectParents then
4702 begin
4703 { Update LastSelected to 0 or 1 components }
4704 LastSelected.Clear;
4705 if Result <> nil then
4706 LastSelected.Add(Result);
4707 end;
4708
4709 // Assert(Result = GetSelectedComponentNaive);
4710 end;
4711
4712 function TDesignFrame.ControlsTreeOneSelected: TTreeNode;
4713 begin
4714 if ControlsTree.SelectionCount = 1 then
4715 Result := ControlsTree.Selections[0]
4716 else
4717 Result := nil;
4718 end;
4719
4720 procedure TDesignFrame.SetSelectedComponent(const Value: TComponent);
4721 var
4722 Node: TTreeNode;
4723 begin
4724 { Disabling OnSelectionChanged is safest because ControlsTree.Select
4725 first calls ClearSelection which, in turn, calls OnSelectionChanged.
4726
4727 If OnSelectionChanged would cause ControlsTreeSelectionChanged then
4728 - UpdateSelectedControl gets called
4729 - in turn TransformDesigning is set
4730 - which may cause some DesigningEnd calls on hinges
4731 - which may free some TTreeNode.Data pointers invalid
4732
4733 There's nothing inherently bad in above (it would be bad only if TTreeNode
4734 instance would become invalid in the middle of ControlsTree.Select),
4735 but still it seems safer to avoid such cascade in the middle of ControlsTree.Select.
4736 }
4737
4738 ControlsTree.OnSelectionChanged := nil;
4739
4740 if Value = nil then
4741 ControlsTree.Select([])
4742 else
4743 if TreeNodeMap.TryGetValue(Value, Node) then
4744 ControlsTree.Select([Node]);
4745
4746 ControlsTree.OnSelectionChanged := @ControlsTreeSelectionChanged;
4747 ControlsTreeSelectionChanged(nil);
4748 end;
4749
4750 function TDesignFrame.CurrentTransform: TCastleTransform;
4751 begin
4752 if SelectedComponent is TCastleBehavior then
4753 Result := TCastleBehavior(SelectedComponent).Parent
4754 else
4755 Result := SelectedTransform;
4756 end;
4757
4758 procedure TDesignFrame.UpdateSelectedInfo;
4759 var
4760 C: TComponent;
4761 SListInfo, SListWarnings: TStringList;
4762 begin
4763 C := SelectedComponent;
4764 if C is TCastleComponent then
4765 begin
4766 SListInfo := nil;
4767 SListWarnings := nil;
4768 try
4769 SListInfo := TStringList.Create;
4770 SListWarnings := TStringList.Create;
4771
4772 TCastleComponent(C).DesignerInfo(SListInfo);
4773 TCastleComponent(C).DesignerWarnings(SListWarnings);
4774
4775 if (SListInfo.Count <> 0) or (SListWarnings.Count <> 0) then
4776 begin
4777 TabInfo.TabVisible := true;
4778
4779 MemoInfo.Lines.Clear;
4780
4781 if SListWarnings.Count <> 0 then
4782 begin
4783 MemoInfo.Lines.Add('Warnings (%d):', [SListWarnings.Count]);
4784 MemoInfo.Lines.AddStrings(SListWarnings, false);
4785 TabInfo.Caption := Format('Warnings (%d)', [SListWarnings.Count]);
4786 end else
4787 TabInfo.Caption := 'Info';
4788
4789 if SListInfo.Count <> 0 then
4790 begin
4791 if MemoInfo.Lines.Count <> 0 then
4792 MemoInfo.Lines.Add('');
4793 MemoInfo.Lines.Add('Information:');
4794 MemoInfo.Lines.AddStrings(SListInfo, false);
4795 end;
4796 end else
4797 begin
4798 TabInfo.TabVisible := false;
4799 end;
4800 finally
4801 FreeAndNil(SListInfo);
4802 FreeAndNil(SListWarnings);
4803 end;
4804 end else
4805 begin
4806 TabInfo.TabVisible := false;
4807 end;
4808 end;
4809
4810 procedure TDesignFrame.UpdateSelectedControl;
4811
4812 procedure InitializeCollectionFormEvents(InspectorType: TInspectorType);
4813 var
4814 I: Integer;
4815 Row: TOIPropertyGridRow;
4816 Ed: TCollectionPropertyEditor = nil;
4817 begin
4818 if CollectionPropertyEditorForm = nil then
4819 begin
4820 { If there is any property that can have a TCollectionPropertyEditor,
4821 then (once for the whole lifetime of this TDesignFrame) we need to assign
4822 our callbacks to the associated TCollectionPropertyEditorForm .
4823 *Before* the form can be actually invoked by user pressing "..." button
4824 near the respective field.
4825
4826 The TCollectionPropertyEditorForm form instance is internal in LCL,
4827 it is reused by all property editors and it stays constant
4828 for the rest of the application's lifetime.
4829 The code below detects if there's *any* field with TCollectionPropertyEditor,
4830 and if yes -- creates (and immediately closes) the associated
4831 TCollectionPropertyEditorForm, just to initialize our callbacks.
4832
4833 Example field: TDbf.FieldDefs, test with
4834 https://github.com/castle-engine/castle-db-aware-controls }
4835
4836 for I := 0 to Inspector[InspectorType].RowCount - 1 do
4837 begin
4838 Row := Inspector[InspectorType].Rows[I];
4839 if Row.Editor is TCollectionPropertyEditor then
4840 begin
4841 Ed := TCollectionPropertyEditor(Row.Editor);
4842 Break;
4843 end;
4844 end;
4845 if Ed <> nil then
4846 begin
4847 CollectionPropertyEditorForm := Ed.ShowCollectionEditor(nil, nil, '') as TCollectionPropertyEditorForm;
4848 CollectionPropertyEditorForm.FreeNotification(Self);
4849 CollectionPropertyEditorForm.Close; // Hide the form
4850 CollectionPropertyEditorForm.OnClose := @PropertyGridCollectionItemClose;
4851 CollectionPropertyEditorForm.FormStyle := fsStayOnTop;
4852 CollectionPropertyEditorForm.CollectionListBox.OnClick := @PropertyGridCollectionItemClick;
4853 { We remove TToolButton's actions and use our own's OnClick events
4854 instead so that we can hook our undo/redo system in }
4855 CollectionPropertyEditorForm.AddButton.Action := nil;
4856 CollectionPropertyEditorForm.AddButton.Enabled := True;
4857 CollectionPropertyEditorForm.DeleteButton.Action := nil;
4858 CollectionPropertyEditorForm.DeleteButton.Enabled := True;
4859 CollectionPropertyEditorForm.MoveUpButton.Action := nil;
4860 CollectionPropertyEditorForm.MoveUpButton.Enabled := True;
4861 CollectionPropertyEditorForm.MoveDownButton.Action := nil;
4862 CollectionPropertyEditorForm.MoveDownButton.Enabled := True;
4863 CollectionPropertyEditorForm.AddButton.OnClick := @PropertyGridCollectionItemAdd;
4864 CollectionPropertyEditorForm.DeleteButton.OnClick := @PropertyGridCollectionItemDelete;
4865 CollectionPropertyEditorForm.MoveUpButton.OnClick := @PropertyGridCollectionItemMoveUp;
4866 CollectionPropertyEditorForm.MoveDownButton.OnClick := @PropertyGridCollectionItemMoveDown;
4867 end;
4868 end;
4869 end;
4870
4871 var
4872 Selected: TComponentList;
4873 I, SelectedCount: Integer;
4874 SelectionForOI: TPersistentSelectionList;
4875 UI: TCastleUserInterface;
4876 InspectorType: TInspectorType;
4877 V: TCastleViewport;
4878 T: TCastleTransform;
4879 begin
4880 OnSelectionChanged(Self); // Calling it in ControlsTreeSelectionChanged doesn't seem to be enough as RenameSelectedPossible is true there even in case SelectedCount = 0 (does it use some obsolete value?)
4881
4882 GetSelected(Selected, SelectedCount);
4883 try
4884 case SelectedCount of
4885 0: LabelControlSelected.Caption := 'Nothing Selected';
4886 1: LabelControlSelected.Caption := 'Selected:' + NL + ComponentCaption(Selected[0]);
4887 else LabelControlSelected.Caption := 'Selected:' + NL + IntToStr(SelectedCount) + ' components';
4888 end;
4889
4890 SetEnabledVisible(ControlProperties, SelectedCount <> 0);
4891
4892 SelectionForOI := TPersistentSelectionList.Create;
4893 try
4894 for I := 0 to SelectedCount - 1 do
4895 SelectionForOI.Add(Selected[I]);
4896 for InspectorType in TInspectorType do
4897 Inspector[InspectorType].Selection := SelectionForOI;
4898
4899 { Inspector itAll includes all fields from all inspectors, always.
4900 So there's no reason to run InitializeCollectionFormEvents on other itXxx inspectors. }
4901 InitializeCollectionFormEvents(itAll);
4902 finally FreeAndNil(SelectionForOI) end;
4903
4904 UI := SelectedUserInterface;
4905 SetEnabledVisible(PanelAnchors, UI <> nil);
4906 if UI <> nil then
4907 UpdateAnchors(UI, true);
4908
4909 V := SelectedViewport;
4910 T := CurrentTransform;
4911 SetEnabledVisible(PanelLayoutTransform, T <> nil);
4912
4913 (*
4914 // The TransformDesigning mechanism works, but it's unused for now.
4915
4916 if SelectedComponent is TCastleToolTransform then
4917 { Design parent of TCastleToolTransform,
4918 otherwise TCastleToolTransform would disappear as soon as we select it. }
4919 TransformDesigning := TCastleToolTransform(SelectedComponent).Parent
4920 else
4921 TransformDesigning := T;
4922 *)
4923
4924 VisualizeTransformSelected.SetSelectedParents(Selected);
4925 if T is TCastleAbstractRootTransform then
4926 begin
4927 { Special case to disallow editing TCastleAbstractRootTransform transformation.
4928 See InspectorFilter for explanation, in short: editing TCastleAbstractRootTransform
4929 transformation is very unintuitive. }
4930 VisualizeTransformSelected.Parent := nil
4931 end else
4932 begin
4933 VisualizeTransformSelected.Parent := T; // works also in case SelectedTransform is nil
4934 end;
4935 finally FreeAndNil(Selected) end;
4936
4937 if CameraPreview <> nil then
4938 CameraPreview.SelectedChanged(T, V);
4939
4940 { if selection determines CurrentViewport, update CurrentViewport immediately
4941 (without waiting for OnUpdate) -- maybe this will be relevant at some point }
4942 UpdateCurrentViewport;
4943
4944 UpdateSelectedInfo;
4945 end;
4946
4947 (*
4948 // The TransformDesigning mechanism works, but it unused for now.
4949 procedure TDesignFrame.TransformDesigningFreeNotification(const Value: TFreeNotificationObserver);
4950 begin
4951 TransformDesigning := nil;
4952 end;
4953
4954 procedure TDesignFrame.SetTransformDesigning(const Value: TCastleTransform);
4955 var
4956 B: TCastleBehavior;
4957 begin
4958 if FTransformDesigning <> Value then
4959 begin
4960 if FTransformDesigning <> nil then
4961 begin
4962 for B in FTransformDesigning.BehaviorsEnumerate do
4963 B.DesigningEnd;
4964 end;
4965
4966 FTransformDesigning := Value;
4967 FTransformDesigningObserver.Observed := Value;
4968
4969 if FTransformDesigning <> nil then
4970 begin
4971 for B in FTransformDesigning.BehaviorsEnumerate do
4972 B.DesigningBegin;
4973 end;
4974 end;
4975 end;
4976 *)
4977
4978 procedure TDesignFrame.ControlsTreeSelectionChanged(Sender: TObject);
4979 begin
4980 UpdateSelectedControl;
4981 end;
4982
4983 procedure TDesignFrame.ControlsTreeDragOver(Sender, Source: TObject; X,
4984 Y: Integer; State: TDragState; var Accept: Boolean);
4985
4986 { Drag and drop handling when destination is ControlsTree.
4987 Useful info about TTreeView drag and drop handling:
4988 on https://stackoverflow.com/questions/18856374/delphi-treeview-drag-and-drop-between-nodes
4989 }
4990
4991 function NodeSide(const Node: TTreeNode; const X, Y: Integer): TTreeNodeSide;
4992 var
4993 R: TRect;
4994 begin
4995 R := Node.DisplayRect(false);
4996 if Y < Lerp(0.75, R.Bottom, R.Top) then
4997 Result := tnsTop
4998 else
4999 if Y > Lerp(0.25, R.Bottom, R.Top) then
5000 Result := tnsBottom
5001 else
5002 Result := tnsInside;
5003 end;
5004
5005 var
5006 SrcComponents: TComponentList;
5007 IgnoredSrcComponentsCount: Integer;
5008 Dst: TTreeNode;
5009 begin
5010 Accept := false;
5011 if Source = ControlsTree then
5012 begin
5013 // get destination of drag-and-drop
5014 Dst := ControlsTree.GetNodeAt(X, Y);
5015 ControlsTreeNodeUnderMouse := Dst;
5016
5017 // get and check source of drag-and-drop
5018 GetSelected(SrcComponents, IgnoredSrcComponentsCount, false);
5019 if SrcComponents <> nil then
5020 try
5021 Accept := ControlsTreeAllowDrag(SrcComponents, Dst);
5022 finally FreeAndNil(SrcComponents) end;
5023
5024 if not Accept then
5025 ControlsTreeNodeUnderMouse := nil;
5026
5027 { We don't use TCustomTreeView.GetHitTestInfoAt,
5028 it never contains flags htAbove, htBelow, htOnRight that interest us.
5029 (Simply not implemented, marked by TODO in Lazarus sources.) }
5030 //ControlsTreeNodeUnderMouseHit := ControlsTree.GetHitTestInfoAt(X, Y);
5031 if ControlsTreeNodeUnderMouse <> nil then
5032 ControlsTreeNodeUnderMouseSide := NodeSide(ControlsTreeNodeUnderMouse, X, Y);
5033 ControlsTree.Invalidate; // force custom-drawn look redraw
5034 end else
5035 if Source is TCastleShellListView then
5036 begin
5037 if SelectedComponent <> nil then
5038 Accept := ShellListComponentClass(TCastleShellListView(Source),
5039 SelectedComponent) <> nil;
5040 end;
5041 end;
5042
5043 procedure TDesignFrame.ControlsTreeEditing(Sender: TObject; Node: TTreeNode;
5044 var AllowEdit: Boolean);
5045 var
5046 C: TComponent;
5047 begin
5048 { This event is fired when calling TCustomListView.CanEdit
5049 which itself is called in TCustomListView.ShowEditor
5050 therefore this event preceeds initializing and showing of the editor. }
5051 C := TComponent(Node.Data);
5052 AllowEdit := C <> nil; // may be nil on special tree items "Behaviors" or "Non-Visual Components"
5053
5054 { Old: when Note.Text was different from C.Name, we set it here.
5055 This is pointless now, but also harmless, since TreeNodeCaption
5056 now just returns C.Name. }
5057 if AllowEdit then
5058 Node.Text := C.Name;
5059 end;
5060
5061 procedure TDesignFrame.ControlsTreeEditingEnd(Sender: TObject; Node: TTreeNode;
5062 Cancel: Boolean);
5063 var
5064 UndoComment: String;
5065 Sel: TComponent;
5066 begin
5067 try
5068 Sel := TComponent(Node.Data);
5069 if Sel = nil then
5070 begin
5071 // may be nil on special tree items "Behaviors" or "Non-Visual Components"
5072 WritelnWarning('Node data is nil at ControlsTreeEditingEnd, this should not happen');
5073 Exit;
5074 end;
5075
5076 { Check whether the edit actually changed anything.
5077 Otherwise the code below would execute too often (and make e.g. warnings
5078 about name uneditable for subcomponents) even when clicking around on "Items"
5079 without changing anything. }
5080 if Sel.Name <> Node.Text then
5081 begin
5082 if not RenamePossible(Sel) then
5083 begin
5084 if Sel.Owner <> nil then
5085 begin
5086 WritelnWarning('Renaming subcomponent (%s.%s) is not allowed. Subcomponents cannot be accessed by their names using TCastleView.DesignedComponent.', [
5087 Sel.Owner.ClassName,
5088 Sel.Name
5089 ]);
5090 end else
5091 begin
5092 { This never happens now, as RenamePossible for now only blocks editing
5093 name of subcomponents. }
5094 WritelnWarning('Renaming %s is not allowed.', [
5095 Sel.Name
5096 ]);
5097 end;
5098 Exit;
5099 end;
5100
5101 { Without this check, one could change Sel.Name to empty ('').
5102 Although TComponent.SetName checks that it's a valid Pascal identifier already,
5103 but it also explicitly allows to set Name = ''.
5104 Object inspector has special code to secure from empty Name
5105 (in TComponentNamePropertyEditor.SetValue), so we need a similar check here. }
5106 if not IsValidIdent(Node.Text) then
5107 begin
5108 ErrorBox(Format(oisComponentNameIsNotAValidIdentifier, [Node.Text]));
5109 Exit;
5110 end;
5111
5112 UndoComment := 'Rename ' + Sel.Name + ' into ' + Node.Text;
5113
5114 try
5115 Sel.Name := Node.Text;
5116 except
5117 { We capture exception and change into ErrorBox,
5118 otherwise tree view in LCL GTK2 may end up showing a weird content
5119 after doing "Node.Text := TreeNodeCaption(Sel)" below
5120 (blank, with size of component name) and sometimes hang.
5121 Explicitly catching and showing the error by ErrorBox workarounds it. }
5122 on E: EComponentError do
5123 begin
5124 ErrorBox(E.Message);
5125 Exit;
5126 end;
5127 end;
5128
5129 ModifiedOutsideObjectInspector(UndoComment, ucHigh); // It'd be good if we set "ItemIndex" to index of "name" field, but there doesn't seem to be an easy way to
5130 end;
5131 finally
5132 { This method must set Node.Text, to cleanup after ControlsTreeEditing + user editing.
5133 - If the name was correct, then "Sel.Name := " goes without exception,
5134 and we want to show new name + class name.
5135 - If the name was not correct, then "Sel.Name := " raises exception,
5136 and we want to show old name + class name. }
5137 Node.Text := TreeNodeCaption(Sel);
5138 end;
5139 end;
5140
5141 function TDesignFrame.ControlsTreeAllowDrag(const SrcComponent: TComponent; const Dst: TTreeNode): Boolean;
5142 begin
5143 Result := not (
5144 { Do not allow to drag-and-drop from ControlsTree to ControlsTree when:
5145
5146 - special tree items "Behaviors" or "Non-Visual Components"
5147 ( https://github.com/castle-engine/castle-engine/issues/520 )
5148 - root component
5149 - subcomponents (like TCastleScrollView.ScrollArea),
5150 - temporary transforms
5151 }
5152 (SrcComponent = nil) or
5153 (SrcComponent = DesignRoot) or
5154 (csSubComponent in SrcComponent.ComponentStyle) or
5155 (SrcComponent is TCastleToolTransform)
5156 );
5157 end;
5158
5159 function TDesignFrame.ControlsTreeAllowDrag(const Src, Dst: TTreeNode): Boolean;
5160 var
5161 SrcComponent: TComponent;
5162 begin
5163 Result := (Src <> nil) and (Dst <> nil) and (Src <> Dst);
5164 if Result then
5165 begin
5166 SrcComponent := TObject(Src.Data) as TComponent;
5167 Result := ControlsTreeAllowDrag(SrcComponent, Dst);
5168 end;
5169 end;
5170
5171 function TDesignFrame.ControlsTreeAllowDrag(const SrcComponents: TComponentList; const Dst: TTreeNode): Boolean;
5172 var
5173 C: TComponent;
5174 begin
5175 for C in SrcComponents do
5176 if not ControlsTreeAllowDrag(C, Dst) then
5177 Exit(false);
5178 Result := true;
5179 end;
5180
5181 procedure TDesignFrame.FrameAnchorsChange(Sender: TObject);
5182 var
5183 UI: TCastleUserInterface;
5184 OldRect: TFloatRectangle;
5185 begin
5186 UI := SelectedUserInterface;
5187 if UI <> nil then
5188 begin
5189 OldRect := UI.RenderRectWithBorder;
5190
5191 UI.HorizontalAnchorSelf := SelfAnchorsFrame.HorizontalAnchor;
5192 UI.VerticalAnchorSelf := SelfAnchorsFrame.VerticalAnchor;
5193 if CheckParentSelfAnchorsEqual.Checked then
5194 begin
5195 UI.HorizontalAnchorParent := UI.HorizontalAnchorSelf;
5196 UI.VerticalAnchorParent := UI.VerticalAnchorSelf;
5197 // keep invisible ParentAnchorsFrame synchronized
5198 ParentAnchorsFrame.HorizontalAnchor := UI.HorizontalAnchorParent;
5199 ParentAnchorsFrame.VerticalAnchor := UI.VerticalAnchorParent;
5200 end else
5201 begin
5202 UI.HorizontalAnchorParent := ParentAnchorsFrame.HorizontalAnchor;
5203 UI.VerticalAnchorParent := ParentAnchorsFrame.VerticalAnchor;
5204 end;
5205
5206 AdjustUserInterfaceAnchorsToKeepRect(UI, OldRect);
5207 end;
5208 end;
5209
5210 procedure TDesignFrame.AdjustUserInterfaceAnchorsToKeepRect(
5211 const UI: TCastleUserInterface; const RenderRectBeforeChange: TFloatRectangle);
5212 var
5213 NewRect: TFloatRectangle;
5214 begin
5215 // adjust anchors, to preserve previous position
5216 NewRect := UI.RenderRectWithBorder;
5217 if NewRect.IsEmpty or RenderRectBeforeChange.IsEmpty then
5218 begin
5219 { Empty rectangle(s) may happen e.g. if control is empty,
5220 e.g. TCastleLabel.Caption = ''.
5221 To implement AdjustUserInterfaceAnchorsToKeepRect perfectly for this case,
5222 we'd need TCastleUserInterface method like GlobalTranslationEvenIfEmpty,
5223 but it would be a burden to implement it just for this special case.
5224
5225 It seems that not doing anythign is just valid in this case.
5226 At least, user can choose various anchors, and clicking back on original
5227 anchor will (intuitively) restore the control back to where it was.
5228
5229 Note: Resetting "UI.Translation := TVector2.Zero"
5230 wasn't intuitive, see https://github.com/castle-engine/castle-engine/issues/422 .
5231 It would reset the control position when it's not expected.
5232 }
5233 end else
5234 begin
5235 UI.Translation := UI.Translation + Vector2(
5236 (RenderRectBeforeChange.Left - NewRect.Left) / UI.UIScale,
5237 (RenderRectBeforeChange.Bottom - NewRect.Bottom) / UI.UIScale);
5238 end;
5239
5240 ModifiedOutsideObjectInspector('', ucLow);
5241 end;
5242
5243 procedure TDesignFrame.ControlsTreeEndDrag(Sender, Target: TObject; X,
5244 Y: Integer);
5245 begin
5246 ControlsTreeNodeUnderMouse := nil;
5247 ControlsTree.Invalidate; // force custom-drawn look redraw
5248 end;
5249
5250 function TDesignFrame.RenamePossible(const C: TComponent): Boolean;
5251 begin
5252 { Do not allow renaming subcomponents.
5253 It is confusing, since their names live in different namespace
5254 (e.g. Items owned by TCastleViewport), and should not really be used
5255 to access them. }
5256 Result := C.Owner = DesignOwner;
5257 end;
5258
5259 function TDesignFrame.RenameSelectedPossible: Boolean;
5260 begin
5261 { Notes:
5262
5263 - We do not check "GetSelectedComponent <> nil",
5264 as a component may also be selected indirectly by selecting
5265 special tree items "Behaviors" or "Non-Visual Components" underneath.
5266 For rename, it has to be selected directly.
5267
5268 - We do not check "ControlsTree.SelectionCount > 0" or "ControlsTree.Selected <> nil".
5269
5270 We rely on ControlsTreeOneSelected which is also used by rename operation.
5271 Currently it underneath checks "ControlsTree.SelectionCount = 1".
5272 }
5273 Result :=
5274 (ControlsTreeOneSelected <> nil) and
5275 (ControlsTreeOneSelected.Data <> nil) and
5276 RenamePossible(TComponent(ControlsTreeOneSelected.Data));
5277 end;
5278
5279 procedure TDesignFrame.RenameSelectedItem;
5280 begin
5281 if RenameSelectedPossible then
5282 ControlsTreeOneSelected.EditText;
5283 end;
5284
5285 procedure TDesignFrame.ControlsTreeDragDrop(Sender, Source: TObject; X,
5286 Y: Integer);
5287
5288 { Preserve UI or TCastleTransform transformation when changing parent. }
5289 function PreserveTransformation: Boolean;
5290 begin
5291 Result := not (ssCtrl in GetKeyShiftState);
5292 end;
5293
5294 procedure MoveOnlyTreeNodes(
5295 const SrcComponent, DstComponent: TComponent); forward;
5296
5297 { Does Parent contains PotentialChild, searching recursively.
5298 It checks is Parent equal PotentialChild,
5299 and searches Parent's children,
5300 and Parent's children's children etc.
5301
5302 Uses ControlsTree hierarchy knowledge, so it accounts
5303 for all visible in the hierarchy relationships,
5304 e.g. non-visual components may be parents and children of each other,
5305 TCastleUserInterface may be parent of TCastleTransform through
5306 TCastleViewport.Items etc. }
5307 function ContainsRecursive(const Parent, PotentialChild: TComponent): Boolean;
5308 var
5309 ParentNode, PotentialChildNode: TTreeNode;
5310 begin
5311 ParentNode := TreeNodeMap[Parent];
5312 PotentialChildNode := TreeNodeMap[PotentialChild];
5313
5314 while PotentialChildNode <> nil do
5315 begin
5316 if PotentialChildNode = ParentNode then
5317 Exit(true);
5318 PotentialChildNode := PotentialChildNode.Parent;
5319 end;
5320
5321 Result := false;
5322 end;
5323
5324 procedure MoveUserInterface(const Src, Dst: TCastleUserInterface);
5325 var
5326 Index: Integer;
5327 OldRect: TFloatRectangle;
5328 begin
5329 OldRect := Src.RenderRectWithBorder;
5330
5331 case ControlsTreeNodeUnderMouseSide of
5332 tnsInside:
5333 begin
5334 if not ContainsRecursive(Src, Dst) then
5335 begin
5336 if Src.Parent <> nil then
5337 Src.Parent.RemoveControl(Src);
5338 Dst.InsertFront(Src);
5339 if PreserveTransformation then
5340 AdjustUserInterfaceAnchorsToKeepRect(Src, OldRect);
5341 MoveOnlyTreeNodes(Src, Dst);
5342 end;
5343 end;
5344 tnsBottom, tnsTop:
5345 begin
5346 if (Dst.Parent <> nil) and
5347 not ContainsRecursive(Src, Dst.Parent) then
5348 begin
5349 if Src.Parent <> nil then
5350 Src.Parent.RemoveControl(Src);
5351 Index := Dst.Parent.IndexOfControl(Dst);
5352 Assert(Index <> -1);
5353 if ControlsTreeNodeUnderMouseSide = tnsBottom then
5354 Inc(Index);
5355 Dst.Parent.InsertControl(Index, Src);
5356 if PreserveTransformation then
5357 AdjustUserInterfaceAnchorsToKeepRect(Src, OldRect);
5358 MoveOnlyTreeNodes(Src, Dst);
5359 end;
5360 end;
5361 {$ifndef COMPILER_CASE_ANALYSIS}
5362 else raise EInternalError.Create('ControlsTreeDragDrop:ControlsTreeNodeUnderMouseSide?');
5363 {$endif}
5364 end;
5365 ValidateHierarchy;
5366 end;
5367
5368 procedure MoveTransform(const Src, Dst: TCastleTransform);
5369 var
5370 Index: Integer;
5371 FinalPreserveTransformation: Boolean;
5372 WorldPos, WorldDir, WorldUp: TVector3;
5373 begin
5374 FinalPreserveTransformation := PreserveTransformation and
5375 Src.HasWorldTransform and
5376 { Do it only when scale is identity, otherwise GetWorldView/SetWorldView would
5377 not preserve scale. }
5378 TVector3.Equals(ScaleFromMatrix(Src.WorldTransform), NoScale) and
5379 Dst.HasWorldTransform and
5380 TVector3.Equals(ScaleFromMatrix(Dst.WorldTransform), NoScale);
5381 if FinalPreserveTransformation then
5382 Src.GetWorldView(WorldPos, WorldDir, WorldUp);
5383
5384 case ControlsTreeNodeUnderMouseSide of
5385 tnsInside:
5386 begin
5387 if not ContainsRecursive(Src, Dst) then
5388 begin
5389 if Src.Parent <> nil then
5390 Src.Parent.Remove(Src);
5391 Dst.Add(Src);
5392 if FinalPreserveTransformation then
5393 Src.SetWorldView(WorldPos, WorldDir, WorldUp);
5394 MoveOnlyTreeNodes(Src, Dst);
5395 end;
5396 end;
5397 tnsBottom, tnsTop:
5398 begin
5399 if (Dst.Parent <> nil) and
5400 not ContainsRecursive(Src, Dst.Parent) then
5401 begin
5402 if Src.Parent <> nil then
5403 Src.Parent.Remove(Src);
5404 Index := Dst.Parent.List.IndexOf(Dst);
5405 Assert(Index <> -1);
5406 if ControlsTreeNodeUnderMouseSide = tnsBottom then
5407 Inc(Index);
5408 Dst.Parent.Insert(Index, Src);
5409 if FinalPreserveTransformation then
5410 Src.SetWorldView(WorldPos, WorldDir, WorldUp);
5411 MoveOnlyTreeNodes(Src, Dst);
5412 end;
5413 end;
5414 {$ifndef COMPILER_CASE_ANALYSIS}
5415 else raise EInternalError.Create('ControlsTreeDragDrop:ControlsTreeNodeUnderMouseSide?');
5416 {$endif}
5417 end;
5418 ValidateHierarchy;
5419 end;
5420
5421 procedure MoveBehavior(const Src: TCastleBehavior; const Dst: TCastleTransform);
5422 begin
5423 case ControlsTreeNodeUnderMouseSide of
5424 tnsInside:
5425 begin
5426 Src.Parent.RemoveBehavior(Src);
5427 Dst.AddBehavior(Src);
5428 // TODO: update tree in a simple way for now
5429 UpdateDesign;
5430 end;
5431 end;
5432 end;
5433
5434 procedure MoveNonVisual(
5435 const Src: TComponent;
5436 const Dst: TCastleComponent);
5437 var
5438 SrcParentComponent: TCastleComponent;
5439 begin
5440 SrcParentComponent := NonVisualComponentParent(Src);
5441 case ControlsTreeNodeUnderMouseSide of
5442 tnsInside:
5443 begin
5444 SrcParentComponent.RemoveNonVisualComponent(Src);
5445 Dst.AddNonVisualComponent(Src);
5446 // TODO: update tree in a simple way for now
5447 UpdateDesign;
5448 end;
5449 end;
5450 end;
5451
5452 function ViewportItemsNode(const Viewport: TCastleViewport;
5453 const ViewportTreeNode: TTreeNode): TTreeNode;
5454 var
5455 I: Integer;
5456 begin
5457 Assert(TObject(ViewportTreeNode.Data) = Viewport);
5458 Assert(ViewportTreeNode.Data <> nil);
5459 Assert(TObject(ViewportTreeNode.Data) is TCastleViewport);
5460
5461 for I := 0 to ViewportTreeNode.Count - 1 do
5462 if TObject(ViewportTreeNode[I].Data) = Viewport.Items then
5463 Exit(ViewportTreeNode[I]);
5464 raise EInternalError.CreateFmt('No tree node for viewport Items (TCastleTransform) found: %s %s', [
5465 Viewport.Name,
5466 Viewport.ClassName
5467 ]);
5468 end;
5469
5470 { Move only the nodes in TTreeView, and update their captions.
5471 Assumes the move is possible. }
5472 procedure MoveOnlyTreeNodes(
5473 const SrcComponent, DstComponent: TComponent);
5474 var
5475 Src, Dst: TTreeNode;
5476 begin
5477 Src := TreeNodeMap[SrcComponent];
5478 Dst := TreeNodeMap[DstComponent];
5479 case ControlsTreeNodeUnderMouseSide of
5480 tnsInside:
5481 begin
5482 { Special treatment when inserting UI into TCastleViewport,
5483 testcase: try to drag some UI into TCastleViewport (with tnsInside),
5484 it should be added right before "Items" node. }
5485 if (DstComponent is TCastleViewport) and
5486 (SrcComponent is TCastleUserInterface) then
5487 Src.MoveTo(ViewportItemsNode(TCastleViewport(DstComponent), Dst), naInsert)
5488 else
5489 Src.MoveTo(Dst, naAddChild);
5490 end;
5491 tnsBottom:
5492 begin
5493 Src.MoveTo(Dst, naInsertBehind);
5494 end;
5495 tnsTop:
5496 begin
5497 Src.MoveTo(Dst, naInsert);
5498 end;
5499 end;
5500 end;
5501
5502 { Returns @true if List contains some parent of C (but not exactly C). }
5503 function ListIncludesParent(const C: TComponent; const List: TComponentList): Boolean;
5504 var
5505 ListItem: TComponent;
5506 begin
5507 for ListItem in List do
5508 if C <> ListItem then
5509 if ContainsRecursive(ListItem, C) then
5510 Exit(true);
5511 Result := false;
5512 end;
5513
5514 { Handle drag-and-drop from and to ControlsTree, i.e. dragging within
5515 the hierarchy tree. }
5516 procedure DragAndDropFromControlsTree;
5517 var
5518 Dst: TTreeNode;
5519 SrcComponent, DstComponent: TComponent;
5520 SrcComponents: TComponentList;
5521 IgnoredSrcComponentsCount: Integer;
5522 begin
5523 // get destination of drag-and-drop
5524 Dst := ControlsTreeNodeUnderMouse;
5525 DstComponent := TComponent(Dst.Data);
5526
5527 // get and check source of drag-and-drop
5528 GetSelected(SrcComponents, IgnoredSrcComponentsCount, false);
5529 if SrcComponents <> nil then
5530 try
5531 for SrcComponent in SrcComponents do
5532 begin
5533 { Do not process components when their parent is also already on the list. }
5534 if not ListIncludesParent(SrcComponent, SrcComponents) then
5535 { Checking again ControlsTreeAllowDrag is somewhat paranoid:
5536 ControlsTreeDragOver should have checked it already. }
5537 if ControlsTreeAllowDrag(SrcComponent, Dst) then
5538 begin
5539 if (SrcComponent is TCastleUserInterface) and
5540 (DstComponent is TCastleUserInterface) then
5541 begin
5542 MoveUserInterface(
5543 TCastleUserInterface(SrcComponent),
5544 TCastleUserInterface(DstComponent));
5545 end else
5546 if (SrcComponent is TCastleTransform) and
5547 (DstComponent is TCastleTransform) then
5548 begin
5549 MoveTransform(
5550 TCastleTransform(SrcComponent),
5551 TCastleTransform(DstComponent));
5552 end else
5553 if (SrcComponent is TCastleBehavior) and
5554 (DstComponent is TCastleTransform) then
5555 begin
5556 MoveBehavior(
5557 TCastleBehavior(SrcComponent),
5558 TCastleTransform(DstComponent));
5559 end else
5560 if (not ( (SrcComponent is TCastleBehavior) or
5561 (SrcComponent is TCastleTransform) or
5562 (SrcComponent is TCastleUserInterface) ) ) and
5563 (DstComponent is TCastleComponent) then
5564 begin
5565 MoveNonVisual(
5566 SrcComponent,
5567 TCastleComponent(DstComponent));
5568 end;
5569 end;
5570 end;
5571
5572 { Select the SrcComponents.
5573
5574 This is necessary:
5575
5576 - If our movement used TTreeNode.MoveTo and not UpdateDesign.
5577 I.e. it updated ControlsTree smartly, no need to build.
5578
5579 In that case TTreeView.Selected property value
5580 is changed to nil but in TTreeNode.Selected stays true.
5581 This results in inconsistent state.
5582
5583 Possibly this reason is outdated:
5584 our code doesn't use use TTreeView.Selected ever now.
5585 See ControlsTreeOneSelected.
5586
5587 - If our movement used UpdateDesign.
5588
5589 Then selection was lost, we recover it.
5590 }
5591 SetSelected(SrcComponents);
5592
5593 ModifiedOutsideObjectInspector(Format('Drag and drop %d components', [
5594 SrcComponents.Count
5595 ]), ucHigh);
5596 finally FreeAndNil(SrcComponents) end;
5597 end;
5598
5599 procedure DragAndDropFromShellListView(const Source: TCastleShellListView);
5600 begin
5601 if SelectedComponent <> nil then
5602 ShellListAddComponent(Source, SelectedComponent)
5603 else
5604 { TODO: This is never displayed, since Accept=false in this case.
5605 But it's a pity -- we should communicate to user better why drag-and-drop
5606 is not allowed now. }
5607 WritelnWarning('Select a component in hierarchy, to allow to drag-and-drop children into it');
5608 end;
5609
5610 begin
5611 if Source = ControlsTree then
5612 DragAndDropFromControlsTree
5613 else
5614 if Source is TCastleShellListView then
5615 DragAndDropFromShellListView(TCastleShellListView(Source));
5616 end;
5617
5618 procedure TDesignFrame.ControlsTreeAdvancedCustomDrawItem(
5619 Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState;
5620 Stage: TCustomDrawStage; var PaintImages, DefaultDraw: Boolean);
5621 var
5622 C: TCanvas;
5623
5624 procedure DrawTreeNodeUnderMouse;
5625 const
5626 ColorOutline = clBlack;
5627 ColorDecoration = clGray;
5628 var
5629 NodeRect, R: TRect;
5630 begin
5631 NodeRect := Node.DisplayRect(false);
5632
5633 { We can't draw it in cdPrePaint, as after csPrePaint
5634 the node rectangle is cleared anyway.
5635 And we can't draw it in any cdXxxErase, which are not implemented
5636 in LCL (2.1.0). }
5637 C.Pen.Color := ColorOutline;
5638 C.Pen.Style := psDot;
5639 C.Brush.Style := bsClear;
5640 C.Rectangle(NodeRect);
5641
5642 if ControlsTreeNodeUnderMouseSide = tnsInside then
5643 begin
5644 R := NodeRect.SplitRect(srRight, NodeRect.Height);
5645 R.Inflate(-5, -5);
5646 C.Brush.Color := ColorDecoration;
5647 C.Brush.Style := bsSolid;
5648 C.Pen.Color := ColorOutline;
5649 C.Pen.Style := psSolid;
5650 //C.FillRect(R);
5651 C.Polygon([
5652 Point(R.Left , R.Top),
5653 Point(R.Right, R.CenterPoint.Y),
5654 Point(R.Left , R.Bottom)
5655 ]);
5656 end else
5657 begin
5658 if ControlsTreeNodeUnderMouseSide = tnsTop then
5659 R := NodeRect.SplitRect(srTop, 0.1)
5660 else
5661 R := NodeRect.SplitRect(srBottom, 0.1);
5662 R.Left := R.Left + ((Node.Level + 1)* ControlsTree.Indent);
5663
5664 C.Brush.Color := ColorDecoration;
5665 C.Brush.Style := bsSolid;
5666 C.FillRect(R);
5667 end;
5668 end;
5669
5670 procedure DrawTreeNodeClassName(const NodeClassName: String);
5671 var
5672 TextRect: TRect;
5673 begin
5674 TextRect := Node.DisplayRect(true);
5675 C.Brush.Style := bsClear;
5676 C.Font.Color := clLtGray;
5677 C.TextOut(TextRect.Right, TextRect.Top, ' (' + NodeClassName + ')');
5678 end;
5679
5680 begin
5681 C := ControlsTree.Canvas;
5682 DefaultDraw := true;
5683
5684 case Stage of
5685 cdPostPaint:
5686 begin
5687 if Node = ControlsTreeNodeUnderMouse then
5688 DrawTreeNodeUnderMouse;
5689
5690 { When InternalCastleDesignInvalidate, don't trust that pointers
5691 on Node.Data are valid. This may happen if you freed joint,
5692 which also freed associated anchor.
5693
5694 TODO: understand better why this is possible.
5695 After FreeComponentRecursively, we immediately do UpdateDesign
5696 and at that point the InternalCastleDesignInvalidate should be already
5697 resolved? }
5698
5699 if (not InternalCastleDesignInvalidate) and
5700 (Node.Data <> nil) then
5701 DrawTreeNodeClassName(TObject(Node.Data).ClassName);
5702 end;
5703 else ; // nothing to do otherwise
5704 end;
5705 end;
5706
5707 procedure TDesignFrame.CheckParentSelfAnchorsEqualChange(Sender: TObject);
5708 var
5709 UI: TCastleUserInterface;
5710 OldRect: TFloatRectangle;
5711 begin
5712 ParentAnchorsFrame.Visible := not CheckParentSelfAnchorsEqual.Checked;
5713 ParentAnchorsFrame.Enabled := not CheckParentSelfAnchorsEqual.Checked;
5714 if CheckParentSelfAnchorsEqual.Checked then
5715 begin
5716 UI := SelectedUserInterface;
5717 if UI <> nil then
5718 begin
5719 OldRect := UI.RenderRectWithBorder;
5720
5721 UI.HorizontalAnchorParent := UI.HorizontalAnchorSelf;
5722 UI.VerticalAnchorParent := UI.VerticalAnchorSelf;
5723
5724 AdjustUserInterfaceAnchorsToKeepRect(UI, OldRect);
5725
5726 // update also (invisible now) ParentAnchorsFrame UI state
5727 UpdateAnchors(UI, false);
5728 end;
5729 end;
5730 end;
5731
5732 procedure TDesignFrame.ButtonClearTranslationClick(Sender: TObject);
5733 var
5734 UI: TCastleUserInterface;
5735 begin
5736 UI := SelectedUserInterface;
5737 if UI <> nil then
5738 begin
5739 UI.Translation := TVector2.Zero;
5740 ModifiedOutsideObjectInspector('Clear anchor deltas for ' + UI.Name, ucHigh);
5741 end;
5742 end;
5743
5744 procedure TDesignFrame.SimulationPlayStop;
5745 var
5746 NewDesignOwner, NewDesignRoot: TComponent;
5747 SavedSelection: TSavedSelection;
5748 LoadInfo: TInternalComponentLoadInfo;
5749 begin
5750 if InternalCastleApplicationMode in [appSimulation, appSimulationPaused] then
5751 InternalCastleApplicationMode := appDesign
5752 else
5753 InternalCastleApplicationMode := appSimulation;
5754
5755 if CastleApplicationMode = appSimulation then
5756 begin
5757 DesignStateBeforePhysicsRun := ComponentToString(DesignRoot);
5758 DesignModifiedBeforePhysicsRun := FDesignModified;
5759 end else
5760 begin
5761 SavedSelection := GetSavedSelection;
5762
5763 LoadInfo := TInternalComponentLoadInfo.Create;
5764 try
5765 LoadInfo.PreserveDataAcrossUndo := DesignOwner;
5766
5767 NewDesignOwner := TComponent.Create(Self);
5768 NewDesignRoot := InternalStringToComponent(DesignStateBeforePhysicsRun, NewDesignOwner, LoadInfo);
5769 OpenDesign(NewDesignRoot, NewDesignOwner, FDesignUrl);
5770 finally FreeAndNil(LoadInfo) end;
5771
5772 FDesignModified := DesignModifiedBeforePhysicsRun;
5773 OnUpdateFormCaption(Self);
5774
5775 RestoreSavedSelection(SavedSelection);
5776 end;
5777
5778 // TODO: why is this not called automatically?
5779 ActionSimulationPlayStopUpdate(ActionSimulationPlayStop);
5780 ActionSimulationPauseUnpauseUpdate(ActionSimulationPauseUnpause);
5781 end;
5782
5783 procedure TDesignFrame.ShowAllJointsTools;
5784 var
5785 V: TCastleViewport;
5786 BehList: TCastleBehaviorList;
5787 B: TCastleBehavior;
5788 begin
5789 V := CurrentViewport;
5790 if V = nil then Exit;
5791
5792 BehList := V.Items.FindAllBehaviors(TCastleAbstractJoint);
5793 try
5794 for B in BehList do
5795 TCastleAbstractJoint(B).InternalCreateGizmos;
5796 finally FreeAndNil(BehList) end;
5797 end;
5798
5799 procedure TDesignFrame.SimulationPauseUnpause;
5800 begin
5801 if InternalCastleApplicationMode = appSimulationPaused then
5802 InternalCastleApplicationMode := appSimulation
5803 else
5804 if InternalCastleApplicationMode = appSimulation then
5805 InternalCastleApplicationMode := appSimulationPaused;
5806
5807 // TODO: why is this not called automatically?
5808 ActionSimulationPlayStopUpdate(ActionSimulationPlayStop);
5809 ActionSimulationPauseUnpauseUpdate(ActionSimulationPauseUnpause);
5810 end;
5811
5812 procedure TDesignFrame.ActionSimulationPlayStopExecute(Sender: TObject);
5813 begin
5814 SimulationPlayStop;
5815 end;
5816
5817 procedure TDesignFrame.ActionSimulationPlayStopUpdate(Sender: TObject);
5818 begin
5819 if CastleApplicationMode = appDesign then
5820 ActionSimulationPlayStop.ImageIndex := TImageIndex(iiSimulationPlay)
5821 else
5822 ActionSimulationPlayStop.ImageIndex := TImageIndex(iiSimulationStop);
5823 ActionSimulationPlayStop.Checked := CastleApplicationMode in [appSimulation, appSimulationPaused];
5824 end;
5825
5826 procedure TDesignFrame.ActionSimulationPauseUnpauseUpdate(Sender: TObject);
5827 begin
5828 ActionSimulationPauseUnpause.Checked := CastleApplicationMode = appSimulationPaused;
5829 ActionSimulationPauseUnpause.Visible := CastleApplicationMode in [appSimulation, appSimulationPaused];
5830 end;
5831
5832 procedure TDesignFrame.ActionSimulationPauseUnpauseExecute(Sender: TObject);
5833 begin
5834 SimulationPauseUnpause;
5835 end;
5836
5837 procedure TDesignFrame.HideAllJointsTools;
5838 var
5839 V: TCastleViewport;
5840 BehList: TCastleBehaviorList;
5841 B: TCastleBehavior;
5842 begin
5843 V := CurrentViewport;
5844 if V = nil then Exit;
5845
5846 BehList := V.Items.FindAllBehaviors(TCastleAbstractJoint);
5847 try
5848 for B in BehList do
5849 TCastleAbstractJoint(B).InternalDestroyGizmos;
5850 finally FreeAndNil(BehList) end;
5851 end;
5852
5853 procedure TDesignFrame.ActionPlayStopExecute(Sender: TObject);
5854 begin
5855 OnRunningToggle(Self);
5856 end;
5857
5858 procedure TDesignFrame.ActionApiReferenceOfCurrentExecute(Sender: TObject);
5859 begin
5860 OnApiReferenceOfCurrent(Self);
5861 end;
5862
5863 procedure TDesignFrame.ActionPlayStopUpdate(Sender: TObject);
5864 var
5865 IsRunning: Boolean;
5866 begin
5867 IsRunning := OnIsRunning();
5868 if IsRunning then
5869 ActionPlayStop.ImageIndex := TImageIndex(iiStop)
5870 else
5871 ActionPlayStop.ImageIndex := TImageIndex(iiPlay);
5872 ActionPlayStop.Checked := IsRunning;
5873 end;
5874
5875 procedure TDesignFrame.ButtonResetTransformationClick(Sender: TObject);
5876 var
5877 T: TCastleTransform;
5878 begin
5879 T := CurrentTransform;
5880 if T <> nil then
5881 begin
5882 T.Identity;
5883 ModifiedOutsideObjectInspector('Reset transformations for ' + T.Name, ucHigh);
5884 end;
5885 end;
5886
5887 procedure TDesignFrame.ButtonRotateModeClick(Sender: TObject);
5888 begin
5889 if InsideToggleModeClick then Exit;
5890 InsideToggleModeClick := true;
5891 ChangeMode(moRotate);
5892 InsideToggleModeClick := false;
5893 end;
5894
5895 procedure TDesignFrame.ButtonScaleModeClick(Sender: TObject);
5896 begin
5897 if InsideToggleModeClick then Exit;
5898 InsideToggleModeClick := true;
5899 ChangeMode(moScale);
5900 InsideToggleModeClick := false;
5901 end;
5902
5903 procedure TDesignFrame.ButtonSelectModeClick(Sender: TObject);
5904 begin
5905 if InsideToggleModeClick then Exit;
5906 InsideToggleModeClick := true;
5907 ChangeMode(moSelect);
5908 InsideToggleModeClick := false;
5909 end;
5910
5911 procedure TDesignFrame.ButtonTranslateModeClick(Sender: TObject);
5912 begin
5913 if InsideToggleModeClick then Exit;
5914 InsideToggleModeClick := true;
5915 ChangeMode(moTranslate);
5916 InsideToggleModeClick := false;
5917 end;
5918
5919 procedure TDesignFrame.ButtonInteractModeClick(Sender: TObject);
5920 begin
5921 if InsideToggleModeClick then Exit;
5922 InsideToggleModeClick := true;
5923 ChangeMode(moInteract);
5924 InsideToggleModeClick := false;
5925 end;
5926
5927 procedure TDesignFrame.FrameResize(Sender: TObject);
5928
5929 { Buttons on top panel are resized by LCL to have height equal panel height,
5930 but this makes them non-square. Fix them to be square.
5931 Fixes problem observed on Windows. }
5932 procedure FixButtonSquare(const B: TSpeedButton);
5933 begin
5934 if B.Width < B.Height then
5935 B.Constraints.MinWidth := B.Height;
5936 end;
5937
5938 begin
5939 UpdateEditorDataForPropertyEditors;
5940
5941 FixButtonSquare(ButtonInteractMode);
5942 FixButtonSquare(ButtonSelectMode);
5943 FixButtonSquare(ButtonTranslateMode);
5944 FixButtonSquare(ButtonRotateMode);
5945 FixButtonSquare(ButtonScaleMode);
5946 FixButtonSquare(ButtonPlayStop);
5947 FixButtonSquare(ButtonSimulationPlayStop);
5948 FixButtonSquare(ButtonSimulationPause);
5949
5950 { Make ButtonApiReferenceForCurrent square, with size following
5951 LabelControlSelected.Height.
5952 Fixes the button being larger than LabelControlSelected,
5953 which looks bad. }
5954 ButtonApiReferenceForCurrent.Width := LabelControlSelected.Height;
5955 ButtonApiReferenceForCurrent.Height := LabelControlSelected.Height;
5956 end;
5957
5958 procedure TDesignFrame.MenuItemAddComponentClick(Sender: TObject);
5959 var
5960 R: TRegisteredComponent;
5961 begin
5962 R := TRegisteredComponent(Pointer((Sender as TComponent).Tag));
5963 AddComponent(R.ComponentClass, R.OnCreate);
5964 end;
5965
5966 procedure TDesignFrame.MenuTreeViewItemCutClick(Sender: TObject);
5967 begin
5968 CutComponent;
5969 end;
5970
5971 procedure TDesignFrame.MenuTreeViewItemRenameClick(Sender: TObject);
5972 begin
5973 RenameSelectedItem;
5974 end;
5975
5976 procedure TDesignFrame.MenuTreeViewItemDeleteClick(Sender: TObject);
5977 begin
5978 DeleteComponent;
5979 end;
5980
5981 procedure TDesignFrame.MenuTreeViewItemCopyClick(Sender: TObject);
5982 begin
5983 CopyComponent;
5984 end;
5985
5986 procedure TDesignFrame.MenuTreeViewItemPasteClick(Sender: TObject);
5987 begin
5988 PasteComponent;
5989 end;
5990
5991 procedure TDesignFrame.MenuTreeViewItemSaveSelectedClick(Sender: TObject);
5992 begin
5993 SaveSelected;
5994 end;
5995
5996 procedure TDesignFrame.MenuTreeViewPopup(Sender: TObject);
5997
5998 procedure ClearComponentEditorVerbs;
5999 begin
6000 { remove all TMenuItemToExecuteVerb }
6001 while (MenuTreeView.Items.Count > 0) and
6002 (MenuTreeView.Items[0] is TMenuItemToExecuteVerb) do
6003 MenuTreeView.Items[0].Free;
6004
6005 { remove separator }
6006 if (MenuTreeView.Items.Count > 0) and
6007 (MenuTreeView.Items[0].Caption = '-') then
6008 MenuTreeView.Items[0].Free;
6009 end;
6010
6011 procedure AddComponentEditorVerbs(const C: TComponent);
6012 var
6013 E: TBaseComponentEditor;
6014 I: Integer;
6015 MenuItem: TMenuItemToExecuteVerb;
6016 MenuItemSeparator: TMenuItem;
6017 InsertedVerbs: Cardinal;
6018 begin
6019 E := GetComponentEditor(C, FComponentEditorDesigner);
6020 if E <> nil then
6021 begin
6022 InsertedVerbs := 0;
6023 for I := 0 to E.GetVerbCount - 1 do
6024 begin
6025 { Ignore "Create default event" that we couldn't handle now,
6026 as our designer cannot initialize Code Tools to insert the event in code. }
6027 if E.GetVerb(I) = oisCreateDefaultEvent then
6028 Continue;
6029 MenuItem := TMenuItemToExecuteVerb.Create(Self);
6030 MenuItem.Caption := E.GetVerb(I);
6031 MenuItem.VerbIndex := I;
6032 MenuItem.ComponentEditor := E;
6033 MenuItem.ComponentToExecute := C;
6034 MenuTreeView.Items.Insert(InsertedVerbs, MenuItem);
6035 Inc(InsertedVerbs);
6036 end;
6037
6038 { add separator if needed }
6039 if InsertedVerbs <> 0 then
6040 begin
6041 MenuItemSeparator := TMenuItem.Create(Self);
6042 MenuItemSeparator.Caption := '-';
6043 MenuTreeView.Items.Insert(InsertedVerbs, MenuItemSeparator);
6044 end;
6045 end;
6046 end;
6047
6048 var
6049 Sel: TComponent;
6050 CanAddUserInterface, CanAddTransform, CanAddBehavior: Boolean;
6051 begin
6052 Sel := SelectedComponent;
6053
6054 ClearComponentEditorVerbs;
6055 if Sel <> nil then
6056 AddComponentEditorVerbs(Sel);
6057
6058 MenuTreeViewItemRename.Enabled := RenameSelectedPossible;
6059 MenuTreeViewItemDuplicate.Enabled := Sel <> nil;
6060 MenuTreeViewItemCut.Enabled := Sel <> nil;
6061 MenuTreeViewItemCopy.Enabled := Sel <> nil;
6062 MenuTreeViewItemSaveSelected.Enabled := Sel <> nil;
6063 MenuTreeViewItemDelete.Enabled := ControlsTree.SelectionCount > 0; // delete can handle multiple objects
6064
6065 CanAddUserInterface := false;
6066 CanAddTransform := false;
6067 CanAddBehavior := false;
6068
6069 if (Sel is TCastleUserInterface) or ((Sel = nil) and (DesignRoot is TCastleUserInterface)) then
6070 begin
6071 CanAddUserInterface := true;
6072 end else
6073 if (Sel is TCastleTransform) or ((Sel = nil) and (DesignRoot is TCastleTransform)) then
6074 begin
6075 CanAddTransform := true;
6076 CanAddBehavior := true;
6077 end else
6078 if Sel is TCastleBehavior then
6079 begin
6080 CanAddBehavior := true;
6081 end;
6082 // on other components, you can add only NonVisualComponent
6083
6084 MenuTreeViewItemAddUserInterface.SetEnabledVisible(CanAddUserInterface);
6085 MenuTreeViewItemAddTransform.SetEnabledVisible(CanAddTransform);
6086 MenuTreeViewItemAddBehavior.SetEnabledVisible(CanAddBehavior);
6087
6088 // at most one of MenuItemChangeClassXxx is enabled
6089 MenuItemChangeClassUserInterface.SetEnabledVisible(false);
6090 MenuItemChangeClassTransform.SetEnabledVisible(false);
6091 MenuItemChangeClassBehavior.SetEnabledVisible(false);
6092 MenuItemChangeClassNonVisual.SetEnabledVisible(false);
6093 if Sel is TCastleUserInterface then
6094 MenuItemChangeClassUserInterface.SetEnabledVisible(true)
6095 else
6096 if Sel is TCastleTransform then
6097 MenuItemChangeClassTransform.SetEnabledVisible(true)
6098 else
6099 if Sel is TCastleBehavior then
6100 MenuItemChangeClassBehavior.SetEnabledVisible(true)
6101 else
6102 if Sel <> nil then
6103 MenuItemChangeClassNonVisual.SetEnabledVisible(true);
6104
6105 MenuTreeView.PopupComponent := ControlsTree; // I'm not sure what it means, something like menu owner?
6106 end;
6107
6108 procedure TDesignFrame.MenuTreeViewItemDuplicateClick(Sender: TObject);
6109 begin
6110 DuplicateComponent;
6111 end;
6112
6113 procedure TDesignFrame.ViewportSetup2D;
6114 var
6115 V: TCastleViewport;
6116 begin
6117 V := CurrentViewport;
6118 if V = nil then Exit;
6119
6120 V.Setup2D;
6121 ModifiedOutsideObjectInspector('2D Camera And Projection At Runtime: ' + V.Name, ucHigh);
6122 end;
6123
6124 procedure TDesignFrame.ViewportToggleProjection;
6125 var
6126 V: TCastleViewport;
6127 begin
6128 V := CurrentViewport;
6129 if V = nil then Exit;
6130
6131 if V.InternalCamera.ProjectionType = ptPerspective then
6132 V.InternalCamera.ProjectionType := ptOrthographic
6133 else
6134 V.InternalCamera.ProjectionType := ptPerspective;
6135 end;
6136
6137 function TDesignFrame.CameraToSynchronize(const V: TCastleViewport): TCastleCamera;
6138 begin
6139 { Prefer to use camera from CameraPreview, as this is most natural in UI,
6140 because user sees CameraPreview.
6141 Do this even when SelectedTransform is also (maybe different) camera. }
6142 if (CameraPreview <> nil) and
6143 (CameraPreview.SelectedCamera <> nil) and
6144 (CameraPreview.SelectedCamera.World = V.Items) then
6145 Result := CameraPreview.SelectedCamera
6146 else
6147 if (SelectedTransform is TCastleCamera) and
6148 (TCastleCamera(SelectedTransform).World = V.Items) then
6149 Result := TCastleCamera(SelectedTransform)
6150 else
6151 Result := V.Camera;
6152 end;
6153
6154 procedure TDesignFrame.CameraSynchronize(const Source, Target: TCastleCamera; const MakeUndo: Boolean);
6155 var
6156 BeginPos, BeginDir, BeginUp, EndPos, EndDir, EndUp: TVector3;
6157 begin
6158 Target.ProjectionType := Source.ProjectionType;
6159 Target.Perspective.FieldOfView := Source.Perspective.FieldOfView;
6160 Target.Perspective.FieldOfViewAxis := Source.Perspective.FieldOfViewAxis;
6161 Target.Orthographic.Origin := Source.Orthographic.Origin;
6162 Target.Orthographic.Width := Source.Orthographic.Width;
6163 Target.Orthographic.Height := Source.Orthographic.Height;
6164
6165 Target.GetWorldView(BeginPos, BeginDir, BeginUp);
6166 Source.GetWorldView(EndPos, EndDir, EndUp);
6167
6168 { Instead of using FixCamera2D, just explicitly force Z values to be unchanged. }
6169 if (Source.ProjectionType = ptOrthographic) and
6170 TVector3.Equals(EndDir, Vector3(0, 0, -1)) and
6171 TVector3.Equals(EndUp, Vector3(0, 1, 0)) then
6172 begin
6173 EndPos.Z := BeginPos.Z;
6174 end;
6175
6176 if MakeUndo then
6177 begin
6178 { To record undo for Target camera pos/dir/up, we do a little trick.
6179 As we want to animate using AnimateTo, but we want to record undo state
6180 with already final pos/dir/up, so we *temporarily* adjust Target instantly
6181 to Source pos/dir/up. }
6182 Target.SetWorldView(EndPos, EndDir, EndUp);
6183 ModifiedOutsideObjectInspector('Align Camera To View: ' + Target.Name, ucHigh);
6184 // restore Target to begin positions, to animate to it
6185 Target.SetWorldView(BeginPos, BeginDir, BeginUp);
6186 end;
6187
6188 Target.AnimateTo(EndPos, EndDir, EndUp, CameraTransitionTime);
6189 end;
6190
6191 procedure TDesignFrame.ViewportAlignViewToCamera;
6192 var
6193 V: TCastleViewport;
6194 C: TCastleCamera;
6195 begin
6196 V := CurrentViewport;
6197 if V = nil then Exit;
6198
6199 C := CameraToSynchronize(V);
6200 if C <> nil then
6201 CameraSynchronize(C, V.InternalCamera, false);
6202 end;
6203
6204 procedure TDesignFrame.ViewportAlignCameraToView;
6205 var
6206 V: TCastleViewport;
6207 C: TCastleCamera;
6208 begin
6209 V := CurrentViewport;
6210 if V = nil then Exit;
6211
6212 C := CameraToSynchronize(V);
6213 if C <> nil then
6214 CameraSynchronize(V.InternalCamera, C, true);
6215 end;
6216
6217 procedure TDesignFrame.UpdateColliders(T: TCastleTransform);
6218 var
6219 BehList: TCastleBehaviorList;
6220 V: TCastleViewport;
6221 B: TCastleBehavior;
6222 begin
6223 if T = nil then
6224 begin
6225 V := CurrentViewport;
6226 if V = nil then Exit;
6227 T := V.Items;
6228 end;
6229
6230 BehList := T.FindAllBehaviors(TCastleCollider);
6231 try
6232 for B in BehList do
6233 if FShowColliders then
6234 TCastleCollider(B).InternalDesigningBegin
6235 else
6236 TCastleCollider(B).InternalDesigningEnd;
6237 finally FreeAndNil(BehList) end;
6238 end;
6239
6240 {
6241 function TDesignFrame.SelectionSave: Classes.TList;
6242 var
6243 I: Integer;
6244 begin
6245 Result := Classes.TList.Create;
6246 Result.Count := ControlsTree.SelectionCount;
6247 for I := 0 to Result.Count - 1 do
6248 Result[I] := ControlsTree.Selections[I];
6249 end;
6250
6251 procedure TDesignFrame.SelectionRestoreAndFree(var Selection: Classes.TList);
6252 begin
6253 ControlsTree.Select(Selection);
6254 FreeAndNil(Selection);
6255 end;
6256 }
6257
6258 procedure TDesignFrame.SetParent(AParent: TWinControl);
6259 {$ifdef LCLwin32}
6260 var
6261 H: Integer;
6262 InspectorType: TInspectorType;
6263 {$endif}
6264 begin
6265 inherited SetParent(AParent);
6266 {$ifdef LCLwin32}
6267 // fix height of rows of object inspector
6268 if AParent <> nil then
6269 begin
6270 H := Canvas.TextHeight('Wg') + 4;
6271 for InspectorType in TInspectorType do
6272 Inspector[InspectorType].DefaultItemHeight := H;
6273 end;
6274 {$endif}
6275 end;
6276
6277 procedure TDesignFrame.UpdateAnchors(const UI: TCastleUserInterface;
6278 const AllowToHideParentAnchorsFrame: Boolean);
6279 begin
6280 SelfAnchorsFrame.HorizontalAnchor := UI.HorizontalAnchorSelf;
6281 SelfAnchorsFrame.VerticalAnchor := UI.VerticalAnchorSelf;
6282 ParentAnchorsFrame.HorizontalAnchor := UI.HorizontalAnchorParent;
6283 ParentAnchorsFrame.VerticalAnchor := UI.VerticalAnchorParent;
6284
6285 if AllowToHideParentAnchorsFrame then
6286 begin
6287 CheckParentSelfAnchorsEqual.Checked :=
6288 (UI.HorizontalAnchorSelf = UI.HorizontalAnchorParent) and
6289 (UI.VerticalAnchorSelf = UI.VerticalAnchorParent);
6290 { The above will automatically call CheckParentSelfAnchorsEqualChanged,
6291 if Checked just changed. }
6292 end;
6293 end;
6294
6295 procedure TDesignFrame.ChangeMode(const NewMode: TMode);
6296 begin
6297 Mode := NewMode;
6298
6299 ButtonInteractMode.Down := Mode = moInteract;
6300 ButtonSelectMode.Down := Mode = moSelect;
6301 ButtonTranslateMode.Down := Mode = moTranslate;
6302 ButtonRotateMode.Down := Mode = moRotate;
6303 ButtonScaleMode.Down := Mode = moScale;
6304
6305 case Mode of
6306 moTranslate: VisualizeTransformSelected.Operation := voTranslate;
6307 moRotate: VisualizeTransformSelected.Operation := voRotate;
6308 moScale: VisualizeTransformSelected.Operation := voScale;
6309 else VisualizeTransformSelected.Operation := voSelect;
6310 end;
6311 end;
6312
6313 procedure TDesignFrame.ModifiedOutsideObjectInspector(const UndoComment: String;
6314 const UndoCommentPriority: TUndoCommentPriority; const UndoOnRelease: Boolean = false);
6315 var
6316 InspectorType: TInspectorType;
6317 begin
6318 // TODO: this moves UI scrollbar up,
6319 // TODO: this is not optimized
6320 // (PropertyGridModified does some unnecessary things if we only changed size)
6321
6322 for InspectorType in TInspectorType do
6323 Inspector[InspectorType].RefreshPropertyValues;
6324 // do not call PropertyGridModified if nothing selected, e.g. after delete operation
6325 if ControlsTree.SelectionCount <> 0 then
6326 PropertyGridModified(nil);
6327
6328 MarkModified;
6329
6330 if UndoOnRelease then
6331 UndoSystem.ScheduleRecordUndoOnRelease := true
6332 else
6333 RecordUndo(UndoComment, UndoCommentPriority); //it will overwrite Undo recorded in PropertyGridModified with a better comment
6334 end;
6335
6336 procedure TDesignFrame.NewDesign(const ComponentClass: TComponentClass;
6337 const ComponentOnCreate: TNotifyEvent);
6338 var
6339 NewRoot: TComponent;
6340 NewDesignOwner: TComponent;
6341 begin
6342 NewDesignOwner := TComponent.Create(Self);
6343
6344 NewRoot := ComponentClass.Create(NewDesignOwner);
6345 if Assigned(ComponentOnCreate) then
6346 ComponentOnCreate(NewRoot);
6347 NewRoot.Name := ProposeComponentName(ComponentClass, NewDesignOwner);
6348
6349 { In these special cases, set FullSize to true,
6350 since this is almost certainly what user wants when creating a new UI
6351 that has this component class as root. }
6352 if (ComponentClass = TCastleUserInterface) or
6353 (ComponentClass = TCastleRectangleControl) then
6354 (NewRoot as TCastleUserInterface).FullSize := true;
6355
6356 UndoSystem.ClearUndoHistory;
6357
6358 OpenDesign(NewRoot, NewDesignOwner, '');
6359
6360 RecordUndo('Start new design', High(TUndoCommentPriority)); // This Undo comment is never seen
6361 end;
6362
6363 procedure TDesignFrame.ReleaseAllKeysAndMouse;
6364 begin
6365 CastleControl.ReleaseAllKeysAndMouse;
6366 end;
6367
6368 procedure TDesignFrame.FocusDesign;
6369 begin
6370 { Note that we ignore this call when CastleControl is disabled or invisible.
6371 Otherwise SetFocus would raise an error: understandably, we cannot focus
6372 disabled or invisible control.
6373 Ignoring it here prevents errors at "Escape" key or Undo when the design
6374 is non-visual (like sounds.castle-component). }
6375 if CastleControl.Enabled and CastleControl.Visible then
6376 CastleControl.SetFocus;
6377 end;
6378
6379 procedure TDesignFrame.FindToggle;
6380 begin
6381 FindActive := not FindActive;
6382 SetEnabledVisible(EditFindInHierarchy, FindActive);
6383 if FindActive then
6384 begin
6385 EditFindInHierarchy.Text := ''; // clear edit when showing it
6386 // Note: SetFocus must be done after making it enabled, otherwise exception is raised
6387 EditFindInHierarchy.SetFocus;
6388 end;
6389 end;
6390
6391 procedure TDesignFrame.EditFindInHierarchyChange(Sender: TObject);
6392 var
6393 LowerFindText: String;
6394 TreeNode: TTreeNode;
6395 C: TComponent;
6396 begin
6397 if FindActive and (EditFindInHierarchy.Text <> '') then
6398 begin
6399 LowerFindText := LowerCase(EditFindInHierarchy.Text);
6400
6401 TreeNode := ControlsTree.Items.GetFirstNode;
6402 while TreeNode <> nil do
6403 begin
6404 C := SelectedFromNode(TreeNode, false);
6405 if (C <> nil) and (Pos(LowerFindText, LowerCase(C.Name)) <> 0) then
6406 begin
6407 SelectedComponent := C;
6408 Exit;
6409 end;
6410 TreeNode := TreeNode.GetNext;
6411 end;
6412
6413 Beep; // nothing found
6414 end;
6415 end;
6416
6417 procedure TDesignFrame.FindNext;
6418 var
6419 LowerFindText: String;
6420 TreeNode: TTreeNode;
6421 Sel, C: TComponent;
6422 SeenSelection: Boolean;
6423 begin
6424 if FindActive and (EditFindInHierarchy.Text <> '') then
6425 begin
6426 if SelectedComponent = nil then
6427 begin
6428 { try to find first match }
6429 EditFindInHierarchyChange(nil)
6430 end else
6431 begin
6432 Sel := GetSelectedComponent(false);
6433 LowerFindText := LowerCase(EditFindInHierarchy.Text);
6434
6435 // first pass: go to selected component, find first match after it
6436 SeenSelection := false;
6437
6438 TreeNode := ControlsTree.Items.GetFirstNode;
6439 while TreeNode <> nil do
6440 begin
6441 C := SelectedFromNode(TreeNode, false);
6442
6443 if SeenSelection and
6444 (C <> nil) and
6445 (Pos(LowerFindText, LowerCase(C.Name)) <> 0) then
6446 begin
6447 SelectedComponent := C;
6448 Exit;
6449 end;
6450 if C = Sel then
6451 SeenSelection := true;
6452
6453 TreeNode := TreeNode.GetNext;
6454 end;
6455
6456 // no match found after selected component, search from the beginning
6457
6458 if not SeenSelection then
6459 begin
6460 WritelnWarning('Not found SelectedComponent %s among tree nodes, something is wrong', [Sel.Name]);
6461 Exit;
6462 end;
6463
6464 TreeNode := ControlsTree.Items.GetFirstNode;
6465 while TreeNode <> nil do
6466 begin
6467 C := SelectedFromNode(TreeNode, false);
6468
6469 if C = Sel then
6470 begin
6471 // we reached selection again, so no next match found
6472 Exit;
6473 end;
6474
6475 if (C <> nil) and (Pos(LowerFindText, LowerCase(C.Name)) <> 0) then
6476 begin
6477 SelectedComponent := C;
6478 Exit;
6479 end;
6480
6481 TreeNode := TreeNode.GetNext;
6482 end;
6483 end;
6484 end;
6485 end;
6486
6487 initialization
6488 { Enable using our property edits e.g. for TCastleScene.URL }
6489 CastlePropEdits.Register;
6490 CastleEditorPropEdits.Register;
6491
6492 { Inside CGE editor,
6493 - CastleApplicationMode is never appRunning,
6494 - so CastleDesignMode is always true. }
6495 InternalCastleApplicationMode := appDesign;
6496
6497 { Inside CGE editor, file monitor is always enabled. }
6498 FileMonitor.MakePossiblyEnabled;
6499 FileMonitor.Enabled := true;
6500 end.