Debian Codegraph @

tools/castle-editor/code/designundosystem.pas

raw
1 {
2 Copyright 2020-2022 Yevhen Loza, 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 { An undo system that handles:
17 Recording the changes made to the designed Scene
18 Performing Undo/Redo actions based on current undo history }
19 unit DesignUndoSystem;
20
21 interface
22
23 uses
24 Classes, Generics.Collections,
25 CastleUtils,
26 EditorUtils;
27
28 type
29 TUndoCommentPriority = (
30 { Low priority comments will get overwritten by a higher priority comments
31 which correspond to a more specific description of what has happened,
32 but are not always available. }
33 ucLow,
34 { High priority comments usually describe what exactly happened
35 and should overwrite less specific comments. }
36 ucHigh
37 );
38
39
40 type
41 { Content of the Undo record.
42 We might want to change it in future, most likely make several types of data
43 that can be recorded as undo events }
44 TUndoData = String;
45
46 type
47 { A single change in scene content. }
48 TUndoHistoryElement = class(TObject)
49 { Content of this undo. }
50 Data: TUndoData;
51 Selection: TSavedSelection;
52 { Human-readable explanation of what action is recorded in this undo record. }
53 Comment: String;
54 { Estimate of this undo record size;
55 It may be several bytes inaccurate,
56 but it's used only to avoid exceeding some preset RAM limit. }
57 function Size: SizeInt;
58 end;
59
60 type
61 { All undo records currently availalbe. }
62 TUndoHistory = specialize TObjectList<TUndoHistoryElement>;
63
64 type
65 { Manages undo records and performs undo/redo. }
66 TUndoSystem = class(TComponent)
67 //private const MaxUndo = 50;
68 { Max amount of memory that can be reserved by Undo System.
69 If the current records total size overruns this limit,
70 the fist undo records will be purged.
71 Maybe we'll want to have it as user-definable variable in Castle-Editor settings. }
72 private const MaxUndoHistorySize = 128 * 1024 * 1024; //128 Mb
73 private
74 { Current undo step,
75 equals to the last element of the Undo History, unless an undo has been performed. }
76 CurrentUndo: Integer;
77 { Current undo element priority,
78 new undo record with identical data but higher priority
79 can overwrite undo record with lower priority.
80 This is required because often we receive several identical undo records
81 for the same user action, some of them may have a "better" (i.e. more specific) comment
82 which should overwrite the previous (or following) less specific comments. }
83 CurrentUndoCommentPriority: TUndoCommentPriority;
84 { All undo records in this session. }
85 UndoHistory: TUndoHistory;
86 { Calculates total size of RAM used by the Undo History. }
87 function UndoHistorySize: Integer;
88 public
89 { Called when Undo information displayed to the User should be changed. }
90 OnUpdateUndo: TNotifyEvent;
91 { Should the Undo be recorded on Release event?
92 Note, that we rely here on Release event, which may never come in case
93 user has switched a window (e.g. with Alt-Tab) while dragging.
94 This value will be purged when recording a new Undo record. }
95 ScheduleRecordUndoOnRelease: Boolean;
96 { Verbose log to WritelnLog. }
97 VerboseLog: Boolean;
98 constructor Create(AOwner: TComponent); override;
99 destructor Destroy; override;
100 { Should be called after every significant change, including initial loading of the design. }
101 { Try to record a new Undo record.
102 If several actions have been undone before, all the redo history will be cleared at this moment.
103 If the new Undo record is equal to the recorded one then nothing will be recorded. }
104 procedure RecordUndo(const UndoData: TUndoData; const SavedSelection: TSavedSelection; const UndoComment: String;
105 const UndoCommentPriority: TUndoCommentPriority);
106 { Get a recent state change and move one step backwards in Undo History. }
107 function Undo: TUndoHistoryElement;
108 { Get a state change following current state and move one step fowrard in Undo History. }
109 function Redo: TUndoHistoryElement;
110 { Is it possible to perform Undo right now? }
111 function IsUndoPossible: Boolean;
112 { Is it possible to perform Redo right now? }
113 function IsRedoPossible: Boolean;
114 { Get comment for Undo action if it's possible, or return ''. }
115 function UndoComment: String;
116 { Get comment for Redo action if it's possible, or return ''. }
117 function RedoComment: String;
118 { Clear all Undo History. }
119 procedure ClearUndoHistory;
120 { Log, following VerboseLog flag. }
121 procedure DoLog(const S: String);
122 procedure DoLog(const SPattern: String; const Args: array of const);
123 end;
124
125 implementation
126 uses
127 SysUtils,
128 CastleComponentSerialize, CastleLog, CastleStringUtils;
129
130 function TUndoHistoryElement.Size: SizeInt;
131
132 { See https://www.freepascal.org/docs-html/ref/refsu13.html
133 I'm not sure if this includes size of string pointer or not.
134 Note that Length(AnsiString) returns length of the string in bytes, not in UTF8 characters. }
135 function SizeOfAnsiString(const S: String): SizeInt;
136 const
137 HS = 16;
138 begin
139 Result := Length(S) + 1 + HS;
140 end;
141
142 begin
143 Result := Self.InstanceSize +
144 SizeOfAnsiString(Data) +
145 SizeOfAnsiString(Selection.SelectedComponent) +
146 SizeOfAnsiString(Comment);
147 end;
148
149 constructor TUndoSystem.Create(AOwner: TComponent);
150 begin
151 inherited;
152 UndoHistory := TUndoHistory.Create(true);
153 ClearUndoHistory;
154 end;
155
156 destructor TUndoSystem.Destroy;
157 begin
158 FreeAndNil(UndoHistory);
159 inherited;
160 end;
161
162 function TUndoSystem.UndoHistorySize: Integer;
163 var
164 U: TUndoHistoryElement;
165 begin
166 Result := 0;
167 for U in UndoHistory do
168 Result += U.Size;
169 end;
170
171 procedure TUndoSystem.RecordUndo(const UndoData: TUndoData; const SavedSelection: TSavedSelection;
172 const UndoComment: String;
173 const UndoCommentPriority: TUndoCommentPriority);
174 var
175 NewUndoElement: TUndoHistoryElement;
176 NewUndoHistorySize: Integer;
177 begin
178 ScheduleRecordUndoOnRelease := false;
179 if (UndoHistory.Count > 0) and (UndoData = UndoHistory[CurrentUndo].Data) then
180 begin
181 if not TSavedSelection.Equals(SavedSelection, UndoHistory[CurrentUndo].Selection) then
182 begin
183 DoLog('New Undo is identical to previous Undo record. Only selection has changed. This change has been saved.');
184 UndoHistory[CurrentUndo].Selection := SavedSelection;
185 OnUpdateUndo(Self);
186 end;
187 if (UndoCommentPriority > CurrentUndoCommentPriority) then
188 begin
189 DoLog('Overwriting previous Undo record "' + UndoHistory[CurrentUndo].Comment +
190 '" with a higher priority comment: "' + UndoComment + '".');
191 UndoHistory[CurrentUndo].Comment := UndoComment;
192 OnUpdateUndo(Self); // It is safe to call OnUpdateUndo multiple times - it only updates menu captions
193 end;
194 Exit;
195 end;
196
197 DoLog('Saving Undo record. CurrentUndo = ' + IntToStr(CurrentUndo));
198 // Clean all next undo records if available;
199 UndoHistory.Count := CurrentUndo + 1;
200 // Add new UndoElement
201 NewUndoElement := TUndoHistoryElement.Create;
202 NewUndoElement.Data := UndoData;
203 NewUndoElement.Selection := SavedSelection;
204 NewUndoElement.Comment := UndoComment;
205 UndoHistory.Add(NewUndoElement);
206 Inc(CurrentUndo);
207 CurrentUndoCommentPriority := UndoCommentPriority;
208
209 Assert(UndoHistory.Count - 1 = CurrentUndo);
210 // Make sure Undo doesn't consume too much RAM
211 {if CurrentUndo > MaxUndo then
212 begin
213 UndoHistory.Delete(0);
214 Dec(CurrentUndo);
215 end;}
216 NewUndoHistorySize := UndoHistorySize;
217 while (NewUndoHistorySize > MaxUndoHistorySize) and (UndoHistory.Count > 1) do
218 begin
219 NewUndoHistorySize -= UndoHistory[0].Size;
220 UndoHistory.Delete(0);
221 Dec(CurrentUndo);
222 end;
223 Assert(UndoHistorySize = NewUndoHistorySize);
224 OnUpdateUndo(Self);
225 DoLog('Undo record saved. CurrentUndo = ' + IntToStr(CurrentUndo) + '; Undo History Size = ' + SizeToStr(NewUndoHistorySize));
226 end;
227
228 function TUndoSystem.Undo: TUndoHistoryElement;
229 begin
230 ScheduleRecordUndoOnRelease := false;
231 if IsUndoPossible then
232 begin
233 DoLog('Performing Undo from ' + IntToStr(CurrentUndo) + ' to ' + IntToStr(CurrentUndo - 1));
234 Dec(CurrentUndo);
235 Result := UndoHistory[CurrentUndo];
236 CurrentUndoCommentPriority := High(TUndoCommentPriority); // Whatever happens next this Undo record cannot be overwritten
237 OnUpdateUndo(Self);
238 end else
239 raise EInternalError.Create('Undo was requested but undo is not possible');
240 end;
241
242 function TUndoSystem.Redo: TUndoHistoryElement;
243 begin
244 ScheduleRecordUndoOnRelease := false;
245 if IsRedoPossible then
246 begin
247 DoLog('Performing Redo from ' + IntToStr(CurrentUndo) + ' to ' + IntToStr(CurrentUndo + 1));
248 Inc(CurrentUndo);
249 Result := UndoHistory[CurrentUndo];
250 CurrentUndoCommentPriority := High(TUndoCommentPriority); // Whatever happens next this Undo record cannot be overwritten
251 OnUpdateUndo(Self);
252 end else
253 raise EInternalError.Create('Redo was requested but redo is not possible');
254 end;
255
256 function TUndoSystem.IsUndoPossible: Boolean;
257 begin
258 Result := CurrentUndo > 0;
259 end;
260
261 function TUndoSystem.IsRedoPossible: Boolean;
262 begin
263 Result := CurrentUndo < UndoHistory.Count - 1;
264 end;
265
266 function TUndoSystem.RedoComment: String;
267 begin
268 if IsRedoPossible then
269 begin
270 if UndoHistory[CurrentUndo + 1].Comment = '' then
271 Result := 'Redo'
272 else
273 Result := 'Redo: ' + UndoHistory[CurrentUndo + 1].Comment;
274 end else
275 Result := 'Redo';
276 end;
277
278 function TUndoSystem.UndoComment: String;
279 begin
280 if IsUndoPossible then
281 begin
282 if UndoHistory[CurrentUndo].Comment = '' then
283 Result := 'Undo'
284 else
285 Result := 'Undo: ' + UndoHistory[CurrentUndo].Comment;
286 end else
287 Result := 'Undo';
288 end;
289
290 procedure TUndoSystem.ClearUndoHistory;
291 begin
292 ScheduleRecordUndoOnRelease := false;
293 UndoHistory.Clear;
294 CurrentUndo := -1;
295 CurrentUndoCommentPriority := High(TUndoCommentPriority); // Just for consistency
296 if Assigned(OnUpdateUndo) then
297 OnUpdateUndo(Self);
298 DoLog('Clearing Undo hisotry.');
299 end;
300
301 procedure TUndoSystem.DoLog(const S: String);
302 begin
303 if VerboseLog then
304 WriteLnLog(S);
305 end;
306
307 procedure TUndoSystem.DoLog(const SPattern: String; const Args: array of const);
308 begin
309 DoLog(Format(SPattern, Args));
310 end;
311
312 end.