Debian Codegraph @

src/deprecated_units/castleprogress.pas

raw
1 {
2 Copyright 2002-2022 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 { Progress bar functionality (TProgress, global variable Progress). }
17 unit CastleProgress
18 deprecated 'use TCastleView and WaitForRenderAndCall to display progress of loading operations';
19
20 {$I castleconf.inc}
21
22 { Define this only for testing }
23 { $define TESTING_PROGRESS_DELAY}
24
25 interface
26
27 uses SysUtils, CastleUtils, CastleTimeUtils;
28
29 type
30 TProgress = class;
31
32 { Abstract user interface of the progress bar.
33 See @link(TProgress) for information how to use progress bars. }
34 TProgressUserInterface = class
35 private
36 FBarYPosition: Single;
37 FImage: TObject;
38 FOwnsImage: boolean;
39 procedure SetImage(const Value: TObject);
40 public
41 const
42 DefaultBarYPosition = 0.5;
43
44 constructor Create;
45 destructor Destroy; override;
46
47 { Image displayed as a background of the progress bar.
48
49 Not all progress bar interfaces support it, some simply ignore it.
50 You can leave it @nil, then the interface will use whatever is suitable
51 (e.g. capture screen contents each time the progress bar starts).
52
53 Whether the image assigned here is "owned" (that is, "automatically
54 freed") by TProgressUserInterface instance depends on OwnsImage.
55 In any case, we don't modify the image
56 (if we need to resize it to fit the screen size,
57 we do it on a temporary copy).
58
59 The type of this must be @link(CastleImages.TRGBImage), but it cannot
60 be declared as such here, we want this unit to be part of base
61 units, not dependent on images. }
62 property Image: TObject read FImage write SetImage;
63 property OwnsImage: boolean read FOwnsImage write FOwnsImage default false;
64
65 { Vertical position of the displayed progress bar.
66 This feature is supposed to indicate a suitable free space on the
67 background @link(Image) where we can nicely fit the progress bar UI.
68
69 Not all progress bar interfaces support it, some simply ignore it.
70
71 0 means the middle of progress bar is at the bottom of the image,
72 1 means at the top. 0.5 indicates the middle, and it's the default. }
73 property BarYPosition: Single read FBarYPosition write FBarYPosition
74 {$ifdef FPC} default DefaultBarYPosition {$endif};
75
76 { Deprecated name for BarYPosition. }
77 property ImageBarYPosition: Single read FBarYPosition write FBarYPosition
78 {$ifdef FPC} default DefaultBarYPosition; deprecated {$endif};
79
80 { Show progress bar. }
81 procedure Init(Progress: TProgress); virtual; abstract;
82 { Update progress bar (because Progress.Position changed). }
83 procedure Update(Progress: TProgress); virtual; abstract;
84 { Hide progress bar. }
85 procedure Fini(Progress: TProgress); virtual; abstract;
86 end;
87
88 { Progress bar functionality.
89
90 This provides the functionality of a progress bar (everything that
91 wants to signal progress should call @link(Progress) methods),
92 but not the actual user interface. The user interface is "pluggable",
93 that is you assign something to the Progress.UserInterface property.
94 See the units:
95
96 @unorderedList(
97 @itemSpacing Compact
98 @item(CastleWindowProgress --- show progress bar in OpenGL window)
99 @item(CastleProgressConsole --- show progress bar on StdErr)
100 @item(And you can also implement progress handling yourself,
101 e.g. using Lazarus form or using Lazarus progress bar on existing form.)
102 )
103
104 This way any unit that implements some lengthy operation can call
105 appropriate functions of the @link(Progress) object. And the final program
106 can choose how it wants to show that progress to user (in console?
107 in OpenGL window? etc.).
108
109 Usage example:
110
111 @longcode(#
112 Progress.UserInterface := ... some TProgressUserInterface instance ...;
113 ...
114 Progress.Init(100, 'Doing something time-consuming, please wait');
115 try
116 for i := 1 to 100 do
117 begin
118 ... do something ...
119 Progress.Step;
120 end;
121 finally Progress.Fini; end;
122 #)
123
124 Using @code("try ... finally ... end") above is not strictly required,
125 but is strongly suggested. Rule of thumb says to always call
126 Progress.Fini when you called Progress.Init.
127
128 The @link(TProgress.Step) is implemented such that you don't have to
129 worry about calling it too often. We will not update the interface
130 (@link(TProgressUserInterface.Update)) too often,
131 see TProgress.UpdatePart and TProgress.UpdateDelay for details.
132
133 This unit creates one instance of the class @link(TProgress): @link(Progress).
134 Usually this is what you want to use. For complicated cases,
135 you can create and pass around more instances
136 (e.g. from different threads, each @link(TProgress) object displaying
137 it's state in a separate window.) }
138 TProgress = class
139 private
140 FUserInterface: TProgressUserInterface;
141 FUpdatePart: Cardinal;
142 FUpdateDelay: TFloatTime;
143
144 FMax, FPosition: Cardinal;
145 { Variables below are meaningfull only if Active.
146
147 When UserInterfaceDelayed, this is the time and position (always 0)
148 of the TProgress.Init call.
149 When not UserInterfaceDelayed, this is the time and position
150 of the last TProgress.Init or TProgress.Update call. }
151 LastUpdatePos: Cardinal;
152 LastUpdateTime: TTimerResult;
153 UserInterfaceDelayed: boolean;
154
155 FTitle: string;
156 FActive: boolean;
157 procedure SetPosition(const Value: Cardinal);
158 public
159 const
160 { }
161 DefaultUpdatePart = {$ifdef TESTING_PROGRESS_DELAY} 100000000 {$else} 100 {$endif};
162 DefaultUpdateDelay = {$ifdef TESTING_PROGRESS_DELAY} 0 {$else} 0.25 {$endif};
163
164 property UserInterface: TProgressUserInterface
165 read FUserInterface write FUserInterface;
166
167 { Define how often to redraw interface (TProgressUserInterface.Update).
168 Position must change by (1/UpdatePart) * Max and at the same time
169 at least UpdateDelay seconds must pass to redraw.
170
171 This allows you to call @link(Step) very often, without worrying
172 that you cause redraw too often (which would cause slowdown).
173
174 UpdateDelay default value is DefaultUpdateDelay.
175 @groupBegin }
176 property UpdatePart: Cardinal read FUpdatePart write FUpdatePart
177 default DefaultUpdatePart;
178 property UpdateDelay: TFloatTime read FUpdateDelay write FUpdateDelay;
179 { @groupEnd }
180
181 { Current Position of the progress bar.
182 Always >= 0 and <= @link(Max).
183
184 You can set this property only when @link(Active).
185 Setting it to something > @link(Max) will be silently clamped to @link(Max).
186 You can only increase it (trying to decrease it will be silently
187 ignored, which is useful if your position information is only an
188 approximation).
189 In other words, setthing this property is equivalent
190 to appropriate @link(Step) call. }
191 property Position: Cardinal read FPosition write SetPosition;
192 property Max: Cardinal read FMax;
193 property Title: string read FTitle;
194
195 { Are we between Init and Fini calls.
196 Init changes Active to true, Fini changes Active to false. }
197 property Active: boolean read FActive;
198
199 { Start the progress bar.
200 You can call Init only when Active = false (that is, you
201 cannot Init while another progress is working).
202 Initializes @link(Max), @link(Title), sets @link(Position) to 0 and
203 changes @link(Active) to true.
204
205 UserInterface must be initialized (non-nil) when calling
206 Init, and you cannot change UserInterface when progress is Active
207 (i.e. before you call Fini).
208
209 If DelayUserInterface is set to @true, a very useful optimization
210 is performed: TProgress.Init will not
211 immediately result in TProgressUserInterface.Init call.
212 Instead, actual initialization of the interface will be delayed
213 until some TProgress.Update, when UpdateDelay time will pass.
214
215 The advantage of DelayUserInterface is that if
216 an operation will take a very short time, we will not waste
217 time on possibly lengthy initialization of the progress bar
218 interface. For example, CastleWindowProgress may have to capture OpenGL screen
219 at the initialization, which takes a noticeable fraction of second
220 by itself. So it's not sensible to init CastleWindowProgress if an entire
221 operation between Progress.Init and Fini will take only 0.001 of second..
222
223 The only downside of DelayUserInterface is that it's not applicable
224 to an operation with very few steps (e.g. 1) that may take a long time.
225 If a time between Init and the first Update or Fini is really large,
226 the progress bar will not be visible. }
227 procedure Init(AMax: Cardinal; const ATitle: string;
228 const DelayUserInterface: boolean = false);
229
230 { Increments progress bar @link(Position) by @code(StepSize).
231 Use only when @link(Active), that is between @link(Init) and @link(Fini)
232 calls.
233
234 @link(Position) always stays <= @link(Max) (you can depend on this
235 when implementaing TProgressUserInterface descendants).
236 But it is legal to try to raise @link(Position) above
237 @link(Max) by using this method, we will silently clamp @link(Position)
238 to @link(Max).
239 This is usefull when given @link(Max) was only an approximation of needed
240 steps. }
241 procedure Step(StepSize: Cardinal = 1);
242
243 { Finish progress bar.
244 You can call it only when Active = true (that is, if you called Init
245 before). Fini changes Active to false.
246
247 Note that it's perfectly legal to call Fini before Position
248 reaches Max (it's sensible e.g. when you're allowing user to break
249 some lenghty operation, or when Max was only an approximation
250 of steps needed). }
251 procedure Fini;
252
253 constructor Create;
254 end;
255
256 var
257 { Global progress bar instance.
258 Created in initialization of this unit, freed in finalization. }
259 Progress: TProgress;
260
261 type
262 TProgressNullInterface = class(TProgressUserInterface)
263 public
264 procedure Init(Progress: TProgress); override;
265 procedure Update(Progress: TProgress); override;
266 procedure Fini(Progress: TProgress); override;
267 end;
268
269 var
270 { A special progress user interface, that simply doesn't show progress anywhere.
271
272 If you set Progress.UserInterface to this,
273 then progress Init/Update/Fini will work --- but will not be displayed
274 anywhere. This is done at the initialization of this unit,
275 so you can safely use progress bars even before real interface
276 is initialized.
277
278 Created in initialization, freed in finalization. }
279 ProgressNullInterface: TProgressNullInterface;
280
281 implementation
282
283 uses Math;
284
285 { TProgressUserInterface ----------------------------------------------------- }
286
287 constructor TProgressUserInterface.Create;
288 begin
289 inherited;
290 FBarYPosition := DefaultBarYPosition;
291 end;
292
293 destructor TProgressUserInterface.Destroy;
294 begin
295 if OwnsImage then
296 FreeAndNil(FImage) else
297 FImage := nil;
298 inherited;
299 end;
300
301 procedure TProgressUserInterface.SetImage(const Value: TObject);
302 begin
303 if FImage <> Value then
304 begin
305 if OwnsImage then
306 FreeAndNil(FImage);
307 FImage := Value;
308 end;
309 end;
310
311 { TProgress ------------------------------------------------------------------ }
312
313 procedure TProgress.Init(AMax: Cardinal; const ATitle: string;
314 const DelayUserInterface: boolean);
315 begin
316 Check(not Active, 'TProgress.Init error: progress is already active');
317 FActive := true;
318
319 Check(UserInterface <> nil,
320 'TProgress.Init error: UserInterface not initialized');
321
322 FPosition := 0;
323
324 { Max(AMax, 1) secures us against AMax <= 0 values.
325
326 (Otherwise, it would have to be secured at many places when calling
327 Progress.Init, as sometimes AMax <= 0 values values can naturally
328 occur. Consider e.g. building octree, when the VRML scene turns out
329 to be empty.)
330
331 The idea is that AMax <= 0 means that actually operation is already
332 finished. So we'll set Max to 1 (to allow UserInterface to display it,
333 since user interface can display only Max >= 1 values)
334 and we'll do Step(1) immediately at the end of TProgress.Init,
335 to show to user that operation is already done. }
336 FMax := Math.Max(AMax, 1);
337
338 FTitle := ATitle;
339
340 { Calling UserInterface.Init updates LastUpdatePos and LastUpdateTime,
341 just like calling UserInterface.Update. }
342 LastUpdatePos := FPosition;
343 LastUpdateTime := Timer;
344
345 UserInterfaceDelayed := DelayUserInterface;
346
347 if not UserInterfaceDelayed then
348 try
349 UserInterface.Init(Self);
350 except
351 { In case of problems within UserInterface.Init, call Fini
352 to change our state to not Active. }
353 Fini;
354 raise;
355 end;
356
357 { This means that AMax < Max(AMax, 1), in other words: AMax <= 0.
358 Then show to user that this operation actually finished. }
359 try
360 if AMax < Max then Step;
361 except
362 { In case of problems within UserInterface.Init, call Fini
363 to change our state to not Active. }
364 Fini;
365 raise;
366 end;
367 end;
368
369 procedure TProgress.Step(StepSize: Cardinal);
370 begin
371 Assert(Active, 'TProgress.Step error: progress is not active');
372
373 FPosition := FPosition + StepSize;
374 if Position > Max then FPosition := Max;
375
376 if UserInterfaceDelayed then
377 begin
378 { Either actually init user interface, or resign from calling
379 UserInterface.Update. }
380 if TimerSeconds(Timer, LastUpdateTime) > UpdateDelay then
381 begin
382 UserInterface.Init(Self);
383 UserInterfaceDelayed := false;
384 end else
385 Exit;
386 end;
387
388 if ((Position - LastUpdatePos) / Max > 1 / UpdatePart) and
389 (TimerSeconds(Timer, LastUpdateTime) > UpdateDelay) then
390 begin
391 LastUpdatePos := FPosition;
392 LastUpdateTime := Timer;
393 UserInterface.Update(Self);
394
395 {$ifdef TESTING_PROGRESS_DELAY}
396 Sleep(10);
397 {$endif}
398 end;
399 end;
400
401 procedure TProgress.SetPosition(const Value: Cardinal);
402 begin
403 if Value > Position then
404 Step(Value - Position);
405 end;
406
407 procedure TProgress.Fini;
408 begin
409 Check(Active, 'TProgress.Fini error: progress is not active');
410 FActive := false;
411
412 if not UserInterfaceDelayed then
413 begin
414 { update to reflect the current state of Position, if needed.
415 Note that this does NOT mean that at the end Position is = Max.
416 Noone ever guarantees that -- you can call Fini before Position
417 reaches Max. }
418 if LastUpdatePos < Position then
419 UserInterface.Update(Self);
420
421 UserInterface.Fini(Self);
422 end;
423 end;
424
425 constructor TProgress.Create;
426 begin
427 inherited;
428 UpdatePart := DefaultUpdatePart;
429 UpdateDelay := DefaultUpdateDelay;
430 FActive := false;
431 end;
432
433 { TProgressNullInterface ----------------------------------------------------- }
434
435 procedure TProgressNullInterface.Init(Progress: TProgress);
436 begin
437 end;
438
439 procedure TProgressNullInterface.Update(Progress: TProgress);
440 begin
441 end;
442
443 procedure TProgressNullInterface.Fini(Progress: TProgress);
444 begin
445 end;
446
447 { initialization / finalization ---------------------------------------------- }
448
449 initialization
450 Progress := TProgress.Create;
451 ProgressNullInterface := TProgressNullInterface.Create;
452 { initialize Progress.UserInterface to null interface,
453 this way Progress.Init etc. may be always safely called }
454 Progress.UserInterface := ProgressNullInterface;
455 finalization
456 FreeAndNil(Progress);
457 FreeAndNil(ProgressNullInterface);
458 end.