Debian Codegraph @

src/base/castleclassutils.pas

raw
1 {
2 Copyright 2000-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 { Basic classes and class utilities (for streams, strings, lists and such).
17 Many utilities for classes that are defined in the Classes unit,
18 and some classes of our my own.
19
20 Some notes about TStream descendants :
21 @unorderedList(
22 @item(
23 We call a stream "purely sequential" (or just "sequential")
24 if it allows only reading and/or writing of data
25 and does not allow free "Seek" calls,
26 in particular --- it does not allow Seek to move back in a stream.)
27
28 @item(
29 We call a stream "growing" if it's read-only and it's purely sequential
30 and it's Size property may be useless. In other words, when you read
31 a "growing" stream, you don't know when it ends, until you reach the end.
32 You just have to read data until Read returns 0.)
33
34 @item(Remember that to reliably detect end of the stream when you
35 use TStream.Read, you have to test is ReadCount = 0.
36 Merely testing that ReadCount < less than you requested is not enough,
37 e.g. seen for THandleStream when handle is StdIn.)
38 )
39 }
40 unit CastleClassUtils;
41
42 {$I castleconf.inc}
43
44 interface
45
46 uses Classes, SysUtils, Contnrs, Generics.Collections,
47 CastleUtils, CastleStringUtils;
48
49 { ---------------------------------------------------------------------------- }
50 { @section(TStrings utilities) }
51
52 { Add some strings. }
53 procedure StringsAdd(Strs: TStrings; Count: integer; itemVal: string='dummy'); overload;
54
55 { Add all strings from string array to TStrings instance. }
56 procedure AddStrArrayToStrings(const StrArr: array of string; strlist: TStrings);
57
58 type
59 { TStringList that is case sensitive. }
60 TStringListCaseSens = class(TStringList)
61 constructor Create;
62 property CaseSensitive default true;
63 end;
64
65 { Splits S by Splitter, and adds each splitted part to Strings.
66 Splitting is done by Splitter, i.e. if N is the number of occurrences
67 of Splitter inside S, then it always adds N + 1 strings to Strings.
68 Yes, this means that if S starts with Splitter then the first
69 part is equal to ''. And if S ends with Splitter then the last
70 oart is equal to ''. }
71 procedure Strings_AddSplittedString(Strings: TStrings;
72 const S, Splitter: string);
73
74 { Use this instead of @code(SList.Text := S) to workaround FPC 2.0.2 bug.
75 See [http://www.freepascal.org/mantis/view.php?id=6699] }
76 procedure Strings_SetText(SList: TStrings; const S: String);
77
78 { Make sure we don't have more than MaxCount strings on a list.
79 Removes the last strings if necessary. }
80 procedure Strings_Trim(Strings: TStrings; MaxCount: Cardinal);
81
82 { ---------------------------------------------------------------------------- }
83 { @section(TStream utilities) }
84
85 // Unused
86 //procedure StreamWriteByte(Stream: TStream; const Value: Byte);
87 //function StreamReadByte(Stream: TStream): Byte;
88
89 { Write string contents, encoded as 8-bit (UTF-8), to stream.
90 Versions with "Ln" suffix append a newline.
91 Versions without Stream parameter write to StdOutStream.
92
93 Note: When compiled with Delphi, overloaded versions that take
94 Delphi 16-bit String convert it to 8-bit AnsiString,
95 and still write 8-bit. So the output stream contents are the same,
96 in both FPC and Delphi.
97
98 @groupBegin }
99 procedure WriteStr(const Stream: TStream; const S: AnsiString); overload;
100 procedure WritelnStr(const Stream: TStream; const S: AnsiString); overload;
101 procedure WriteStr(const S: AnsiString); overload;
102 procedure WritelnStr(const S: AnsiString); overload;
103
104 {$ifndef FPC}
105 procedure WriteStr(const Stream: TStream; const S: String); overload;
106 procedure WritelnStr(const Stream: TStream; const S: String); overload;
107 procedure WriteStr(const S: String); overload;
108 procedure WritelnStr(const S: String); overload;
109 {$endif}
110 { @groupEnd }
111
112 { Read one character from stream.
113 @raises EReadError If end of stream. }
114 function StreamReadChar(Stream: TStream): AnsiChar;
115
116 function StreamReadZeroEndString(Stream: TStream): AnsiString;
117
118 { Read stream, until you find some character in EndingChars.
119 Returns read contents, without final character (the one in EndingChars set).
120
121 If you use a version with BackEndingChar parameter and pass
122 BackEndingChar = @true, then the ending character will be returned back to
123 stream (we will start reading from it next time).
124 Note that "returning the character" is done by Seek(-1, soFromCurrent),
125 which may not be possible on some streams. Wrap a stream
126 in TPeekCharStream instead, and use TPeekCharStream.ReadUpto,
127 to be able to "return back" a character reliably.
128
129 Independently from BackEndingChar, if you use a version with EndingChar
130 parameter, it will be set to the ending character.
131
132 @raises EReadError If the stream will end before encountering one of EndingChars.
133 @groupBegin }
134 function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars;
135 backEndingChar: boolean; out endingChar: AnsiChar): AnsiString; overload;
136 function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars;
137 backEndingChar: boolean): AnsiString; overload;
138 function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars;
139 out endingChar: AnsiChar): AnsiString; overload;
140 function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars): AnsiString; overload;
141 { @groupEnd }
142
143 { Read stream, until you find some character in EndingChars, or end of stream.
144
145 Compared to StreamReadUpto_NotEOS, this treats "end of stream"
146 as a normal situation, and doesn't raise any exception on it.
147 It sets EndingChar to -1 on end of stream. When EndingChar is not -1,
148 you know you can safely cast it to normal 8-bit character.
149
150 Everything else works like with StreamReadUpto_NotEOS.
151 @groupBegin }
152 function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars;
153 backEndingChar: boolean; out endingChar: integer): AnsiString; overload;
154 function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars;
155 backEndingChar: boolean): AnsiString; overload;
156 function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars;
157 out endingChar: integer): AnsiString; overload;
158 function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars): AnsiString; overload;
159 { @groupEnd }
160
161 { Read a growing stream, and append it to another destination stream.
162 A "growing stream" is a stream that we can only read
163 sequentially, no seeks allowed, and size is unknown until we hit the end.
164
165 The only operation we do on GrowingStream is GrowingStream.Read and the only
166 operation on DestStream is DestStream.WriteBuffer. So DestStream usually
167 must be able to grow dynamically to accomodate any GrowingStream input size.
168
169 This procedure ends when GrowingStream ends. If ResetDestStreamPosition
170 then at the end we do DestStream.Position := 0 (since it is usually useful
171 and it would be easy for you to forget about it). }
172 procedure ReadGrowingStream(const GrowingStream, DestStream: TStream;
173 const ResetDestStreamPosition: Boolean;
174 const BufferSize: Cardinal = 10 * 1000);
175
176 { Read a growing stream, and returns it's contents as a string.
177 A "growing stream" is a stream that we can only read
178 sequentially, no seeks allowed, and size is unknown until we hit the end.
179
180 Works on 8-bit strings, i.e. AnsiStrings. }
181 function ReadGrowingStreamToString(const GrowingStream: TStream): AnsiString;
182
183 { Read a growing stream, and returns it's contents as a string.
184 A "growing stream" is a stream that we can only read
185 sequentially, no seeks allowed, and size is unknown until we hit the end.
186
187 Works with String, i.e. UTF-16 with Delphi, UTF-8 with FPC. }
188 function ReadGrowingStreamToDefaultString(const GrowingStream: TStream): String;
189
190 { Encode / decode a string in a binary stream. Records string length (4 bytes),
191 then the string contents (Length(S) bytes).
192 Works on 8-bit strings, i.e. AnsiStrings.
193 @groupBegin }
194 procedure StreamWriteString(const Stream: TStream; const S: AnsiString);
195 function StreamReadString(const Stream: TStream): AnsiString;
196 { @groupEnd }
197
198 { Convert whole Stream to a string.
199
200 Changes Stream.Position to 0 and then reads Stream.Size bytes,
201 so be sure that Stream.Size is usable.
202 Use @link(ReadGrowingStreamToString) if you want to read a stream where
203 setting Position / reading Size are not reliable.
204
205 Works on 8-bit strings, i.e. AnsiStrings. }
206 function StreamToString(const Stream: TStream): AnsiString;
207
208 { Set contents of TMemoryStream to given string, in UTF-8 encoding.
209 If Rewind then the position is reset to the beginning,
210 otherwise it stays at the end.
211
212 Works on 8-bit strings, i.e. AnsiStrings. }
213 procedure MemoryStreamLoadFromString(const Stream: TMemoryStream;
214 const S: AnsiString; const Rewind: boolean = true); overload;
215 function MemoryStreamLoadFromString(
216 const S: AnsiString; const Rewind: boolean = true): TMemoryStream; overload;
217
218 { Set contents of TMemoryStream to given string,
219 in UTF-8 or UTF-16 (matching default String) encoding.
220 If Rewind then the position is reset to the beginning,
221 otherwise it stays at the end.
222
223 On FPC, works with 8-bit strings (AnsiStrings) and is equivalent to MemoryStreamLoadFromString8.
224 On Delphi, works with 16-bit strings (UnicodeString), so the resulting stream size is 2x larger. }
225 procedure MemoryStreamLoadFromDefaultString(const Stream: TMemoryStream;
226 const S: String; const Rewind: boolean = true); overload;
227 function MemoryStreamLoadFromDefaultString(
228 const S: String; const Rewind: boolean = true): TMemoryStream; overload;
229
230 type
231 EStreamNotImplemented = class(Exception);
232 EStreamNotImplementedWrite = class(EStreamNotImplemented);
233 EStreamNotImplementedSeek = class(EStreamNotImplemented);
234 EStreamNotImplementedSetSize = class(EStreamNotImplemented);
235
236 { Abstract class to read another stream, always being able to back one character.
237 This is a purely sequential read-only stream.
238 This means that calling @link(Write), @link(Seek) (changing Position)
239 or setting @code(Size) will always cause an exception with
240 appropriate descendant of @link(EStreamNotImplemented).
241
242 Getting @code(Size) and @code(Position) is allowed.
243 Getting @code(Size) is simply
244 implemented by getting SourceStream.Size (so it works if the underlying
245 source stream supports getting Size). Getting @code(Position) always works
246 correctly, as it's just the number of characters
247 @italic(read) from this stream. The fact that we may
248 read ahead in the underlying source stream (for buffering, for peeking)
249 is completely hidden.
250
251 We do not assume anything about the underlying source stream, in particular
252 the underlying source stream may also be purely sequential
253 (so we can only read from it, and we cannot predict when it ends).
254
255 The main advantage of using this class is that you get PeekChar routine:
256 you can always peek ahead one character in the stream,
257 without reading it (i.e. next time you will call Read or ReadBuffer
258 you will still get that char). And it works for all source streams,
259 including the ones where seeking is not allowed (so Seek(-1, soCurrent)
260 would not work).
261
262 Another advantage is the @link(Line) and @link(Column) information. }
263 TPeekCharStream = class(TStream)
264 private
265 FSourceStream: TStream;
266 FOwnsSourceStream: boolean;
267 FLine, FColumn: Int64;
268 protected
269 { @returns(SourceStream.Size). }
270 function GetSize: Int64; override;
271
272 { This stream doesn't support setting size.
273 (All other versions of SetSize also call this.)
274 @raises(EStreamNotImplementedSetSize Always.) }
275 procedure SetSize(NewSize: Longint); override;
276
277 {$ifndef FPC}
278 function GetPosition: Int64; virtual; abstract;
279 {$endif}
280 procedure UpdateLineColumn(const C: AnsiChar); overload;
281 procedure UpdateLineColumn(const Buffer; const BufferCount: Integer); overload;
282 public
283 constructor Create(ASourceStream: TStream; AOwnsSourceStream: boolean);
284 destructor Destroy; override;
285
286 { This stream doesn't support seeking.
287 (SetPosition and all other versions of Seek also call this.)
288 @raises(EStreamNotImplementedSeek Always.) }
289 function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
290
291 { This stream doesn't support writing.
292 (WriteBuffer also calls this.)
293 @raises(EStreamNotImplementedWrite Always.) }
294 function Write(const Buffer; Count: Longint): Longint; override;
295
296 { Underlying stream. }
297 property SourceStream: TStream read FSourceStream;
298
299 { Should we free underlying SourceStream at destruction. }
300 property OwnsSourceStream: boolean
301 read FOwnsSourceStream write FOwnsSourceStream;
302
303 { Peek next character. Returns the next character
304 without making it "already read", so the next call to
305 Read or ReadBuffer will return this char.
306 Subsequent calls to PeekChar (without any Read/ReadBuffer between)
307 will also return the same character.
308
309 Returns -1 if stream ended, otherwise returns Ord or given char.
310
311 This may call SourceStream.Read, and any exceptions that may be
312 raised in SourceStream.Read are propagated higher from this method. }
313 function PeekChar: Integer; virtual; abstract;
314
315 { Read next character. A shortcut for Read(c, 1), but it returns -1
316 if end of stream is reached. So it's consistent with PeekChar.
317 Sometimes it's also more comfortable, and it's a little faster. }
318 function ReadChar: Integer; virtual; abstract;
319
320 { Read characters, until one of EndingChars (or end of stream) is found.
321 The ending character is not "consumed" from the stream.
322 The Result is guaranteed to not contain any char from EndingChars. }
323 function ReadUpto(const EndingChars: TSetOfChars): AnsiString; virtual;
324
325 {$ifndef FPC}
326 property Position: Int64 read GetPosition;
327 {$endif}
328
329 { Line number in the file (counting from 1). }
330 property Line: Int64 read FLine;
331
332 { Column number in the file (counting from 1). }
333 property Column: Int64 read FColumn;
334 end;
335
336 { Read another stream, sequentially, always being able to back one character.
337 This is a simplest non-abstract implementation of
338 the @link(TPeekCharStream) class. }
339 TSimplePeekCharStream = class(TPeekCharStream)
340 private
341 PeekedChar: Integer;
342 IsPeekedChar: boolean;
343 FPosition: Int64;
344 protected
345 function GetPosition: Int64; override;
346 public
347 function Read(var Buffer; Count: Longint): Longint; override;
348 function PeekChar: Integer; override;
349 function ReadChar: Integer; override;
350 end;
351
352 const
353 DefaultReadBufferSize = 1024 * 1024;
354
355 type
356 { Read another stream, sequentially, always being able to back one character,
357 and buffering it. This implements abstract TPeekCharStream class,
358 so this is a purely sequential read-only stream that reads from
359 underlying SourceStream and you can use PeekChar and ReadChar and
360 ReadUpto routines.
361
362 This stream will buffer incoming data from SourceStream.
363 This means that reading by a very small chunks (like e.g. byte-by-byte)
364 does not hurt performance. }
365 TBufferedReadStream = class(TPeekCharStream)
366 private
367 FPosition: Int64;
368
369 { Always non-nil, allocated for BufferSize bytes. }
370 Buffer: PByteArray;
371
372 { A position of the next unread char in Buffer,
373 i.e. PeekChar simply returns Buffer[BufferPos]
374 (unless BufferPos = BufferEnd, in which case buffer must be refilled). }
375 BufferPos: Cardinal;
376
377 { Always BufferPos <= BufferEnd.
378 Always Buffer[BufferPos..BufferEnd - 1] is the data that still must be
379 returned by TBufferedReadStream.Read method. }
380 BufferEnd: Cardinal;
381
382 FBufferSize: Cardinal;
383
384 { Sets Buffer contents, BufferEnd reading data from SourceStream.
385 BufferPos is always resetted to 0 by this. }
386 procedure FillBuffer;
387 protected
388 function GetPosition: Int64; override;
389 public
390 constructor Create(ASourceStream: TStream; AOwnsSourceStream: boolean;
391 ABufferSize: Cardinal = DefaultReadBufferSize);
392 destructor Destroy; override;
393
394 function Read(var LocalBuffer; Count: Longint): Longint; override;
395 function PeekChar: Integer; override;
396 function ReadChar: Integer; override;
397 function ReadUpto(const EndingChars: TSetOfChars): AnsiString; override;
398
399 property BufferSize: Cardinal read FBufferSize;
400 end;
401
402 { ---------------------------------------------------------------------------- }
403 { @section(TComponent utilities) }
404
405 { Create Component instance, if it's @nil.
406 If Component = nil then it will do
407 @code(Component := ComponentClass.Create(Owner)). }
408 procedure CreateIfNeeded(var Component: TComponent;
409 ComponentClass: TComponentClass; Owner: TComponent);
410
411 type
412 { Used by @link(TCastleComponent.PropertySections). }
413 TPropertySection = (psBasic, psLayout);
414 TPropertySections = set of TPropertySection;
415
416 TCastleComponent = class;
417
418 { Use by @link(TCastleComponent.TranslateProperties). }
419 TTranslatePropertyEvent = procedure (const Sender: TCastleComponent;
420 const PropertyName: String; var PropertyValue: String) of object;
421
422 { Call methods of this class within @link(TCastleComponent.CustomSerialization) override.
423 Do not create instances of this class yourself. }
424 TSerializationProcess = class abstract
425 public
426 type
427 TListEnumerateEvent = procedure (const Proc: TGetChildProc) of object;
428 TListAddEvent = procedure (const NewComponent: TComponent) of object;
429 TListClearEvent = procedure of object;
430
431 var
432 { @exclude
433 Used by TCastleViewport to keep navigation/camera across undo. }
434 InternalPreserveDataAcrossUndo: TComponent;
435
436 { Serialize and deserialize given simple Value.
437 This mechanism allows to explicitly serialize/deserialize any internal value,
438 without the need to make it a published property.
439
440 When deserializing, we always try to read it from file.
441 If it is not present, the Value is not modified.
442
443 When serializing, we write it to file only if IsStored.
444 Generally IsStored=false should indicate "the Value is the same as when the object
445 is created, thus there's no point in serializing it".
446
447 The values are guaranteed to be read/written in the same way as if a published
448 property with the same name (Key) and same type would be read/written.
449 This allows to utilize this mechanism to read, to a local/private variable,
450 a value that was previously a published property value.
451 This is a way to provide backward-compatibility for old designs: this way class
452 can interpret old values in design files, even though it no longer publishes
453 given property.
454
455 @seealso ReadWriteSubComponent
456
457 @groupBegin }
458 procedure ReadWriteInteger(const Key: String; var Value: Integer; const IsStored: Boolean);
459 overload; virtual; abstract;
460 procedure ReadWriteBoolean(const Key: String; var Value: Boolean; const IsStored: Boolean);
461 overload; virtual; abstract;
462 procedure ReadWriteString(const Key: String; var Value: String; const IsStored: Boolean);
463 overload; virtual; abstract;
464 procedure ReadWriteSingle(const Key: String; var Value: Single; const IsStored: Boolean);
465 overload; virtual; abstract;
466 { @groupEnd }
467
468 { Serialize and deserialize a subcomponent.
469 Being a subcomponent, we know that Value is not nil,
470 and it is not referenced anywhere else in the design
471 (so serialization/deserialization can expect class contents, not just name),
472 so we just serialize and deserialize the contents.
473
474 When deserializing, we always try to read it from file.
475 If it is not present, nothing is modified.
476
477 When serializing, we write it to file only if IsStored.
478 Generally IsStored=false should indicate "the Value is the same as when the object
479 is created, thus there's no point in serializing it".
480
481 The values are guaranteed to be read/written in the same way as if a published
482 property with the same name (Key) and same type would be read/written.
483 This allows to utilize this mechanism to read, to a local/private variable,
484 a value that was previously a published property value.
485 This is a way to provide backward-compatibility for old designs: this way class
486 can interpret old values in design files, even though it no longer publishes
487 given property.
488
489 @seealso ReadWriteInteger
490 @seealso ReadWriteBoolean
491 @seealso ReadWriteSingle
492 @seealso ReadWriteString }
493 procedure ReadWriteSubComponent(const Key: String; const Value: TComponent;
494 const IsStored: Boolean); virtual; abstract;
495
496 { Make a list serialized and deserialized.
497 The definition of list is very flexible here, you provide callbacks
498 that should, when called,
499
500 @unorderedList(
501 @itemSpacing compact
502 @item enumerate (call other callback for each item),
503 @item clear all items (that were possibly added by previous deserialization),
504 @item add new item.
505 )
506
507 Do not worry about conflict between Key and some published property.
508 We internally "mangle" keys to avoid it. }
509 procedure ReadWriteList(const Key: String;
510 const ListEnumerate: TListEnumerateEvent; const ListAdd: TListAddEvent;
511 const ListClear: TListClearEvent); virtual; abstract;
512 end;
513
514 { Component with various CGE extensions: can be a parent of other non-visual components
515 (to display them in CGE editor and serialize them to files), can be translated,
516 can have custom logic when serializing/deserializing (CustomSerialization).
517
518 Note that everywhere in CGE (in particular in editor and when serializing) we handle
519 a standard Pascal TComponent as well. So there's no need to derive all your components from
520 TCastleComponent, so you derive from standard TComponent too.
521 You can use TCastleComponent only if necessary, i.e. only if you need one of
522 the extra features in this class. }
523 TCastleComponent = class(TComponent)
524 strict private
525 type
526 { Used by @link(TCastleComponent.NonVisualComponentsEnumerate).
527 Do not use this type explicitly, it should only be used by for..in
528 construction like "for C in MyComponent.NonVisualComponentsEnumerate do ...".
529 @exclude }
530 TNonVisualComponentsEnumerator = record
531 strict private
532 FParent: TCastleComponent;
533 FPosition: Integer;
534 function GetCurrent: TComponent; inline;
535 public
536 constructor Create(const AParent: TCastleComponent);
537 function MoveNext: Boolean; inline;
538 property Current: TComponent read GetCurrent;
539 function GetEnumerator: TNonVisualComponentsEnumerator;
540 end;
541 var
542 FNonVisualComponents: TComponentList;
543 FIsLoading: Boolean;
544 function GetNonVisualComponents(const Index: Integer): TComponent;
545 procedure SerializeNonVisualComponentsEnumerate(const Proc: TGetChildProc);
546 procedure SerializeNonVisualComponentsAdd(const C: TComponent);
547 procedure SerializeNonVisualComponentsClear;
548 protected
549 function GetInternalText: String; virtual;
550 procedure SetInternalText(const Value: String); virtual;
551 procedure SetName(const Value: TComponentName); override;
552
553 { Enumerate all properties that are possible to translate in this component.
554 E.g. in @link(TCastleLabel) it will return @link(TCastleLabel.Caption),
555 in @link(TCastleEdit) it will return @link(TCastleEdit.Text) and
556 @link(TCastleEdit.Placeholder).
557
558 Returns only non-empty properties, thus assuming that if current
559 (by convention, English) text is empty, then there is no point
560 in translating it. Moreover descendants may define boolean properties
561 to exclude particular text from translating, e.g.
562 @link(TCastleLabel.CaptionTranslate),
563 @link(TCastleEdit.TextTranslate),
564 @link(TCastleEdit.PlaceholderTranslate).
565
566 It is not recursive (it doesn't enumerate children properties).
567 Use global @link(TranslateProperties) procedure to call this
568 on a hierarchy of TComponent.
569
570 You usually don't want to call this method (it is called by other engine routines).
571 But you may find it useful to override this, if you define new component. }
572 procedure TranslateProperties(const TranslatePropertyEvent: TTranslatePropertyEvent); virtual;
573 public
574 { Internal field used by CastleComponentSerialize.
575 @exclude }
576 InternalOriginalName: String;
577
578 destructor Destroy; override;
579
580 { Override this method to call various methods of SerializationProcess,
581 which in turn allows to serialize/deserialize things that are not published.
582 This allows to serialize/deserialize with more freedom, e.g. to serialize/deserialize
583 some private field. }
584 procedure CustomSerialization(const SerializationProcess: TSerializationProcess); virtual;
585
586 { Main text property, that is synchronized with Name initially.
587 @exclude }
588 property InternalText: String read GetInternalText write SetInternalText;
589
590 { Set IsLoading to @true and (only on FPC) add csLoading flag to ComponentState.
591 Used when deserializing.
592 Do not call this yourself, CastleComponentSerialize automatically calls this.
593 @exclude }
594 procedure InternalLoading;
595
596 { Set IsLoading to @false and (only on FPC) remove csLoading flag from ComponentState
597 and call virtual TComponent.Loaded.
598 Used when deserializing.
599 Do not call this yourself, CastleComponentSerialize automatically calls this.
600 Descendants can override TComponent.Loaded to react to being loaded.
601 @exclude }
602 procedure InternalLoaded;
603
604 { Section where to show property in the editor. }
605 function PropertySections(const PropertyName: String): TPropertySections; virtual;
606
607 { Ignore this component when serializing parent's
608 @link(TCastleUserInterface.Controls) list or @link(TCastleTransform.List),
609 and do not show this component in CGE editor.
610 This simply sets csTransient flag in ComponentStyle.
611
612 This is useful for children that are automatically managed by the parent,
613 and should not be modified by user code. For example,
614 TCastleCheckbox is internally composed from TCastleImageControl
615 and TCastleLabel children, but we don't want to serialize or even
616 show these children to user.
617
618 Note that if you want to prevent this component from serializing as part of
619 @link(TCastleUserInterface.Controls) list or @link(TCastleTransform.List),
620 but you still want it to be visible in CGE editor,
621 then make it a "subcomponent" instead, by @code(SetSubComponent(true)).
622
623 Note that both csSubComponent and csTransient only disable the component
624 serialization as part of parent's lists enumerated by CustomSerialization
625 (see internal TCastleUserInterface.SerializeChildrenEnumerate ,
626 TCastleTransform.SerializeChildrenEnumerate,
627 TCastleTransform.SerializeBehaviorsEnumerate).
628
629 If you will make the component published in its own property
630 (which is normal for "subcomponents")
631 then it will be serialized anyway, just as part of it's own property
632 (like TCastleScrollView.ScrollArea).
633 So to @italic(really) avoid serializing a children component
634 make it csSubComponent and/or csTransient,
635 and do not publish it.
636 }
637 procedure SetTransient;
638
639 { Add non-visual component to this component.
640 This is used to organize non-visual components in a tree hierarchy,
641 in CGE designs and editor.
642
643 @seealso NonVisualComponentsCount
644 @seealso NonVisualComponents
645 @seealso NonVisualComponentsEnumerate }
646 procedure AddNonVisualComponent(const NonVisualComponent: TComponent);
647
648 { Insert non-visual component to this component.
649 This is used to organize non-visual components in a tree hierarchy,
650 in CGE designs and editor.
651
652 @seealso NonVisualComponentsCount
653 @seealso NonVisualComponents
654 @seealso NonVisualComponentsEnumerate }
655 procedure InsertNonVisualComponent(const Index: Integer; const NonVisualComponent: TComponent);
656
657 { Remove component previously added by AddNonVisualComponent. }
658 procedure RemoveNonVisualComponent(const NonVisualComponent: TComponent);
659
660 { Index of component previously added non-visual component.
661 Returns -1 if component was not found. }
662 function NonVisualComponentsIndexOf(const NonVisualComponent: TComponent): Integer;
663
664 { Count of components added by AddNonVisualComponent.
665
666 @seealso AddNonVisualComponent
667 @seealso NonVisualComponents
668 @seealso NonVisualComponentsEnumerate }
669 function NonVisualComponentsCount: Integer;
670
671 { Components added by AddNonVisualComponent. }
672 property NonVisualComponents [const Index: Integer]: TComponent read GetNonVisualComponents;
673
674 { You can enumerate current non-visual components using loop like
675 @code(for C in MyComponent.NonVisualComponentsEnumerate do ...).
676 Do not call this method in other contexts, it is only useful for "for..in" construction.
677
678 @seealso AddNonVisualComponent }
679 function NonVisualComponentsEnumerate: TNonVisualComponentsEnumerator;
680
681 { Is the component during deserialization now.
682
683 Note: We can't use @code(csLoading in ComponentState) because in Delphi
684 it is not possible to control it from CastleComponentSerialize. }
685 property IsLoading: Boolean read FIsLoading;
686
687 { Whether the current value of this object should be written
688 to the stream. This should be @true if @italic(anything) inside
689 this object should be serialized (which means it has non-default
690 value or "stored" specifier indicates that it should be serialized).
691
692 This is used by CastleComponentSerialize, which is used in
693 Castle Game Engine for all serialization.
694
695 In simple cases, this just says whether the current value of this object
696 equals to some default value.
697
698 The default implementation of this class returns @true (so always write).
699
700 Descendants that override this to sometimes return @false
701 (so no need to write) must be very careful: any addition of a new field
702 requires extending this method, otherwise new field may not be saved sometimes
703 (when all other fields are default). Descentants of such classes
704 must also be aware of it.
705 This check must include everything that is inside this object in JSON,
706 including subcomponents and children objects (as done e.g. by
707 @link(TSerializationProcess.ReadWriteList)).
708 In practice, overriding this method is only reasonable for simple classes
709 that will not change much in the future, like TCastleVector3Persistent.
710
711 The name of this method is consistent with TPropertyEditor.ValueIsStreamed
712 in LCL. }
713 function ValueIsStreamed: Boolean; virtual;
714
715 { Override to add information that should be visible at design-time.
716 Call @code(SList.Add) for each new line of information. }
717 procedure DesignerInfo(const SList: TStrings); virtual;
718
719 { Override to add warnings that should be visible at design-time.
720 Call @code(SList.Add) for each new warning. }
721 procedure DesignerWarnings(const SList: TStrings); virtual;
722 end;
723
724 { Enumerate all properties that are possible to translate in this component
725 and its children. E.g. in @link(TCastleLabel) it will return @link(TCastleLabel.Caption),
726 in @link(TCastleEdit) it will return @link(TCastleEdit.Text)
727 and @link(TCastleEdit.Placeholder).
728
729 Returns only non-empty properties, thus assuming that if current
730 (by convention, English) text is empty, then there is no point
731 in translating it. Moreover descendants may define boolean properties
732 to exclude particular text from translating, e.g.
733 @link(TCastleLabel.CaptionTranslate),
734 @link(TCastleEdit.TextTranslate),
735 @link(TCastleEdit.PlaceholderTranslate).
736
737 For every TComponent it also recursively enumerates properties
738 to translate in children, i.e. in all published subcomponents and children
739 (returned by TCastleComponent.CustomSerialization). The goal is to be 100% consistent with
740 CastleComponentSerialize, which is used to (de)serialize hierarchy of
741 components (like TCastleUserInterface or TCastleTransform).
742
743 You usually don't want to call this method (it is called by other engine routines).
744 Use higher-level routines in @link(CastleLocalizationGetText).
745
746 @seealso TCastleComponent.TranslateProperties }
747 procedure TranslateProperties(const C: TComponent;
748 const TranslatePropertyEvent: TTranslatePropertyEvent);
749
750 { ---------------------------------------------------------------------------- }
751 { @section(Variables to read/write standard input/output using TStream classes.
752 Initialized and finalized in this unit.) }
753
754 var
755 { Streams to read/write a standard input/output/error of the program.
756
757 Tip: to read the standard input as a text file,
758 you can use @link(TTextReader) and @link(StdInStream):
759
760 @longCode(#
761 var
762 StdInReader: TTextReader;
763 begin
764 StdInReader := TTextReader.Create(StdInStream, false);
765 try
766 while not StdInReader.Eof do
767 DoSomethingWithInputLine(StdInReader.Readln);
768 finally FreeAndNil(StdinReader) end;
769 end;
770 #)
771
772 The advantage of using @link(TTextReader) above,
773 compared to using the standard Pascal @code(Readln) procedure
774 to read from the standard Pascal @code(Input) text file,
775 is that you can easily modify the above code to read from @italic(any)
776 stream. So, instead of the standard input, you can easily read
777 some stream that decompresses gzip data, or downloads data from
778 the Internet... Actually, the overloaded constructor
779 @link(TTextReader.Create) can accept an URL, like a @code(file://...)
780 or @code(http://...), and will internally use the stream returned
781 by @link(Download) function for this URL.
782
783 Notes @bold(only for Windows GUI applications):
784
785 @orderedList(
786 @item(
787 Some (or all) of the variables below may be @nil in a Windows GUI
788 application.
789
790 If you want to be on the safe side, then don't use these streams
791 in the GUI application (when IsConsole = false on Windows).
792 But (with some caveats, see below) you can sometimes use them,
793 if they are not-nil.
794 )
795
796 @item(
797 You @italic(can) have some of the standard streams available,
798 even in a GUI application.
799
800 User can run a GUI program and explicitly redirect it's standard stream,
801 e.g. @code(cat something | my_program.exe) for stdin or
802 @code(my_program.exe > output.txt) for stdout. Actually
803 some shells, like Cygwin's bash, always redirect some streams
804 under the hood.
805
806 Note that the FPC (and Delphi?) RTL may not provide the standard
807 Input/Output/ErrOutput in this case (because IsConsole = false),
808 but we try a little harder, regardless of the IsConsole value.
809 )
810
811 @item(
812 Caveat: in a GUI program under Windows you @italic(cannot)
813 depend on the fact that "StdOutStream <> nil means that stdout
814 is actually available (because user redirected stdout etc.)".
815 A first write to the StdOutStream may cause EWriteError,
816 so watch out for this.
817
818 This is tested on Windows 2000 Prof, with FPC 2.0.0 and 2.1.1 (revision 4317).
819 When no stdout is available, StdOutStream should be nil, because
820 GetStdHandle(STD_OUTPUT_HANDLE) should return 0. However,
821 GetStdHandle(STD_OUTPUT_HANDLE) doesn't return 0... It returns
822 some invalid handle (no, not INVALID_HANDLE_VALUE either)
823 that you can't write into (trying to write returns in ERROR_INVALID_HANDLE
824 WinAPI error). It seems that there is no way for me to check
825 whether GetStdHandle(STD_OUTPUT_HANDLE) returned valid handle
826 (e.g. because the program's stdout was redirected, so stdout is perfectly
827 available) or whether it returned something unusable.
828
829 Note that GetStdHandle(STD_INPUT_HANDLE) and GetStdHandle(STD_ERROR_HANDLE)
830 work correctly, so it should be OK to check StdInStream <> nil or
831 StdErrStream <> nil. The only problematic one is GetStdHandle(STD_OUTPUT_HANDLE).)
832 )
833 )
834 }
835 StdInStream, StdOutStream, StdErrStream: TStream;
836
837 { ---------------------------------------------------------------------------- }
838 { @section(Containers) }
839
840 type
841 { Extended TObjectStack for Castle Game Engine. }
842 TCastleObjectStack = class({$ifndef PASDOC}Contnrs.{$endif}TObjectStack)
843 private
844 function GetCapacity: TListSize;
845 procedure SetCapacity(const Value: TListSize);
846 public
847 property Capacity: TListSize read GetCapacity write SetCapacity;
848 end;
849
850 { Extended TObjectQueue for Castle Game Engine. }
851 TCastleObjectQueue = class({$ifndef PASDOC}Contnrs.{$endif}TObjectQueue)
852 private
853 function GetCapacity: TListSize;
854 procedure SetCapacity(const Value: TListSize);
855 public
856 property Capacity: TListSize read GetCapacity write SetCapacity;
857 end;
858
859 { Extended TObjectList for Castle Game Engine. }
860 TCastleObjectList = class({$ifndef PASDOC}Contnrs.{$endif}TObjectList)
861 public
862 { Create and fill with the contents of given array.
863
864 Since in ObjectPascal you can create open array parameter on the fly,
865 this constructor is often comfortable to use, for example you can
866 write @code(List := TCastleObjectList.Create(..., [Item1, Item2]);). }
867 constructor CreateFromArray(const FreeObjects: boolean;
868 const AItems: array of TObject);
869
870 { Add contents of given array to the list. }
871 procedure AddRange(const A: array of TObject); overload;
872 procedure AddArray(const A: array of TObject); deprecated 'use AddRange, consistent with other lists';
873
874 { Add contents of other TObjectList instance to the list. }
875 procedure AddRange(AList: Contnrs.TObjectList); overload;
876 procedure AddList(AList: Contnrs.TObjectList); deprecated 'use AddRange, consistent with other lists';
877
878 { Replace first found descendant of ReplaceClass with NewItem.
879 In case no descendant of ReplaceClass was found,
880 we'll we add NewItem to the list (depending on AddEnd value:
881 at the beginning or at the end of the list).
882
883 If NewItem is @nil, this simply removes the first found
884 descendant of ReplaceClass.
885
886 Returns the replaced (or removed) old item. It is removed from
887 the list just like the Extract method, so it's never freed.
888 Or @nil, if none was found (or there was @nil inside the list).
889
890 The typical use scenario for this method is when NewItem is also
891 a descendant from ReplaceClass, and you always keep at most one
892 ReplaceClass descendant on the list.
893 For example, you have UI controls list (like
894 TCastleWindow.Controls), and you want your NewItem to be the only instance
895 of TCastleOnScreenMenu class inside.
896 Moreover, in case order on the list is important (for example on
897 TCastleWindow.Controls order corresponds to screen depth --- what control
898 is under / above each other), you want to place NewItem at the same
899 position as previous TCastleOnScreenMenu instance, if any. }
900 function MakeSingle(ReplaceClass: TClass; NewItem: TObject;
901 AddEnd: boolean): TObject; deprecated 'this is a complicated method without clear use-case now; do not use';
902
903 { Extract (remove from the list, but never free) given item index.
904 This is similar TObjectList.Extract, except it takes an index. }
905 function Extract(Index: Integer): TObject; overload;
906
907 { Extract (remove from the list, but never free) first found descendant of
908 RemoveClass. Returns the removed item. Or @nil, if none was found
909 (or there was @nil inside the list and it got removed). }
910 function Extract(RemoveClass: TClass): TObject; overload;
911
912 { Delete (do not free) all found instances of the given Item.
913 Shifts all other pointers to the left.
914 Returns how many instances were removed (that is, how much Count
915 was decreased). }
916 function RemoveAll(Item: TObject): Cardinal;
917
918 function IsFirst(Value: TObject): boolean;
919 function IsLast(Value: TObject): boolean;
920
921 procedure InsertIfNotExists(Index: Integer; Value: TObject);
922 procedure AddIfNotExists(Value: TObject);
923 end;
924
925 TNotifyEventList = class({$ifdef FPC}specialize{$endif} TList<TNotifyEvent>)
926 public
927 { Call all (assigned) Items, from first to last. }
928 procedure ExecuteAll(Sender: TObject);
929
930 { Call all (assigned) Items, from first to last. }
931 procedure ExecuteForward(Sender: TObject);
932
933 { Call all (assigned) Items, from last to first. }
934 procedure ExecuteBackward(Sender: TObject);
935 end;
936
937 TSimpleNotifyEventList = class({$ifdef FPC}specialize{$endif} TList<TSimpleNotifyEvent>)
938 public
939 { Call all (assigned) Items, from first to last. }
940 procedure ExecuteAll;
941
942 { Remove all unassigned items. }
943 procedure Pack;
944
945 { Unassign all items equal this Event.
946 This is useful to do when (possibly) iterating over this list,
947 and doing Remove(Event) would be risky (shifting the items order).
948 So it's safer to do Unassign(Event) and call Pack once we don't iterate
949 over the list anymore. }
950 procedure Unassign(const Event: TSimpleNotifyEvent);
951 end;
952
953 TProcedureList = class({$ifdef FPC}specialize{$endif} TList<TProcedure>)
954 public
955 { Call all (assigned) Items, from first to last. }
956 procedure ExecuteAll;
957 end;
958
959 {$ifdef FPC}
960 function DumpStackToString(const BaseFramePointer: Pointer): string;
961 function DumpExceptionBackTraceToString: string;
962 {$endif}
963
964 { Propose a name for given component class, making it unique
965 in given ComponentsOwner.
966
967 If you provide non-empty BaseName, it will be used as component base name,
968 and we will only add numeric suffix to make it unique.
969 Make sure in this case that BaseName is a valid Pascal identifier.
970
971 If you leave empty BaseName, we will use ComponentClass.ClassName
972 to generate a useful base name. Again, we will add numeric suffix
973 to make it unique. }
974 function ProposeComponentName(const ComponentClass: TComponentClass;
975 const ComponentsOwner: TComponent;
976 BaseName: String = ''): String;
977
978 function InternalProposeName(const ComponentClass: TComponentClass;
979 const ComponentsOwner: TComponent): String;
980 deprecated 'use ProposeComponentName';
981
982 type
983 TFreeNotificationObserver = class;
984
985 { Notification from TFreeNotificationObserver.
986 Note that it doesn't specify the freed component,
987 because you can get it from @code(Sender.Observed) if needed. }
988 TFreeNotificationEvent = procedure (const Sender: TFreeNotificationObserver) of object;
989
990 (*Observe when something is freed, and call an event then.
991 You need to set @link(Observed) of this component
992 to make it notified about freeing of something.
993 When the @link(Observed) is freed, this component will make OnFreeNotification event.
994
995 An example code using it:
996
997 @longCode(#
998 type
999 TChild = class(TComponent)
1000 end;
1001
1002 TContainer = class(TComponent)
1003 private
1004 FChild: TChild;
1005 FChildObserver: TFreeNotificationObserver;
1006 procedure SetChild(const Value: TChild);
1007 procedure ChildFreeNotification(const Sender: TFreeNotificationObserver);
1008 public
1009 constructor Create(AOwner: TComponent);
1010 property Child: TChild read FChild write SetChild;
1011 end;
1012
1013 implementation
1014
1015 constructor TContainer.Create(AOwner: TComponent);
1016 begin
1017 inherited;
1018 FChildObserver := TFreeNotificationObserver.Create(Self);
1019 FChildObserver.OnFreeNotification := @ChildFreeNotification;
1020 end;
1021
1022 procedure TContainer.SetChild(const Value: TChild);
1023 begin
1024 if FChild <> Value then
1025 begin
1026 FChild := Value;
1027 FChildObserver.Observed := Value;
1028 end;
1029 end;
1030
1031 procedure TContainer.ChildFreeNotification(const Sender: TFreeNotificationObserver);
1032 begin
1033 FChild := nil;
1034 end;
1035 #)
1036
1037 Using this is an alternative to observing freeing using
1038 standard TComponent.FreeNotification / TComponent.RemoveFreeNotification mechanism
1039 https://castle-engine.io/modern_pascal_introduction.html#_free_notification .
1040 Using TFreeNotificationObserver is:
1041
1042 @unorderedList(
1043 @item(A bit simpler and it's harder to make a mistake.
1044
1045 E.g. the line @code(FChildObserver.Observed := Value) is simpler
1046 than the typical equivalent lines required to unregister notification
1047 of the old value and register notification of the new value.
1048 (See https://castle-engine.io/modern_pascal_introduction.html#_free_notification
1049 example of FreeNotification usage.)
1050 )
1051
1052 @item(The TContainer doesn't need to descend from TComponent.
1053
1054 You can manually free FChildObserver in the TContainer.Destroy.)
1055
1056 @item(Reliable if one class wants to observe freeing of multiple properties,
1057 and some of those properties may be sometimes equal.
1058 In this case using FreeNotification / RemoveFreeNotification with the main class
1059 would be unreliable (as RemoveFreeNotification removes the notification,
1060 even if you registered to it twice by FreeNotification), and requires complicated
1061 code to handles these special cases.
1062
1063 Using this component as a "proxy" to track each property is simpler,
1064 there's no additional code to handle this case. You just need different
1065 observer for each property to be observed.)
1066 )
1067
1068 As the owner of this TFreeNotificationObserver instance (given as parameter
1069 to the constructor, TFreeNotificationObserver.Create) you almost always
1070 want to pass the instance that has the method you will associate
1071 with @link(OnFreeNotification). In most cases (see also example above) this is
1072 available as just "Self". This means that TFreeNotificationObserver
1073 will be freed (and will no longer generate @link(OnFreeNotification))
1074 when the instance holding the associated method is freed, not later
1075 (which would mean the notification callback is called on non-existing instance,
1076 leading to an access violation).
1077 *)
1078 TFreeNotificationObserver = class(TComponent)
1079 strict private
1080 FObserved: TComponent;
1081 FOnFreeNotification: TFreeNotificationEvent;
1082 procedure SetObserved(const Value: TComponent);
1083 protected
1084 procedure Notification(AComponent: TComponent; Operation: TOperation); override;
1085 public
1086 destructor Destroy; override;
1087
1088 { Called when we receive notification that something was freed. }
1089 property OnFreeNotification: TFreeNotificationEvent read FOnFreeNotification write FOnFreeNotification;
1090
1091 { Setting this property makes the given component observed, freeing it will make
1092 OnFreeNotification.
1093 When setting, the previous value of this property stops being observed.
1094
1095 Note that this property will be automatically changed to @nil after OnFreeNotification,
1096 if the OnFreeNotification will not change it. This is necessary (we need to detach
1097 our "free notification" from a component that will be freed) and makes it safer
1098 (we will not expose dangling pointer). }
1099 property Observed: TComponent read FObserved write SetObserved;
1100 end;
1101
1102 implementation
1103
1104 uses
1105 {$ifdef UNIX} {$ifdef FPC} Unix, {$endif} {$endif}
1106 {$ifdef MSWINDOWS} Windows, {$endif}
1107 StrUtils, Math {$ifdef FPC}, StreamIO, RTTIUtils {$endif}, TypInfo,
1108 CastleLog;
1109
1110 { TStrings helpers ------------------------------------------------------- }
1111
1112 procedure StringsAdd(Strs: TStrings; Count: integer; itemVal: string);
1113 var
1114 i: integer;
1115 begin
1116 for i := 1 to Count do Strs.Add(itemVal);
1117 end;
1118
1119 procedure AddStrArrayToStrings(const StrArr: array of string; strlist: TStrings);
1120 var
1121 i: integer;
1122 begin
1123 for i := 0 to High(StrArr) do strlist.Append(StrArr[i]);
1124 end;
1125
1126 constructor TStringListCaseSens.Create;
1127 begin
1128 inherited;
1129 CaseSensitive := true;
1130 end;
1131
1132 procedure Strings_AddSplittedString(Strings: TStrings;
1133 const S, Splitter: string);
1134 var
1135 SplitterPos, Done: Integer;
1136 begin
1137 Done := 0;
1138 SplitterPos := Pos(Splitter, S);
1139 while SplitterPos <> 0 do
1140 begin
1141 Strings.Append(CopyPos(S, Done + 1, SplitterPos - 1));
1142 Done := SplitterPos + Length(Splitter) - 1;
1143 SplitterPos := PosEx(Splitter, S, Done + 1);
1144 end;
1145 Strings.Append(SEnding(S, Done + 1));
1146 end;
1147
1148 procedure Strings_SetText(SList: TStrings; const S: String);
1149 begin
1150 if Length(S) = 1 then
1151 SList.Text := S + LineEnding else
1152 SList.Text := S;
1153 end;
1154
1155 procedure Strings_Trim(Strings: TStrings; MaxCount: Cardinal);
1156 begin
1157 while Cardinal(Strings.Count) > MaxCount do
1158 Strings.Delete(Strings.Count - 1);
1159 end;
1160
1161 { TStream helpers -------------------------------------------------------- }
1162
1163 { // Unused
1164 procedure StreamWriteByte(Stream: TStream; const Value: Byte);
1165 begin
1166 Stream.WriteBuffer(Value, SizeOf(Value));
1167 end;
1168
1169 function StreamReadByte(Stream: TStream): Byte;
1170 begin
1171 Stream.ReadBuffer(Result, SizeOf(Result));
1172 end;
1173 }
1174
1175 procedure WriteStr(const Stream: TStream; const S: AnsiString);
1176 begin
1177 Stream.WriteBuffer(Pointer(S)^, Length(S));
1178 end;
1179
1180 procedure WritelnStr(const Stream: TStream; const S: AnsiString);
1181 begin
1182 WriteStr(Stream, S);
1183 WriteStr(Stream, nl);
1184 end;
1185
1186 procedure WriteStr(const S: AnsiString);
1187 begin
1188 WriteStr(StdOutStream, S);
1189 end;
1190
1191 procedure WritelnStr(const S: AnsiString);
1192 begin
1193 WritelnStr(StdOutStream, S);
1194 end;
1195
1196 {$ifndef FPC}
1197 {$warnings off}
1198
1199 procedure WriteStr(const Stream: TStream; const S: String);
1200 begin
1201 WriteStr(Stream, AnsiString(S));
1202 end;
1203
1204 procedure WritelnStr(const Stream: TStream; const S: String);
1205 begin
1206 WritelnStr(Stream, AnsiString(S));
1207 end;
1208
1209 procedure WriteStr(const S: String);
1210 begin
1211 WriteStr(AnsiString(S));
1212 end;
1213
1214 procedure WritelnStr(const S: String);
1215 begin
1216 WritelnStr(AnsiString(S));
1217 end;
1218
1219 {$warnings on}
1220 {$endif}
1221
1222 function StreamReadChar(Stream: TStream): AnsiChar;
1223 begin
1224 Stream.ReadBuffer(result, SizeOf(result));
1225 end;
1226
1227 function StreamReadZeroEndString(Stream: TStream): AnsiString;
1228 begin
1229 result := StreamReadUpto_NotEOS(Stream, [#0], false);
1230 end;
1231
1232 function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars;
1233 backEndingChar: boolean; out endingChar: AnsiChar): AnsiString; overload;
1234 var
1235 readLen: integer; { ile znakow odczytales }
1236 ch: AnsiChar;
1237 begin
1238 readLen := 0;
1239 result := '';
1240 repeat
1241 Stream.ReadBuffer(ch, 1);
1242 if ch in endingChars then
1243 begin
1244 endingChar := ch;
1245 break;
1246 end;
1247
1248 {zwiekszamy Length(result) o duze bloki zeby nie marnowac czasu
1249 na wiele malych realokacji pamieci}
1250 Inc(readLen);
1251 if readLen > Length(result) then SetLength(result, readLen + 100);
1252 result[readLen] := ch;
1253 until false;
1254
1255 if backEndingChar then Stream.Seek(-1, soFromCurrent);
1256
1257 SetLength(result, readLen);
1258 end;
1259
1260 function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars;
1261 backEndingChar: boolean):AnsiString; overload;
1262 var
1263 dummy: AnsiChar;
1264 begin
1265 result := StreamReadUpto_NotEOS(Stream, endingChars, backEndingChar, dummy);
1266 end;
1267
1268 function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars;
1269 out endingChar: AnsiChar): AnsiString;
1270 begin
1271 result := StreamReadUpto_NotEOS(Stream, endingChars, false, endingChar);
1272 end;
1273
1274 function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars): AnsiString;
1275 begin
1276 result := StreamReadUpto_NotEOS(Stream, endingChars, false);
1277 end;
1278
1279 function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars;
1280 backEndingChar: boolean; out endingChar: integer): AnsiString; overload;
1281 var readLen: integer; { ile znakow odczytales }
1282 ch: AnsiChar;
1283 begin
1284 readLen := 0;
1285 result := '';
1286 repeat
1287 if Stream.Read(ch, 1) = 0 then
1288 begin
1289 endingChar := -1;
1290 break;
1291 end else
1292 if ch in endingChars then
1293 begin
1294 endingChar := Ord(ch);
1295 break;
1296 end;
1297
1298 {zwiekszamy Length(result) o duze bloki zeby nie marnowac czasu
1299 na wiele malych realokacji pamieci}
1300 Inc(readLen);
1301 if readLen > Length(result) then SetLength(result, readLen+100);
1302 result[readLen] := ch;
1303 until false;
1304
1305 if backEndingChar then
1306 if endingChar <> -1 then Stream.Seek(-1, soFromCurrent);
1307
1308 SetLength(result, readLen);
1309 end;
1310
1311 function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars;
1312 backEndingChar: boolean): AnsiString; overload;
1313 var
1314 dummy: integer;
1315 begin
1316 result := StreamReadUpto_EOS(Stream, endingChars, backEndingChar, dummy);
1317 end;
1318
1319 function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars;
1320 out endingChar: integer): AnsiString;
1321 begin
1322 result := StreamReadUpto_EOS(Stream, endingChars, false, endingChar);
1323 end;
1324
1325 function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars): AnsiString;
1326 begin
1327 result := StreamReadUpto_EOS(Stream, endingChars, false);
1328 end;
1329
1330 procedure ReadGrowingStream(const GrowingStream, DestStream: TStream;
1331 const ResetDestStreamPosition: Boolean;
1332 const BufferSize: Cardinal);
1333 var
1334 ReadCount: Integer;
1335 Buffer: Pointer;
1336 begin
1337 Buffer := GetMem(BufferSize);
1338 try
1339 repeat
1340 ReadCount := GrowingStream.Read(Buffer^, BufferSize);
1341 if ReadCount = 0 then Break;
1342 DestStream.WriteBuffer(Buffer^, ReadCount);
1343 until false;
1344 finally FreeMemNiling(Buffer) end;
1345 if ResetDestStreamPosition then DestStream.Position := 0;
1346 end;
1347
1348 function ReadGrowingStreamToMemory(const GrowingStream: TStream): TMemoryStream;
1349 const
1350 BufferSize = 1000 * 1000;
1351 var
1352 ReadCount: Integer;
1353 TotalReadCount: PtrUInt;
1354 MemoryStart: Pointer;
1355 begin
1356 Result := TMemoryStream.Create;
1357 try
1358 TotalReadCount := 0;
1359 repeat
1360 { Note: on 32-bit systems,
1361 - TStream.Size is still Int64 (as on all platforms)
1362 - But allocated memory for pointer is at most High(UInt32) = High(PtrUInt)
1363 Let the assignment "Result.Size" below raise an exception
1364 if trying to read file with size > High(UInt32). }
1365 Result.Size := Int64(TotalReadCount) + BufferSize;
1366
1367 MemoryStart := Pointer(PtrUInt(Result.Memory) + TotalReadCount);
1368 ReadCount := GrowingStream.Read(MemoryStart^, BufferSize);
1369 if ReadCount = 0 then Break;
1370 TotalReadCount := TotalReadCount + ReadCount;
1371 until false;
1372 Result.Size := TotalReadCount;
1373 except FreeAndNil(Result); raise end;
1374 end;
1375
1376 function ReadGrowingStreamToString(const GrowingStream: TStream): AnsiString;
1377 var
1378 Memory: TMemoryStream;
1379 begin
1380 Memory := ReadGrowingStreamToMemory(GrowingStream);
1381 try
1382 SetLength(Result, Memory.Size);
1383 if Memory.Size <> 0 then
1384 Move(Memory.Memory^, Result[1], Memory.Size);
1385 finally FreeAndNil(Memory) end;
1386 end;
1387
1388 function ReadGrowingStreamToDefaultString(const GrowingStream: TStream): String;
1389 var
1390 Memory: TMemoryStream;
1391 begin
1392 Memory := ReadGrowingStreamToMemory(GrowingStream);
1393 try
1394 {$warnings off} // this makes FPS warning "unreachable code" but it makes sense on Delphi, we want to keep compiling it
1395 if (Memory.Size mod SizeOf(Char)) <> 0 then
1396 raise Exception.CreateFmt('ReadGrowingStreamToDefaultString: stream size %d is not a multiple of SizeOf(Char) = %d', [
1397 Memory.Size,
1398 SizeOf(Char)
1399 ]);
1400 {$warnings on}
1401
1402 SetLength(Result, Memory.Size div SizeOf(Char));
1403 if Memory.Size <> 0 then
1404 Move(Memory.Memory^, Result[1], Memory.Size);
1405 finally FreeAndNil(Memory) end;
1406 end;
1407
1408 procedure StreamWriteString(const Stream: TStream; const S: AnsiString);
1409 var
1410 L: Integer;
1411 begin
1412 L := Length(s);
1413 Stream.WriteBuffer(L, SizeOf(L));
1414 { check L > 0 to avoid range check error on S[1] }
1415 if L > 0 then Stream.WriteBuffer(S[1], L);
1416 end;
1417
1418 function StreamReadString(const Stream: TStream): AnsiString;
1419 var
1420 L: Integer;
1421 begin
1422 Stream.ReadBuffer(L, SizeOf(L));
1423 SetLength(Result, L);
1424 { check L > 0 to avoid range check error on Result[1] }
1425 if L > 0 then Stream.ReadBuffer(Result[1], L);
1426 end;
1427
1428 function StreamToString(const Stream: TStream): AnsiString;
1429 begin
1430 SetLength(Result, Stream.Size);
1431 Stream.Position := 0;
1432 Stream.ReadBuffer(Pointer(Result)^, Length(Result));
1433 end;
1434
1435 procedure MemoryStreamLoadFromString(const Stream: TMemoryStream;
1436 const S: AnsiString; const Rewind: boolean);
1437 begin
1438 Stream.Size := Length(S);
1439 if S <> '' then
1440 begin
1441 Stream.WriteBuffer(S[1], Length(S));
1442 if Rewind then Stream.Position := 0;
1443 end;
1444 end;
1445
1446 function MemoryStreamLoadFromString(const S: AnsiString; const Rewind: boolean): TMemoryStream;
1447 begin
1448 Result := TMemoryStream.Create;
1449 try
1450 MemoryStreamLoadFromString(Result, S, Rewind);
1451 except FreeAndNil(Result); raise end;
1452 end;
1453
1454 procedure MemoryStreamLoadFromDefaultString(const Stream: TMemoryStream;
1455 const S: String; const Rewind: boolean);
1456 begin
1457 Stream.Size := Length(S) * SizeOf(Char);
1458 if S <> '' then
1459 begin
1460 Stream.WriteBuffer(S[1], Length(S) * SizeOf(Char));
1461 if Rewind then Stream.Position := 0;
1462 end;
1463 end;
1464
1465 function MemoryStreamLoadFromDefaultString(const S: String; const Rewind: boolean): TMemoryStream;
1466 begin
1467 Result := TMemoryStream.Create;
1468 try
1469 MemoryStreamLoadFromDefaultString(Result, S, Rewind);
1470 except FreeAndNil(Result); raise end;
1471 end;
1472
1473 { TPeekCharStream -------------------------------------------------- }
1474
1475 constructor TPeekCharStream.Create(ASourceStream: TStream;
1476 AOwnsSourceStream: boolean);
1477 begin
1478 inherited Create;
1479 FOwnsSourceStream := AOwnsSourceStream;
1480 FSourceStream := ASourceStream;
1481 FLine := 1;
1482 FColumn := 1;
1483 end;
1484
1485 destructor TPeekCharStream.Destroy;
1486 begin
1487 if OwnsSourceStream then FreeAndNil(FSourceStream);
1488 inherited;
1489 end;
1490
1491 function TPeekCharStream.GetSize: Int64;
1492 begin
1493 Result := SourceStream.Size;
1494 end;
1495
1496 procedure TPeekCharStream.SetSize(NewSize: Longint);
1497 begin
1498 raise EStreamNotImplementedSetSize.Create(
1499 'TPeekCharStream.SetSize not supported');
1500 end;
1501
1502 function TPeekCharStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
1503 begin
1504 raise EStreamNotImplementedSeek.Create('TPeekCharStream.Seek not supported');
1505 {$ifdef FPC}
1506 Result := 0; { just to get rid of dummy fpc warning }
1507 {$endif}
1508 end;
1509
1510 function TPeekCharStream.Write(const Buffer; Count: Longint): Longint;
1511 begin
1512 raise EStreamNotImplementedWrite.Create('TPeekCharStream.Write not supported');
1513 {$ifdef FPC}
1514 Result := 0; { just to get rid of dummy fpc warning }
1515 {$endif}
1516 end;
1517
1518 procedure TPeekCharStream.UpdateLineColumn(const C: AnsiChar);
1519 begin
1520 if (C = #13) or
1521 (C = #10) then
1522 begin
1523 // This way we increase FLine correctly for both Unix and Windows line ending
1524 if C = #10 then
1525 Inc(FLine);
1526 FColumn := 1;
1527 end else
1528 Inc(FColumn);
1529 end;
1530
1531 procedure TPeekCharStream.UpdateLineColumn(const Buffer; const BufferCount: Integer);
1532 var
1533 I: Integer;
1534 begin
1535 for I := 0 to BufferCount - 1 do
1536 UpdateLineColumn(PAnsiChar(@Buffer)[I]);
1537 end;
1538
1539 function TPeekCharStream.ReadUpto(const EndingChars: TSetOfChars): AnsiString;
1540 var
1541 Peeked: Integer;
1542 begin
1543 Result := '';
1544 while true do
1545 begin
1546 Peeked := PeekChar;
1547 if (Peeked = -1) or (AnsiChar(Peeked) in EndingChars) then
1548 Exit;
1549 { ReadChar will return same thing as Peeked now }
1550 Result := Result + AnsiChar(ReadChar);
1551 end;
1552 end;
1553
1554 { Notes about TPeekCharStream.Read overriding:
1555
1556 This tries to read next Count bytes from SourceStream, making sure
1557 that even character that you obtained by PeekChar will be returned
1558 here. In other words, this just implements Read method of TStream :)
1559
1560 This may call SourceStream.Read, and any exceptions that may be
1561 raised in SourceStream.Read are propagated higher from this method.
1562 }
1563
1564 { TSimplePeekCharStream --------------------------------------------------- }
1565
1566 function TSimplePeekCharStream.GetPosition: Int64;
1567 begin
1568 Result := FPosition;
1569 end;
1570
1571 function TSimplePeekCharStream.Read(var Buffer; Count: Longint): Longint;
1572 begin
1573 if (Count <= 0) or
1574 (IsPeekedChar and (PeekedChar = -1)) then
1575 Result := 0 else
1576 if IsPeekedChar then
1577 begin
1578 { Note: It would be more natural to access
1579 PAnsiChar(@Buffer)[...],
1580 but on Delphi the PAnsiChar cannot be indexed like an array. }
1581 PByteArray(@Buffer)^[0] := PeekedChar;
1582 Result := 1 + SourceStream.Read(PByteArray(@Buffer)^[1], Count - 1);
1583 { Note that if SourceStream.Read will raise an exception,
1584 we will still have IsPeekedChar = true. }
1585 IsPeekedChar := false;
1586 end else
1587 Result := SourceStream.Read(Buffer, Count);
1588 FPosition := FPosition + Result;
1589
1590 UpdateLineColumn(Buffer, Result);
1591 end;
1592
1593 function TSimplePeekCharStream.PeekChar: Integer;
1594 var
1595 C: AnsiChar;
1596 begin
1597 if not IsPeekedChar then
1598 begin
1599 if SourceStream.Read(C, 1) = 0 then
1600 PeekedChar := -1
1601 else
1602 PeekedChar := Ord(C);
1603 IsPeekedChar := true;
1604 end;
1605 Result := PeekedChar;
1606 end;
1607
1608 function TSimplePeekCharStream.ReadChar: Integer;
1609 { This is somehow optimized version of TSimplePeekCharStream.Read
1610 for the case when Count = 1. }
1611 var
1612 C: AnsiChar;
1613 begin
1614 if IsPeekedChar then
1615 begin
1616 Result := PeekedChar;
1617 IsPeekedChar := false;
1618 Inc(FPosition);
1619 end else
1620 begin
1621 if SourceStream.Read(C, 1) = 0 then
1622 Result := -1 else
1623 begin
1624 Result := Ord(C);
1625 Inc(FPosition);
1626 end;
1627 end;
1628
1629 if Result <> -1 then
1630 UpdateLineColumn(AnsiChar(Result));
1631 end;
1632
1633 { TBufferedReadStream ----------------------------------------------------- }
1634
1635 constructor TBufferedReadStream.Create(ASourceStream: TStream;
1636 AOwnsSourceStream: boolean; ABufferSize: Cardinal);
1637 begin
1638 inherited Create(ASourceStream, AOwnsSourceStream);
1639
1640 FBufferSize := ABufferSize;
1641 Buffer := GetMem(BufferSize);
1642 BufferPos := 0;
1643 BufferEnd := 0;
1644 end;
1645
1646 destructor TBufferedReadStream.Destroy;
1647 begin
1648 FreeMemNiling(Pointer(Buffer));
1649 inherited;
1650 end;
1651
1652 function TBufferedReadStream.GetPosition: Int64;
1653 begin
1654 Result := FPosition;
1655 end;
1656
1657 procedure TBufferedReadStream.FillBuffer;
1658 begin
1659 BufferEnd := SourceStream.Read(Buffer^[0], BufferSize);
1660 BufferPos := 0;
1661 end;
1662
1663 function TBufferedReadStream.Read(var LocalBuffer; Count: Longint): Longint;
1664 var
1665 CopyCount: Cardinal;
1666 begin
1667 if Count < 0 then
1668 Result := 0 else
1669 if Cardinal(Count) <= BufferEnd - BufferPos then
1670 begin
1671 { In this case we can fill LocalBuffer using only data from Buffer }
1672 Move(Buffer^[BufferPos], LocalBuffer, Count);
1673 BufferPos := BufferPos + Cardinal(Count);
1674 Result := Count;
1675 end else
1676 begin
1677 Move(Buffer^[BufferPos], LocalBuffer, BufferEnd - BufferPos);
1678 Result := BufferEnd - BufferPos;
1679 BufferPos := BufferEnd;
1680 Count := Count - Result;
1681
1682 { Now we must read remaining Count bytes from SourceStream.
1683 If Count < BufferSize I must use Buffer (after all this is the purpose
1684 of TBufferedReadStream, to guarantee buffered reading).
1685 On the other hand, if Count >= BufferSize I can read it directly
1686 from SourceStream, no need to use Buffer in this case. }
1687 if Cardinal(Count) < BufferSize then
1688 begin
1689 FillBuffer;
1690 CopyCount := Min(Cardinal(Count), BufferEnd - BufferPos);
1691 Move(Buffer^[0], PChar(@LocalBuffer)[Result], CopyCount);
1692 BufferPos := BufferPos + CopyCount;
1693 Result := Result + LongInt(CopyCount);
1694 end else
1695 begin
1696 Result := Result + SourceStream.Read(PChar(@LocalBuffer)[Result], Count);
1697 end;
1698 end;
1699 FPosition := FPosition + Result;
1700
1701 UpdateLineColumn(LocalBuffer, Result);
1702 end;
1703
1704 function TBufferedReadStream.PeekChar: Integer;
1705 begin
1706 if BufferPos < BufferEnd then
1707 Result := Buffer^[BufferPos] else
1708 begin
1709 FillBuffer;
1710 if BufferPos < BufferEnd then
1711 Result := Buffer^[BufferPos] else
1712 Result := -1;
1713 end;
1714 end;
1715
1716 function TBufferedReadStream.ReadChar: Integer;
1717 begin
1718 if BufferPos < BufferEnd then
1719 begin
1720 Result := Buffer^[BufferPos];
1721 Inc(BufferPos);
1722 Inc(FPosition);
1723 end else
1724 begin
1725 FillBuffer;
1726 if BufferPos < BufferEnd then
1727 begin
1728 Result := Buffer^[BufferPos];
1729 Inc(BufferPos);
1730 Inc(FPosition);
1731 end else
1732 Result := -1;
1733 end;
1734
1735 if Result <> -1 then
1736 UpdateLineColumn(AnsiChar(Result));
1737 end;
1738
1739 function TBufferedReadStream.ReadUpto(const EndingChars: TSetOfChars): AnsiString;
1740 var
1741 Peeked: Integer;
1742 BufferBeginPos, OldResultLength, ReadCount: Cardinal;
1743 ConsumingChar: AnsiChar;
1744 begin
1745 Result := '';
1746 while true do
1747 begin
1748 Peeked := PeekChar;
1749 if (Peeked = -1) or (AnsiChar(Peeked) in EndingChars) then
1750 Exit;
1751
1752 (*Since this is TBufferedReadStream, we often have a lot of data in our
1753 Buffer. It would be wasteful to just check and copy it one-by-one,
1754 by code like:
1755
1756 Result := Result + Chr(Peeked);
1757
1758 { I could call above "Result := Result + Chr(ReadChar);"
1759 to make implementation of ReadUpto cleaner (not dealing
1760 with private fields of TStreamPeekChar).
1761
1762 But doing like I'm doing now works a little faster.
1763 After PeekChar with result <> -1 I know that I have one place in the buffer.
1764 So I just explicitly increment BufferPos below. }
1765 Inc(BufferPos);
1766 Inc(FPosition);
1767
1768 So the optimized version tries to grab as much as large as possible data
1769 chunk from the buffer, and copy it to Result at once.
1770 *)
1771
1772 UpdateLineColumn(AnsiChar(Peeked));
1773
1774 { Increase BufferPos as much as you can. We know that we can increase
1775 at least by one, since we just called PeekChar and it returned character
1776 <> -1 and not in EndingChars, so we use repeat...until instead of
1777 while...do. }
1778 BufferBeginPos := BufferPos;
1779 repeat
1780 Inc(BufferPos);
1781 if BufferPos >= BufferEnd then
1782 Break
1783 else
1784 begin
1785 ConsumingChar := AnsiChar(Buffer^[BufferPos]);
1786 if ConsumingChar in EndingChars then
1787 Break
1788 else
1789 UpdateLineColumn(ConsumingChar);
1790 end;
1791 until false;
1792
1793 ReadCount := BufferPos - BufferBeginPos;
1794
1795 { Increase FPosition by the same amount that BufferPos was incremented }
1796 FPosition := FPosition + ReadCount;
1797
1798 { Append Buffer^[BufferBeginPos... BufferPos - 1] to Result }
1799 OldResultLength := Length(Result);
1800 SetLength(Result, OldResultLength + ReadCount);
1801 Move(Buffer^[BufferBeginPos], Result[OldResultLength + 1], ReadCount);
1802 end;
1803 end;
1804
1805 { TComponent helpers --------------------------------------------------- }
1806
1807 procedure CreateIfNeeded(var Component: TComponent;
1808 ComponentClass: TComponentClass; Owner: TComponent);
1809 begin
1810 if Component = nil then
1811 Component := ComponentClass.Create(Owner);
1812 end;
1813
1814 { TCastleComponent.TNonVisualComponentsEnumerator ------------------------------------------------- }
1815
1816 { TNonVisualComponentsEnumerator is optimized to be a record, following
1817 https://hallvards.blogspot.com/2007/10/more-fun-with-enumerators.html }
1818
1819 constructor TCastleComponent.TNonVisualComponentsEnumerator.Create(const AParent: TCastleComponent);
1820 begin
1821 // inherited Create;
1822 FParent := AParent;
1823 FPosition := -1;
1824 end;
1825
1826 function TCastleComponent.TNonVisualComponentsEnumerator.GetCurrent: TComponent;
1827 begin
1828 Result := FParent.NonVisualComponents[FPosition];
1829 end;
1830
1831 function TCastleComponent.TNonVisualComponentsEnumerator.MoveNext: Boolean;
1832 begin
1833 Inc(FPosition);
1834 Result := FPosition < FParent.NonVisualComponentsCount;
1835 end;
1836
1837 function TCastleComponent.TNonVisualComponentsEnumerator.GetEnumerator: TNonVisualComponentsEnumerator;
1838 begin
1839 // Returns itself. See https://wiki.freepascal.org/for-in_loop
1840 Result := Self;
1841 end;
1842
1843 { TCastleComponent ----------------------------------------------------------- }
1844
1845 destructor TCastleComponent.Destroy;
1846 begin
1847 FreeAndNil(FNonVisualComponents);
1848 inherited;
1849 end;
1850
1851 procedure TCastleComponent.SetTransient;
1852 begin
1853 Include(FComponentStyle, csTransient);
1854 end;
1855
1856 function TCastleComponent.GetInternalText: String;
1857 begin
1858 Result := '';
1859 end;
1860
1861 procedure TCastleComponent.SetInternalText(const Value: String);
1862 begin
1863 end;
1864
1865 procedure TCastleComponent.InternalLoading;
1866 begin
1867 {$ifdef FPC}
1868 Loading;
1869 {$endif}
1870 FIsLoading := true;
1871 end;
1872
1873 procedure TCastleComponent.InternalLoaded;
1874 begin
1875 FIsLoading := false;
1876
1877 { We need to call Loaded because some things can be delayed to run after
1878 loading for example TCastleSceneCore.UpdateAutoAnimation() }
1879 Loaded;
1880 end;
1881
1882 procedure TCastleComponent.SetName(const Value: TComponentName);
1883 var
1884 ChangeInternalText: Boolean;
1885 begin
1886 { Implementation similar to procedure TControl.SetName in Lazarus. }
1887 if Name = Value then exit;
1888 ChangeInternalText :=
1889 // TControl.SetName does this even in non-design mode.
1890 // ((csDesigning in ComponentState) or CastleDesignMode) and
1891 //
1892 // Note that we don't do it during loading, otherwise having empty
1893 // Caption e.g. on TCastleButton would be impossible:
1894 // reading Name would set Caption.
1895 // During loading, we assume that all component properties are to be deserialized from file,
1896 // and InternalText should not be automatically modified.
1897 (not IsLoading) and
1898 (Name = InternalText) and
1899 // Do not update InternalText when Owner is during deserialization.
1900 ( (Owner = nil) or
1901 (not (Owner is TCastleComponent)) or
1902 (not TCastleComponent(Owner).IsLoading));
1903 // Note that this can raise exception is Value is not a valid name.
1904 inherited SetName(Value);
1905 if ChangeInternalText then
1906 InternalText := Value;
1907 end;
1908
1909 function TCastleComponent.PropertySections(const PropertyName: String): TPropertySections;
1910 begin
1911 if (PropertyName = 'Name') then
1912 Result := [psBasic]
1913 else
1914 Result := [];
1915 end;
1916
1917 procedure TCastleComponent.TranslateProperties(
1918 const TranslatePropertyEvent: TTranslatePropertyEvent);
1919 begin
1920 // nothing to do in this class
1921 end;
1922
1923 function TCastleComponent.NonVisualComponentsCount: Integer;
1924 begin
1925 if FNonVisualComponents = nil then
1926 Result := 0
1927 else
1928 Result := FNonVisualComponents.Count;
1929 end;
1930
1931 function TCastleComponent.GetNonVisualComponents(const Index: Integer): TComponent;
1932 begin
1933 { showing ERangeError will be nicer
1934 than showing EAccessViolation when accessing FNonVisualComponents below }
1935 if FNonVisualComponents = nil then
1936 System.Error(reRangeError);
1937 Result := FNonVisualComponents[Index];
1938 end;
1939
1940 procedure TCastleComponent.AddNonVisualComponent(const NonVisualComponent: TComponent);
1941 begin
1942 // create FNonVisualComponents on-demand, to not burden typical TCastleComponent that doesn't need this
1943 if FNonVisualComponents = nil then
1944 FNonVisualComponents := TComponentList.Create(false);
1945 FNonVisualComponents.Add(NonVisualComponent);
1946 end;
1947
1948 procedure TCastleComponent.InsertNonVisualComponent(const Index: Integer; const NonVisualComponent: TComponent);
1949 begin
1950 // create FNonVisualComponents on-demand, to not burden typical TCastleComponent that doesn't need this
1951 if FNonVisualComponents = nil then
1952 FNonVisualComponents := TComponentList.Create(false);
1953 FNonVisualComponents.Insert(Index, NonVisualComponent);
1954 end;
1955
1956 function TCastleComponent.NonVisualComponentsIndexOf(const NonVisualComponent: TComponent): Integer;
1957 begin
1958 if FNonVisualComponents <> nil then
1959 Result := FNonVisualComponents.IndexOf(NonVisualComponent)
1960 else
1961 Result := -1;
1962 end;
1963
1964 procedure TCastleComponent.RemoveNonVisualComponent(const NonVisualComponent: TComponent);
1965 begin
1966 if FNonVisualComponents <> nil then
1967 FNonVisualComponents.Remove(NonVisualComponent);
1968 end;
1969
1970 function TCastleComponent.NonVisualComponentsEnumerate: TNonVisualComponentsEnumerator;
1971 begin
1972 Result := TNonVisualComponentsEnumerator.Create(Self);
1973 end;
1974
1975 procedure TCastleComponent.CustomSerialization(const SerializationProcess: TSerializationProcess);
1976 begin
1977 inherited;
1978 SerializationProcess.ReadWriteList('NonVisualComponents',
1979 {$ifdef FPC}@{$endif} SerializeNonVisualComponentsEnumerate,
1980 {$ifdef FPC}@{$endif} SerializeNonVisualComponentsAdd,
1981 {$ifdef FPC}@{$endif} SerializeNonVisualComponentsClear);
1982 end;
1983
1984 procedure TCastleComponent.SerializeNonVisualComponentsEnumerate(const Proc: TGetChildProc);
1985 var
1986 I: Integer;
1987 begin
1988 if FNonVisualComponents <> nil then
1989 for I := 0 to FNonVisualComponents.Count - 1 do
1990 if FNonVisualComponents[I].ComponentStyle * [csSubComponent, csTransient] = [] then
1991 Proc(FNonVisualComponents[I]);
1992 end;
1993
1994 procedure TCastleComponent.SerializeNonVisualComponentsAdd(const C: TComponent);
1995 begin
1996 AddNonVisualComponent(C);
1997 end;
1998
1999 procedure TCastleComponent.SerializeNonVisualComponentsClear;
2000 var
2001 I: Integer;
2002 begin
2003 if FNonVisualComponents <> nil then
2004 for I := FNonVisualComponents.Count - 1 downto 0 do // downto, as list may shrink during loop
2005 if FNonVisualComponents[I].ComponentStyle * [csSubComponent, csTransient] = [] then
2006 FNonVisualComponents[I].Free; // will remove itself from Behaviors list
2007 end;
2008
2009 function TCastleComponent.ValueIsStreamed: Boolean;
2010 begin
2011 Result := true;
2012 end;
2013
2014 procedure TCastleComponent.DesignerInfo(const SList: TStrings);
2015 begin
2016 end;
2017
2018 procedure TCastleComponent.DesignerWarnings(const SList: TStrings);
2019 begin
2020 end;
2021
2022 { TComponent routines -------------------------------------------------------- }
2023
2024 type
2025 { Helper class to implement TranslateProperties.
2026
2027 Calls TranslatePropertyEvent on all "children", where "children" are all
2028 components that this class enumerated in CustomSerialization:
2029
2030 - all items on lists reported by ReadWriteList
2031
2032 - all subcomponents reported by ReadWriteSubComponent
2033 }
2034 TTranslatePropertiesOnChildren = class(TSerializationProcess)
2035 strict private
2036 procedure TranslatePropertiesOnChild(Child: TComponent);
2037 public
2038 TranslatePropertyEvent: TTranslatePropertyEvent;
2039 procedure ReadWriteInteger(const Key: String; var Value: Integer; const IsStored: Boolean);
2040 overload; override;
2041 procedure ReadWriteBoolean(const Key: String; var Value: Boolean; const IsStored: Boolean);
2042 overload; override;
2043 procedure ReadWriteString(const Key: String; var Value: String; const IsStored: Boolean);
2044 overload; override;
2045 procedure ReadWriteSingle(const Key: String; var Value: Single; const IsStored: Boolean);
2046 overload; override;
2047 procedure ReadWriteSubComponent(const Key: String; const Value: TComponent;
2048 const IsStored: Boolean); override;
2049 procedure ReadWriteList(const Key: String;
2050 const ListEnumerate: TSerializationProcess.TListEnumerateEvent;
2051 const ListAdd: TSerializationProcess.TListAddEvent;
2052 const ListClear: TSerializationProcess.TListClearEvent); override;
2053 end;
2054
2055 procedure TTranslatePropertiesOnChildren.TranslatePropertiesOnChild(Child: TComponent);
2056 begin
2057 TranslateProperties(Child, TranslatePropertyEvent);
2058 end;
2059
2060 procedure TTranslatePropertiesOnChildren.ReadWriteList(const Key: String;
2061 const ListEnumerate: TSerializationProcess.TListEnumerateEvent;
2062 const ListAdd: TSerializationProcess.TListAddEvent;
2063 const ListClear: TSerializationProcess.TListClearEvent);
2064 begin
2065 ListEnumerate({$ifdef FPC}@{$endif} TranslatePropertiesOnChild);
2066 end;
2067
2068 procedure TTranslatePropertiesOnChildren.ReadWriteSubComponent(
2069 const Key: String; const Value: TComponent; const IsStored: Boolean);
2070 begin
2071 TranslateProperties(Value, TranslatePropertyEvent);
2072 end;
2073
2074 procedure TTranslatePropertiesOnChildren.ReadWriteInteger(const Key: String; var Value: Integer; const IsStored: Boolean);
2075 begin
2076 // just override abstract method to do nothing
2077 end;
2078
2079 procedure TTranslatePropertiesOnChildren.ReadWriteBoolean(const Key: String; var Value: Boolean; const IsStored: Boolean);
2080 begin
2081 // just override abstract method to do nothing
2082 end;
2083
2084 procedure TTranslatePropertiesOnChildren.ReadWriteString(const Key: String; var Value: String; const IsStored: Boolean);
2085 begin
2086 // just override abstract method to do nothing
2087 end;
2088
2089 procedure TTranslatePropertiesOnChildren.ReadWriteSingle(const Key: String; var Value: Single; const IsStored: Boolean);
2090 begin
2091 // just override abstract method to do nothing
2092 end;
2093
2094 procedure TranslateProperties(const C: TComponent;
2095 const TranslatePropertyEvent: TTranslatePropertyEvent);
2096
2097 { Call TranslateProperties on C and its children. }
2098 procedure TranslateChildClass(const C: TObject);
2099 begin
2100 if (C is TComponent) and // also checks is C <> nil
2101 (csSubComponent in TComponent(C).ComponentStyle) then
2102 TranslateProperties(TComponent(C), TranslatePropertyEvent);
2103
2104 { One day we may add here special handling
2105 of TCollection and TObjectList, like TJSONStreamer.StreamClassProperty. }
2106 end;
2107
2108 {$ifdef FPC}
2109 var
2110 PropInfos: TPropInfoList;
2111 PropInfo: PPropInfo;
2112 TypeInfo: PTypeInfo;
2113 I: Integer;
2114 ChildrenEnumerator: TTranslatePropertiesOnChildren;
2115 begin
2116 if C is TCastleComponent then
2117 begin
2118 // translate properties of C
2119 TCastleComponent(C).TranslateProperties(TranslatePropertyEvent);
2120
2121 // translate properties of C children
2122 ChildrenEnumerator := TTranslatePropertiesOnChildren.Create;
2123 try
2124 ChildrenEnumerator.TranslatePropertyEvent := TranslatePropertyEvent;
2125 TCastleComponent(C).CustomSerialization(ChildrenEnumerator);
2126 finally FreeAndNil(ChildrenEnumerator) end;
2127 end;
2128
2129 // translate properties of other C serialized children
2130 PropInfos := TPropInfoList.Create(C, tkProperties);
2131 try
2132 for I := 0 to PropInfos.Count - 1 do
2133 begin
2134 PropInfo := PropInfos[I];
2135 TypeInfo := PropInfo^.PropType {$ifndef FPC}^{$endif};
2136 if TypeInfo^.Kind = tkClass then
2137 TranslateChildClass(GetObjectProp(C, PropInfo));
2138 end;
2139 finally FreeAndNil(PropInfos) end;
2140 {$else}
2141 begin
2142 WritelnWarning('Localization (TranslateProperties) not implemented for Delphi yet.');
2143 {$endif}
2144 end;
2145
2146 { initialization / finalization ---------------------------------------------- }
2147
2148 procedure InitStdStreams;
2149
2150 { Note that instead of GetStdHandle(STD_INPUT_HANDLE) I could just use
2151 StdInputHandle, as this is initialized by FPC RTL exactly to
2152 GetStdHandle(STD_INPUT_HANDLE). Same for other Std*Handle.
2153 However
2154 1. This would not allow me to write InitStdStream without any $ifdefs,
2155 because Windows would still require checking for 0 and INVALID_HANDLE_VALUE
2156 2. This is not documented, so I prefer to not depend on this.
2157 For example, maybe in the future StdInputHandle will be always left as 0
2158 when not IsConsole? I want to exactly avoid this for my Std*Stream.
2159 }
2160
2161 {$ifdef MSWINDOWS}
2162 procedure InitStdStream(var Stream: TStream; nStdHandle: DWord);
2163 var
2164 Handle: THandle;
2165 begin
2166 Handle := GetStdHandle(nStdHandle);
2167 { If the function fails, the return value is INVALID_HANDLE_VALUE.
2168 If an application does not have associated standard handles,
2169 the return value is NULL.
2170 See [http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/getstdhandle.asp] }
2171 if (Handle <> INVALID_HANDLE_VALUE) and
2172 (Handle <> 0) then
2173 Stream := THandleStream.Create(Handle) else
2174 Stream := nil;
2175 end;
2176 {$endif MSWINDOWS}
2177
2178 {$ifdef UNIX}
2179 procedure InitStdStream(var Stream: TStream; Handle: THandle);
2180 begin
2181 Stream := THandleStream.Create(Handle);
2182 end;
2183 {$endif UNIX}
2184
2185 begin
2186 InitStdStream(StdInStream, {$ifdef MSWINDOWS} STD_INPUT_HANDLE {$else} StdInputHandle {$endif});
2187 InitStdStream(StdOutStream, {$ifdef MSWINDOWS} STD_OUTPUT_HANDLE {$else} StdOutputHandle {$endif});
2188 InitStdStream(StdErrStream, {$ifdef MSWINDOWS} STD_ERROR_HANDLE {$else} StdErrorHandle {$endif});
2189 end;
2190
2191 procedure FiniStdStreams;
2192 begin
2193 FreeAndNil(StdInStream);
2194 FreeAndNil(StdOutStream);
2195 FreeAndNil(StdErrStream);
2196 end;
2197
2198 { TCastleObjectStack ------------------------------------------------------------ }
2199
2200 function TCastleObjectStack.GetCapacity: TListSize;
2201 begin
2202 Result := List.Capacity;
2203 end;
2204
2205 procedure TCastleObjectStack.SetCapacity(const Value: TListSize);
2206 begin
2207 List.Capacity := Value;
2208 end;
2209
2210 { TCastleObjectQueue ------------------------------------------------------------ }
2211
2212 function TCastleObjectQueue.GetCapacity: TListSize;
2213 begin
2214 Result := List.Capacity;
2215 end;
2216
2217 procedure TCastleObjectQueue.SetCapacity(const Value: TListSize);
2218 begin
2219 List.Capacity := Value;
2220 end;
2221
2222 { TCastleObjectList ------------------------------------------------------------- }
2223
2224 constructor TCastleObjectList.CreateFromArray(const FreeObjects: boolean;
2225 const AItems: array of TObject);
2226 begin
2227 Create(FreeObjects);
2228 AddRange(AItems);
2229 end;
2230
2231 procedure TCastleObjectList.AddRange(const A: array of TObject);
2232 var
2233 I: Integer;
2234 begin
2235 Capacity := Capacity + High(A) + 1;
2236 for I := 0 to High(A) do
2237 Add(A[I]);
2238 end;
2239
2240 procedure TCastleObjectList.AddArray(const A: array of TObject);
2241 begin
2242 AddRange(A);
2243 end;
2244
2245 procedure TCastleObjectList.AddRange(AList: Contnrs.TObjectList);
2246 {$ifdef FPC}
2247 begin
2248 inherited AddList(AList);
2249 {$else}
2250 var
2251 I: Integer;
2252 begin
2253 for I := 0 to AList.Count - 1 do
2254 Add(AList[I]);
2255 {$endif}
2256 end;
2257
2258 procedure TCastleObjectList.AddList(AList: Contnrs.TObjectList);
2259 begin
2260 AddRange(AList);
2261 end;
2262
2263 function TCastleObjectList.MakeSingle(ReplaceClass: TClass; NewItem: TObject;
2264 AddEnd: boolean): TObject;
2265 var
2266 I: Integer;
2267 begin
2268 if NewItem = nil then
2269 begin
2270 Result := Extract(ReplaceClass);
2271 Exit;
2272 end;
2273
2274 for I := 0 to Count - 1 do
2275 if Items[I] is ReplaceClass then
2276 begin
2277 Result := Extract(I);
2278 Insert(I, NewItem);
2279 Exit;
2280 end;
2281
2282 Result := nil;
2283 if AddEnd then
2284 Insert(Count, NewItem)
2285 else
2286 Insert(0, NewItem);
2287 end;
2288
2289 function TCastleObjectList.Extract(Index: Integer): TObject;
2290 {$ifdef FPC}
2291 begin
2292 Result := TObject(List^[Index]);
2293
2294 { Set to nil and then delete by index. This is a hack to prevent
2295 TList implementation from making any notification about Result
2296 delete/extraction. }
2297 TObject(List^[Index]) := nil;
2298 Delete(Index);
2299
2300 if Assigned(Result) then
2301 Notify(Result, lnExtracted);
2302 {$else}
2303 var
2304 OldOwnsObjects: boolean;
2305 begin
2306 OldOwnsObjects := OwnsObjects;
2307 OwnsObjects := false;
2308 Result := Items[Index];
2309 Delete(Index);
2310 OwnsObjects := OldOwnsObjects;
2311 {$endif}
2312 end;
2313
2314 function TCastleObjectList.Extract(RemoveClass: TClass): TObject;
2315 var
2316 I: Integer;
2317 begin
2318 for I := 0 to Count - 1 do
2319 if Items[I] is RemoveClass then
2320 begin
2321 Result := Extract(I);
2322 Exit;
2323 end;
2324
2325 Result := nil;
2326 end;
2327
2328 function TCastleObjectList.RemoveAll(Item: TObject): Cardinal;
2329 var
2330 I: Integer;
2331 begin
2332 Result := 0;
2333 I := 0;
2334 while I < Count do
2335 begin
2336 if Items[I] = Item then
2337 begin Delete(I); Inc(Result) end else
2338 Inc(I);
2339 end;
2340 end;
2341
2342 function TCastleObjectList.IsFirst(Value: TObject): boolean;
2343 begin
2344 Result := (Count > 0) and (Items[0] = Value);
2345 end;
2346
2347 function TCastleObjectList.IsLast(Value: TObject): boolean;
2348 begin
2349 Result := (Count > 0) and (Items[Count - 1] = Value);
2350 end;
2351
2352 procedure TCastleObjectList.InsertIfNotExists(Index: Integer; Value: TObject);
2353 begin
2354 if IndexOf(Value) = -1 then
2355 Insert(Index, Value);
2356 end;
2357
2358 procedure TCastleObjectList.AddIfNotExists(Value: TObject);
2359 begin
2360 if IndexOf(Value) = -1 then
2361 Add(Value);
2362 end;
2363
2364 { TNotifyEventList ------------------------------------------------------ }
2365
2366 procedure TNotifyEventList.ExecuteAll(Sender: TObject);
2367 var
2368 I: Integer;
2369 begin
2370 for I := 0 to Count - 1 do
2371
2372 { TODO: The test "I < Count" is a quick fix for the problem that list
2373 may be modified during iteration.
2374 E.g. network/remote_logging/gameloghandler.pas in HttpPostFinish
2375 sets FreeSender, which means that Application.OnUpdate list
2376 is modified while we iterate over it.
2377
2378 We should introduce a reliable way to handle this, but for now the test
2379 at least prevents a crash in this case. }
2380
2381 if (I < Count) and Assigned(Items[I]) then
2382 Items[I](Sender);
2383 end;
2384
2385 procedure TNotifyEventList.ExecuteForward(Sender: TObject);
2386 begin
2387 ExecuteAll(Sender);
2388 end;
2389
2390 procedure TNotifyEventList.ExecuteBackward(Sender: TObject);
2391 var
2392 I: Integer;
2393 begin
2394 for I := Count - 1 downto 0 do
2395
2396 { TODO: The test "I < Count" is a quick fix for the problem that when
2397 TCastleApplicationProperties._GLContextClose calls
2398 FOnGLContextCloseObject.ExecuteBackward(Self),
2399 some "on close" callbacks modify the FOnGLContextCloseObject list.
2400
2401 We should introduce a reliable way to handle this, but for now the test
2402 at least prevents a crash in this case. }
2403
2404 if (I < Count) and Assigned(Items[I]) then
2405 Items[I](Sender);
2406 end;
2407
2408 { TSimpleNotifyEventList ------------------------------------------------------ }
2409
2410 procedure TSimpleNotifyEventList.ExecuteAll;
2411 var
2412 I: Integer;
2413 begin
2414 for I := 0 to Count - 1 do
2415 { See TNotifyEventList.ExecuteAll for explanation why the "I < Count"
2416 adds a little safety here. }
2417 if (I < Count) and Assigned(Items[I]) then
2418 Items[I]();
2419 end;
2420
2421 procedure TSimpleNotifyEventList.Pack;
2422 var
2423 I: Integer;
2424 begin
2425 I := 0;
2426 while I < Count do
2427 begin
2428 if Assigned(Items[I]) then
2429 Inc(I)
2430 else
2431 Delete(I);
2432 end;
2433 end;
2434
2435 procedure TSimpleNotifyEventList.Unassign(const Event: TSimpleNotifyEvent);
2436 var
2437 I: Integer;
2438 begin
2439 for I := 0 to Count - 1 do
2440 if SameMethods(TMethod(Event), TMethod(Items[I])) then
2441 Items[I] := nil;
2442 end;
2443
2444 { TProcedureList ------------------------------------------------------ }
2445
2446 procedure TProcedureList.ExecuteAll;
2447 var
2448 I: Integer;
2449 begin
2450 for I := 0 to Count - 1 do
2451 { See TNotifyEventList.ExecuteAll for explanation why the "I < Count"
2452 adds a little safety here. }
2453 if (I < Count) and Assigned(Items[I]) then
2454 Items[I]();
2455 end;
2456
2457 { DumpStack ------------------------------------------------------------------ }
2458
2459 {$ifdef FPC}
2460 function DumpStackToString(const BaseFramePointer: Pointer): string;
2461 var
2462 TextFile: Text;
2463 StringStream: TStringStream;
2464 begin
2465 StringStream := TStringStream.Create('');
2466 try
2467 AssignStream(TextFile, StringStream);
2468 Rewrite(TextFile);
2469 try
2470 Dump_Stack(TextFile, BaseFramePointer);
2471 finally CloseFile(TextFile) end;
2472 Result := StringStream.DataString;
2473 finally FreeAndNil(StringStream) end;
2474 end;
2475
2476 function DumpExceptionBackTraceToString: string;
2477 {$ifdef CASTLE_NINTENDO_SWITCH}
2478 begin
2479 Result := ''; // DumpExceptionBackTrace fails with Access Violation
2480 {$else}
2481 var
2482 TextFile: Text;
2483 StringStream: TStringStream;
2484 begin
2485 {$ifdef VER3_3} {$define CASTLE_SECURE_BACKTRACE} {$endif}
2486 {$ifdef CASTLE_SECURE_BACKTRACE}
2487 try
2488 {$endif}
2489
2490 StringStream := TStringStream.Create('');
2491 try
2492 AssignStream(TextFile, StringStream);
2493 Rewrite(TextFile);
2494 try
2495 DumpExceptionBackTrace(TextFile);
2496 finally CloseFile(TextFile) end;
2497 Result := StringStream.DataString;
2498 finally FreeAndNil(StringStream) end;
2499
2500 {$ifdef CASTLE_SECURE_BACKTRACE}
2501 except
2502 // TODO: investigate and report, reproducible by running play_animation with non-existent data.
2503 // WritelnWarning('Capturing backtrace failed, this is known to happen with some FPC 3.3.1 versions.');
2504 // Cannot log this problem -- as logging itself could use backtrace, causing infinite loop...
2505 Result := '';
2506 end;
2507 {$endif}
2508 {$endif}
2509 end;
2510 {$endif}
2511
2512 function InternalProposeName(const ComponentClass: TComponentClass;
2513 const ComponentsOwner: TComponent): String;
2514 begin
2515 Result := ProposeComponentName(ComponentClass, ComponentsOwner, '');
2516 end;
2517
2518 function ProposeComponentName(const ComponentClass: TComponentClass;
2519 const ComponentsOwner: TComponent;
2520 BaseName: String): String;
2521
2522 { Cleanup S (right now, always taken from some ClassName)
2523 to be a nice component name, which also must make it a valid Pascal identifier. }
2524 function CleanComponentName(const S: String): String;
2525 begin
2526 Result := S;
2527
2528 // remove common prefixes
2529 if IsPrefix('TCastleUserInterface', Result, true) then
2530 Result := PrefixRemove('TCastleUserInterface', Result, true)
2531 else
2532 if IsPrefix('TCastle', Result, true) then
2533 Result := PrefixRemove('TCastle', Result, true)
2534 else
2535 if IsPrefix('T', Result, true) then
2536 Result := PrefixRemove('T', Result, true);
2537
2538 // move 2D and 3D to the back, as component name cannot start with a number
2539 if IsPrefix('2D', Result, true) then
2540 Result := PrefixRemove('2D', Result, true) + '2D';
2541 if IsPrefix('3D', Result, true) then
2542 Result := PrefixRemove('3D', Result, true) + '3D';
2543
2544 // in case the replacements above made '', fix it (can happen in case of TCastleUserInterface)
2545 if Result = '' then
2546 Result := 'Group';
2547
2548 if SCharIs(Result, 1, ['0'..'9']) then
2549 Result := 'Component' + Result;
2550 end;
2551
2552 var
2553 ResultBase: String;
2554 I: Integer;
2555 begin
2556 if BaseName <> '' then
2557 ResultBase := BaseName
2558 else
2559 ResultBase := CleanComponentName(ComponentClass.ClassName);
2560
2561 { A simple test of the CleanComponentName routine.
2562 This is *not* a good place for such automated test, but for now it was simplest to put it here. }
2563 {
2564 Assert(CleanComponentName('TSomething') = 'Something');
2565 Assert(CleanComponentName('TCastleUserInterface') = 'Group');
2566 Assert(CleanComponentName('TCastleUserInterfaceButton') = 'Button');
2567 Assert(CleanComponentName('TCastleSomething') = 'Something');
2568 Assert(CleanComponentName('TCastle2DStuff') = 'Stuff2D');
2569 Assert(CleanComponentName('TCastle3DStuff') = 'Stuff3D');
2570 Assert(CleanComponentName('TCastle4DProcessing') = 'Component4DProcessing');
2571 }
2572
2573 // make unique
2574 I := 1;
2575 Result := ResultBase + IntToStr(I);
2576 while ComponentsOwner.FindComponent(Result) <> nil do
2577 begin
2578 Inc(I);
2579 Result := ResultBase + IntToStr(I);
2580 end;
2581 end;
2582
2583 { TFreeNotificationObserver -------------------------------------------------- }
2584
2585 destructor TFreeNotificationObserver.Destroy;
2586 begin
2587 { detach free notification, if any remains }
2588 Observed := nil;
2589 inherited;
2590 end;
2591
2592 procedure TFreeNotificationObserver.Notification(AComponent: TComponent; Operation: TOperation);
2593 begin
2594 inherited;
2595
2596 { Note: initially I tried implementing this class without tracking FObserved,
2597 instead user needed to call
2598 Xxx.FreeNotification(MyFreeNotificationObserver),
2599 Xxx.RemoveFreeNotification(MyFreeNotificationObserver)
2600 explicitly. But this was bad: even on TFreeNotificationObserver,
2601 we also get notification about freeing of some unrelated components
2602 (TCustomHintAction, THintWindow, TCustomTimer...) when using LCL.
2603
2604 Using Observed property also makes usage simpler:
2605 - No need to use RemoveFreeNotification and FreeNotification.
2606 Instead just set Observed.
2607 - It is obvious that this component observes only *one* component at a time.
2608 (Since this is its purpose). }
2609
2610 if (Operation = opRemove) and
2611 (AComponent <> nil) and // should not happen, but better be secure
2612 (AComponent = FObserved) and
2613 Assigned(OnFreeNotification) then
2614 begin
2615 OnFreeNotification(Self);
2616
2617 { Possibly OnFreeNotification already changed Observed, and we no longer observe it.
2618 But if it didn't... then let's fix it.
2619 We know FObserved will be freed, so we can stop watching. }
2620 if AComponent = FObserved then
2621 Observed := nil;
2622 end;
2623 end;
2624
2625 procedure TFreeNotificationObserver.SetObserved(const Value: TComponent);
2626 begin
2627 if FObserved <> Value then
2628 begin
2629 if FObserved <> nil then
2630 FObserved.RemoveFreeNotification(Self);
2631 FObserved := Value;
2632 if FObserved <> nil then
2633 FObserved.FreeNotification(Self);
2634 end;
2635 end;
2636
2637 initialization
2638 InitStdStreams;
2639 finalization
2640 FiniStdStreams;
2641 end.