Debian Codegraph @

src/ui/castlenotifications.pas

raw
1 {
2 Copyright 2002-2023 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 { Notifications displayed in the OpenGL window (TCastleNotifications). }
17 unit CastleNotifications;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses SysUtils, Classes, Generics.Collections,
24 CastleUIControls, CastleUtils, CastleControls,
25 CastleFonts, CastleTimeUtils, CastleVectors, CastleStringUtils,
26 CastleColors, CastleRectangles, CastleClassUtils;
27
28 type
29 { Notifications displayed on the screen.
30 Each message disappears after a short time.
31 Suitable for game messages like "Picked up 20 ammo".
32 Call @link(Show) to display a message.
33
34 This is a TCastleUserInterface descendant, so to use it --- just add it
35 to TCastleWindow.Controls or TCastleControl.Controls.
36 Use TCastleUserInterface anchors to automatically position it on the screen,
37 for example:
38
39 @longCode(#
40 Notifications := TCastleNotifications.Create(Owner);
41 Notifications.Anchor(hpMiddle);
42 Notifications.Anchor(vpMiddle);
43 Notifications.TextAlignment := hpMiddle; // looks best, when anchor is also in the middle
44 #) }
45 TCastleNotifications = class(TCastleUserInterfaceFont)
46 private
47 type
48 TNotification = class
49 Text: string;
50 Time: TTimerResult; {< appear time }
51 Width: Single;
52 Color: TCastleColor;
53 end;
54 TNotificationList = class({$ifdef FPC}specialize{$endif} TObjectList<TNotification>)
55 procedure DeleteFirst(DelCount: Integer);
56 end;
57 var
58 { Messages, ordered from oldest (new mesages are added at the end).}
59 Messages: TNotificationList;
60 FColor: TCastleColor;
61 FMaxMessages: integer;
62 FTimeout, FFade: Single;
63 FHistory: TCastleStringList;
64 FCollectHistory: boolean;
65 FTextAlignment: THorizontalPosition;
66 FDesignTestMessagesInterval: Single;
67 FDesignTestMessagesTimeout: TFloatTime;
68 FWrap: Boolean;
69 protected
70 procedure PreferredSize(var PreferredWidth, PreferredHeight: Single); override;
71 public
72 const
73 DefaultMaxMessages = 4;
74 DefaultTimeout = 5.0;
75 DefaultFade = 1.0;
76
77 constructor Create(AOwner: TComponent); override;
78 destructor Destroy; override;
79
80 { Show new message. An overloaded version that takes a single string will
81 detect newlines in the string automatically so a message may be multi-line.
82 The messages will be automatically broken to fit on the screen width with
83 given font.
84 @groupBegin }
85 procedure Show(const s: string); overload;
86 procedure Show(s: TStringList); overload;
87 { @groupEnd }
88
89 { Clear all messages. }
90 procedure Clear;
91
92 procedure Update(const SecondsPassed: Single;
93 var HandleInput: boolean); override;
94 procedure Render; override;
95 function PropertySections(const PropertyName: String): TPropertySections; override;
96
97 { Color used to draw subsequent messages. Default value is white. }
98 property Color: TCastleColor read FColor write FColor;
99
100 { All the messages passed to @link(Show), collected only if CollectHistory.
101 May be @nil when not CollectHistory. }
102 property History: TCastleStringList read FHistory;
103 published
104 { How many message lines should be visible on the screen, at maximum. }
105 property MaxMessages: integer
106 read FMaxMessages write FMaxMessages default DefaultMaxMessages;
107
108 { How long a given message should be visible on the screen, in seconds.
109 Message stops being visible when this timeout passed,
110 or when we need more space for new messages (see MaxMessages).
111
112 Note that the @link(Fade) time is already included in this value,
113 so a message is normally visible only for the @code(Timeout - Fade) seconds,
114 and then it starts fading out. }
115 property Timeout: Single
116 read FTimeout write FTimeout {$ifdef FPC}default DefaultTimeout{$endif};
117
118 property Fade: Single read FFade write FFade {$ifdef FPC}default DefaultFade{$endif};
119
120 { Turn this on to have all the messages you pass to @link(Show) be collected
121 inside @link(History) string list. @link(History) is expanded by @link(Show),
122 it is cleared by @link(Clear), just like the notifications on screen.
123 However, unlike the visible messages, it has unlimited size
124 (messages there are not removed when MaxMessages or @link(Timeout)
125 take action), and messages inside are not broken to honour screen width.
126
127 This is useful if you want to show the player a history of messages
128 (in case they missed the message in game). }
129 property CollectHistory: boolean read FCollectHistory write FCollectHistory
130 default false;
131
132 { Alignment of the text inside. }
133 property TextAlignment: THorizontalPosition
134 read FTextAlignment write FTextAlignment default hpLeft;
135
136 { In design mode (within CGE editor) we can spawn test messages (so you can see how
137 the notifications look). This property determines how often we do it.
138 0 means to not do it. }
139 property DesignTestMessagesInterval: Single
140 read FDesignTestMessagesInterval write FDesignTestMessagesInterval
141 {$ifdef FPC}default 1{$endif};
142
143 { Wrap messages to fit in parent width.
144 This is usually nice for display, but it may cause problems
145 when parent size depends on child (e.g. because parent uses
146 @link(TCastleUserInterface.AutoSizeToChildren)), because then child
147 size also depends on parent, and parent would never grow. }
148 property Wrap: Boolean read FWrap write FWrap default true;
149
150 {$define read_interface_class}
151 {$I auto_generated_persistent_vectors/tcastlenotifications_persistent_vectors.inc}
152 {$undef read_interface_class}
153 end;
154
155 implementation
156
157 uses Math,
158 CastleLog, CastleComponentSerialize;
159
160 { TNotificationList ---------------------------------------------------------- }
161
162 procedure TCastleNotifications.TNotificationList.DeleteFirst(DelCount: Integer);
163 var
164 I: Integer;
165 begin
166 { Could be optimized better, but this is simple and works correctly
167 with TObjectList.FreeObjects = true management.
168 This is called only for really small DelCount values, so no problem. }
169 for I := 1 to DelCount do Delete(0);
170 end;
171
172 { TCastleNotifications ------------------------------------------------------- }
173
174 constructor TCastleNotifications.Create(AOwner: TComponent);
175 begin
176 inherited;
177 Messages := TNotificationList.Create;
178 FHistory := TCastleStringList.Create;
179
180 MaxMessages := DefaultMaxMessages;
181 Timeout := DefaultTimeout;
182 Fade := DefaultFade;
183 FColor := White;
184 FDesignTestMessagesInterval := 1;
185 FDesignTestMessagesTimeout := FDesignTestMessagesInterval;
186 FWrap := true;
187
188 {$define read_implementation_constructor}
189 {$I auto_generated_persistent_vectors/tcastlenotifications_persistent_vectors.inc}
190 {$undef read_implementation_constructor}
191 end;
192
193 destructor TCastleNotifications.Destroy;
194 begin
195 FreeAndNil(Messages);
196 FreeAndNil(FHistory);
197
198 {$define read_implementation_destructor}
199 {$I auto_generated_persistent_vectors/tcastlenotifications_persistent_vectors.inc}
200 {$undef read_implementation_destructor}
201 inherited;
202 end;
203
204 procedure TCastleNotifications.Show(S: TStringList);
205
206 procedure AddStrings(S: TStrings);
207 var
208 N: TNotification;
209 i: integer;
210 begin
211 { Below could be optimized. But we use this only for a small number
212 of messages, so no need to. }
213 for i := 0 to S.Count - 1 do
214 begin
215 if Messages.Count = MaxMessages then Messages.Delete(0);
216 N := TNotification.Create;
217 N.Text := S[i];
218 N.Time := Timer;
219 N.Width := Font.TextWidth(N.Text);
220 N.Color := Color;
221 Messages.Add(N);
222 end;
223 end;
224
225 var
226 Broken: TStringList;
227 begin
228 //WritelnLog('Notification', Trim(S.Text)); // too verbose by default
229
230 { We need to know ParentRect to wrap,
231 and for this we need to know final size: both Parent and Container
232 are necessary for this. }
233 if Wrap and (Parent <> nil) and (Container <> nil) then
234 begin
235 Broken := TStringList.Create;
236 try
237 Font.BreakLines(S, Broken, ParentRect.Width);
238 AddStrings(Broken);
239 finally Broken.Free end;
240 end else
241 AddStrings(S);
242
243 if CollectHistory then
244 History.AddRange(S);
245
246 VisibleChange([chRectangle]);
247 end;
248
249 procedure TCastleNotifications.Show(const s: string);
250 var
251 Strs: TStringList;
252 begin
253 Strs := TStringList.Create;
254 try
255 Strs.Text := s;
256 Show(strs);
257 finally Strs.Free end;
258 end;
259
260 procedure TCastleNotifications.Clear;
261 begin
262 Messages.Clear;
263 if CollectHistory then
264 History.Clear;
265 VisibleChange([chRectangle]);
266 end;
267
268 procedure TCastleNotifications.PreferredSize(var PreferredWidth, PreferredHeight: Single);
269 var
270 I: integer;
271 begin
272 inherited;
273 PreferredWidth := 0;
274 PreferredHeight := Font.Height * Messages.Count;
275 for I := 0 to Messages.Count - 1 do
276 PreferredWidth := Max(PreferredWidth, Messages[I].Width);
277 end;
278
279 procedure TCastleNotifications.Render;
280 var
281 SR: TFloatRectangle;
282
283 procedure ShowMessage(const MessageIndex, MessagesCount: Integer;
284 const MessageColor: TCastleColor; const Text: String);
285 begin
286 Font.PrintRect(FloatRectangle(SR.Left,
287 SR.Bottom + (MessagesCount - 1 - MessageIndex) * Font.Height,
288 SR.Width, Font.Height), MessageColor, Text,
289 TextAlignment, vpBottom);
290 end;
291
292 var
293 I: integer;
294 begin
295 SR := RenderRect;
296 for I := 0 to Messages.Count - 1 do
297 ShowMessage(I, Messages.Count, Messages[I].Color, Messages[I].Text);
298 end;
299
300 procedure TCastleNotifications.Update(const SecondsPassed: Single;
301 var HandleInput: boolean);
302 var
303 TimerNow: TTimerResult;
304 TimeoutToFade: TFloatTime;
305 I: integer;
306 C: TCastleColor;
307 begin
308 inherited;
309 TimerNow := Timer;
310 TimeoutToFade := Timeout - Fade;
311 for I := Messages.Count - 1 downto 0 do
312 if TimerSeconds(TimerNow, Messages[I].Time) > Timeout then
313 begin { delete messages 0..I }
314 Messages.DeleteFirst(I + 1);
315 VisibleChange([chRectangle]);
316 break;
317 end else
318 if TimerSeconds(TimerNow, Messages[I].Time) > TimeoutToFade then
319 begin
320 C := Messages[I].Color;
321 C.W := MapRange(TimerSeconds(TimerNow, Messages[I].Time),
322 TimeoutToFade, Timeout, 1, 0);
323 Messages[I].Color := C;
324 VisibleChange([chRectangle]);
325 end;
326
327 if CastleDesignMode and (FDesignTestMessagesInterval <> 0) then
328 begin
329 FDesignTestMessagesTimeout := FDesignTestMessagesTimeout - SecondsPassed;
330 if FDesignTestMessagesTimeout < 0 then
331 begin
332 Show('Test Message in Design Mode at ' + DateTimeToAtStr(CastleNow));
333 FDesignTestMessagesTimeout := FDesignTestMessagesInterval;
334 end;
335 end;
336 end;
337
338 function TCastleNotifications.PropertySections(
339 const PropertyName: String): TPropertySections;
340 begin
341 if ArrayContainsString(PropertyName, [
342 'MaxMessages', 'Timeout', 'Fade', 'CollectHistory', 'TextAlignment',
343 'DesignTestMessagesInterval', 'ColorPersistent', 'Wrap'
344 ]) then
345 Result := [psBasic]
346 else
347 Result := inherited PropertySections(PropertyName);
348 end;
349
350 {$define read_implementation_methods}
351 {$I auto_generated_persistent_vectors/tcastlenotifications_persistent_vectors.inc}
352 {$undef read_implementation_methods}
353
354 initialization
355 RegisterSerializableComponent(TCastleNotifications, 'Notifications');
356 end.