Repository navigation
Expand file tree
/
Copy pathcastleclassutils.pas
More file actions
2947 lines (2491 loc) · 103 KB
/
Copy pathcastleclassutils.pas
File metadata and controls
2947 lines (2491 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
Copyright 2000-2026 Michalis Kamburelis.
This file is part of "Castle Game Engine".
"Castle Game Engine" is free software; see the file COPYING.md,
included in this distribution, for details about the copyright.
"Castle Game Engine" is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
----------------------------------------------------------------------------
}
{ Basic classes and class utilities (for streams, strings, lists and such).
Many utilities for classes that are defined in the Classes unit,
and some classes of our my own.
Some notes about TStream descendants :
@unorderedList(
@item(
We call a stream "purely sequential" (or just "sequential")
if it allows only reading and/or writing of data
and does not allow free "Seek" calls,
in particular --- it does not allow Seek to move back in a stream.)
@item(
We call a stream "growing" if it's read-only and it's purely sequential
and it's Size property may be useless. In other words, when you read
a "growing" stream, you don't know when it ends, until you reach the end.
You just have to read data until Read returns 0.)
@item(Remember that to reliably detect end of the stream when you
use TStream.Read, you have to test is ReadCount = 0.
Merely testing that ReadCount < less than you requested is not enough,
e.g. seen for THandleStream when handle is StdIn.)
)
}
unit CastleClassUtils;
{$I castleconf.inc}
interface
uses Classes, SysUtils, Contnrs, Generics.Collections, Generics.Defaults,
CastleUtils, CastleStringUtils;
{ ---------------------------------------------------------------------------- }
{ @section(TStrings utilities) }
{ @deprecated }
procedure StringsAdd(Strs: TStrings; Count: integer; itemVal: string='dummy');
deprecated 'this utility is very trivial and seldom useful; better implement it in yourself, without relying on CastleClassUtils';
{ Add all strings from the string array to the TStrings instance. }
procedure AddStrArrayToStrings(const StrArr: array of string; strlist: TStrings);
deprecated 'use TStrings.AddStrings';
type
{ TStringList that is case sensitive.
@deprecated
Deprecated, better use TStringList directly and set CaseSensitive to true. }
TStringListCaseSens = class(TStringList)
constructor Create;
property CaseSensitive default true;
end deprecated;
{ Splits S by Splitter, and adds each splitted part to Strings.
Splitting is done by Splitter, i.e. if N is the number of occurrences
of Splitter inside S, then it always adds N + 1 strings to Strings.
Yes, this means that if S starts with Splitter then the first
part is equal to ''. And if S ends with Splitter then the last
oart is equal to ''. }
procedure Strings_AddSplittedString(Strings: TStrings;
const S, Splitter: string);
{ @deprecated }
procedure Strings_SetText(SList: TStrings; const S: String);
deprecated 'use SList.Text := S';
{ Make sure we don't have more than MaxCount strings on a list.
Removes the last strings if necessary. }
procedure Strings_Trim(Strings: TStrings; MaxCount: Cardinal);
deprecated 'this utility is very trivial and seldom useful; better implement it in yourself, without relying on CastleClassUtils';
{$ifndef FPC}
{$define CASTLE_STRINGS_HELPER_ADDSTRINGS}
{$endif}
{$ifdef CASTLE_STRINGS_HELPER_ADDSTRINGS}
{ AddStrings(array of String) method for TStrings.
We know this is
- not necessary with Delphi 12.2
- and it is necessary with 10.2 .
To keep things simple (and tested) we enable it for all Delphis. }
type
TStringsHelper = class helper for TStringList
procedure AddStrings(const A: array of String); overload;
end;
{$endif CASTLE_STRINGS_HELPER_ADDSTRINGS}
{ ---------------------------------------------------------------------------- }
{ @section(TStream utilities) }
// Unused
//procedure StreamWriteByte(Stream: TStream; const Value: Byte);
//function StreamReadByte(Stream: TStream): Byte;
{ Write string contents, encoded as 8-bit (UTF-8), to stream.
Versions with "Ln" suffix append a newline.
Versions without Stream parameter write to StdOutStream.
Note: When compiled with Delphi, overloaded versions that take
Delphi 16-bit String convert it to 8-bit Utf8String,
and still write 8-bit. So the output stream contents are the same,
in both FPC and Delphi.
@groupBegin }
procedure WriteStr(const Stream: TStream; const S: Utf8String); overload;
procedure WritelnStr(const Stream: TStream; const S: Utf8String); overload;
procedure WriteStr(const S: Utf8String); overload;
procedure WritelnStr(const S: Utf8String); overload;
{$ifndef FPC}
procedure WriteStr(const Stream: TStream; const S: String); overload;
procedure WritelnStr(const Stream: TStream; const S: String); overload;
procedure WriteStr(const S: String); overload;
procedure WritelnStr(const S: String); overload;
{$endif}
{ @groupEnd }
{ Read one character from stream.
@raises EReadError If end of stream. }
function StreamReadChar(Stream: TStream): AnsiChar;
{ Read characters until a zero byte is encountered, treat as UTF-8 string. }
function StreamReadZeroEndString(Stream: TStream): Utf8String;
{ Read stream, until you find some character in EndingChars.
Returns read contents, without final character (the one in EndingChars set).
Returns 8-bit string (Utf8String) and assumes the stream contains UTF-8,
which is the encoding we assume for all text files throughout Castle Game Engine.
The resulting @code(Utf8String) can be assigned to a @code(String)
(or any other string type) and the encoding will be correct.
If you use a version with BackEndingChar parameter and pass
BackEndingChar = @true, then the ending character will be returned back to
stream (we will start reading from it next time).
Note that "returning the character" is done by Seek(-1, soFromCurrent),
which may not be possible on some streams. Wrap a stream
in TPeekCharStream instead, and use TPeekCharStream.ReadUpto,
to be able to "return back" a character reliably.
Independently from BackEndingChar, if you use a version with EndingChar
parameter, it will be set to the ending character.
@raises EReadError If the stream will end before encountering one of EndingChars.
@groupBegin }
function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars;
backEndingChar: boolean; out endingChar: AnsiChar): Utf8String; overload;
function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars;
backEndingChar: boolean): Utf8String; overload;
function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars;
out endingChar: AnsiChar): Utf8String; overload;
function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars): Utf8String; overload;
{ @groupEnd }
{ Read stream, until you find some character in EndingChars, or end of stream.
Compared to StreamReadUpto_NotEOS, this treats "end of stream"
as a normal situation, and doesn't raise any exception on it.
It sets EndingChar to -1 on end of stream. When EndingChar is not -1,
you know you can safely cast it to normal 8-bit character.
Everything else works like with StreamReadUpto_NotEOS.
@groupBegin }
function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars;
backEndingChar: boolean; out endingChar: integer): Utf8String; overload;
function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars;
backEndingChar: boolean): Utf8String; overload;
function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars;
out endingChar: integer): Utf8String; overload;
function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars): Utf8String; overload;
{ @groupEnd }
{ Read a growing stream, and append it to another destination stream.
A "growing stream" is a stream that we can only read
sequentially, no seeks allowed, and size is unknown until we hit the end.
The only operation we do on GrowingStream is GrowingStream.Read and the only
operation on DestStream is DestStream.WriteBuffer. So DestStream usually
must be able to grow dynamically to accomodate any GrowingStream input size.
This procedure ends when GrowingStream ends. If ResetDestStreamPosition
then at the end we do DestStream.Position := 0 (since it is usually useful
and it would be easy for you to forget about it). }
procedure ReadGrowingStream(const GrowingStream, DestStream: TStream;
const ResetDestStreamPosition: Boolean;
const BufferSize: Cardinal = 10 * 1000);
{ Read a growing stream, and returns it's contents as a string.
A "growing stream" is a stream that we can only read
sequentially, no seeks allowed, and size is unknown until we hit the end.
Returns 8-bit string (Utf8String) and assumes the stream contains UTF-8,
which is the encoding we assume for all text files in Castle Game Engine.
The resulting @code(Utf8String) can be assigned to a @code(String)
(or any other string type) and the encoding will be correct.
See @url(https://castle-engine.io/coding_conventions#strings_unicode String encoding in Castle Game Engine)
and @url(https://github.com/castle-engine/castle-engine/blob/master/doc/miscellaneous_notes/ansistring_encoding.md AnsiString encoding)
for details what happens. }
function ReadGrowingStreamToString(const GrowingStream: TStream): Utf8String;
{ Read a growing stream, and returns it's contents as a string.
A "growing stream" is a stream that we can only read
sequentially, no seeks allowed, and size is unknown until we hit the end.
Works with String, i.e. UTF-16 with Delphi, UTF-8 with FPC. }
function ReadGrowingStreamToDefaultString(const GrowingStream: TStream): String;
{ Encode / decode a string in a binary stream. Records string length (4 bytes),
then the string contents (Length(S) bytes).
Works on 8-bit strings, assuming they are UTF-8 encoded in stream.
@groupBegin }
procedure StreamWriteString(const Stream: TStream; const S: Utf8String);
function StreamReadString(const Stream: TStream): Utf8String;
{ @groupEnd }
{ Convert whole Stream to a string.
Changes Stream.Position to 0 and then reads Stream.Size bytes,
so be sure that Stream.Size is usable.
Use @link(ReadGrowingStreamToString) if you want to read a stream where
setting Position / reading Size are not reliable.
Returns 8-bit string (Utf8String) and assumes the stream contains UTF-8,
which is the encoding we assume for all text files in Castle Game Engine.
The resulting @code(Utf8String) can be assigned to a @code(String)
(or any other string type) and the encoding will be correct.
See @url(https://castle-engine.io/coding_conventions#strings_unicode String encoding in Castle Game Engine)
and @url(https://github.com/castle-engine/castle-engine/blob/master/doc/miscellaneous_notes/ansistring_encoding.md AnsiString encoding)
for details what happens. }
function StreamToString(const Stream: TStream): Utf8String;
{ Set contents of TMemoryStream to given string, in UTF-8 encoding.
If Rewind then the position is reset to the beginning,
otherwise it stays at the end.
Takes 8-bit string (Utf8String) and makes the stream contain UTF-8,
which is the encoding we assume for all text files in Castle Game Engine.
The @code(Utf8String) can be assigned from / to a @code(String)
(or any other string type) and the encoding will be correct.
See @url(https://castle-engine.io/coding_conventions#strings_unicode String encoding in Castle Game Engine)
and @url(https://github.com/castle-engine/castle-engine/blob/master/doc/miscellaneous_notes/ansistring_encoding.md AnsiString encoding)
for details what happens. }
procedure MemoryStreamLoadFromString(const Stream: TMemoryStream;
const S: Utf8String; const Rewind: boolean = true); overload;
function MemoryStreamLoadFromString(
const S: Utf8String; const Rewind: boolean = true): TMemoryStream; overload;
{ Set contents of TMemoryStream to given string,
in UTF-8 or UTF-16 (matching default String) encoding.
If Rewind then the position is reset to the beginning,
otherwise it stays at the end.
On FPC (without Unicode RTL),
this works with 8-bit strings (AnsiStrings) and is equivalent to
@link(MemoryStreamLoadFromString).
( Note: If one day CASTLE_ANSISTRING_UNCHANGED is supported with
FPC (without Unicode RTL),
this will still take native encoding while @link(MemoryStreamLoadFromString)
will always take UTF-8 encoding. So it will not be equivalent anymore. )
On Delphi, this works with 16-bit strings (UnicodeString), so the resulting
stream size is 2x larger. }
procedure MemoryStreamLoadFromDefaultString(const Stream: TMemoryStream;
const S: String; const Rewind: boolean = true); overload;
function MemoryStreamLoadFromDefaultString(
const S: String; const Rewind: boolean = true): TMemoryStream; overload;
type
EStreamNotImplemented = class(Exception);
EStreamNotImplementedWrite = class(EStreamNotImplemented);
EStreamNotImplementedSeek = class(EStreamNotImplemented);
EStreamNotImplementedSetSize = class(EStreamNotImplemented);
{ Abstract class to read another stream, always being able to back one character.
This is a purely sequential read-only stream.
This means that calling @link(Write), @link(Seek) (changing Position)
or setting @code(Size) will always cause an exception with
appropriate descendant of @link(EStreamNotImplemented).
Getting @code(Size) and @code(Position) is allowed.
Getting @code(Size) is simply
implemented by getting SourceStream.Size (so it works if the underlying
source stream supports getting Size). Getting @code(Position) always works
correctly, as it's just the number of characters
@italic(read) from this stream. The fact that we may
read ahead in the underlying source stream (for buffering, for peeking)
is completely hidden.
We do not assume anything about the underlying source stream, in particular
the underlying source stream may also be purely sequential
(so we can only read from it, and we cannot predict when it ends).
The main advantage of using this class is that you get PeekChar routine:
you can always peek ahead one character in the stream,
without reading it (i.e. next time you will call Read or ReadBuffer
you will still get that char). And it works for all source streams,
including the ones where seeking is not allowed (so Seek(-1, soCurrent)
would not work).
Another advantage is the @link(Line) and @link(Column) information. }
TPeekCharStream = class(TStream)
private
FSourceStream: TStream;
FOwnsSourceStream: boolean;
FLine, FColumn: Int64;
protected
{ @returns(SourceStream.Size). }
function GetSize: Int64; override;
{ This stream doesn't support setting size.
(All other versions of SetSize also call this.)
@raises(EStreamNotImplementedSetSize Always.) }
procedure SetSize(NewSize: Longint); override;
{$ifndef FPC}
function GetPosition: Int64; virtual; abstract;
{$endif}
procedure UpdateLineColumn(const C: AnsiChar); overload;
procedure UpdateLineColumn(const Buffer; const BufferCount: Integer); overload;
public
constructor Create(ASourceStream: TStream; AOwnsSourceStream: boolean);
destructor Destroy; override;
{ This stream doesn't support seeking.
(SetPosition and all other versions of Seek also call this.)
@raises(EStreamNotImplementedSeek Always.) }
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
{ This stream doesn't support writing.
(WriteBuffer also calls this.)
@raises(EStreamNotImplementedWrite Always.) }
function Write(const Buffer; Count: Longint): Longint; override;
{ Underlying stream. }
property SourceStream: TStream read FSourceStream;
{ Should we free underlying SourceStream at destruction. }
property OwnsSourceStream: boolean
read FOwnsSourceStream write FOwnsSourceStream;
{ Peek next character. Returns the next character
without making it "already read", so the next call to
Read or ReadBuffer will return this char.
Subsequent calls to PeekChar (without any Read/ReadBuffer between)
will also return the same character.
Returns -1 if stream ended, otherwise returns Ord or given char.
This may call SourceStream.Read, and any exceptions that may be
raised in SourceStream.Read are propagated higher from this method. }
function PeekChar: Integer; virtual; abstract;
{ Read next character. A shortcut for Read(c, 1), but it returns -1
if end of stream is reached. So it's consistent with PeekChar.
Sometimes it's also more comfortable, and it's a little faster. }
function ReadChar: Integer; virtual; abstract;
{ Read characters, until one of EndingChars (or end of stream) is found.
The ending character is not "consumed" from the stream.
The Result is guaranteed to not contain any char from EndingChars.
Returns 8-bit string (Utf8String) and assumes the stream contains UTF-8,
which is the encoding we assume for all text files in Castle Game Engine.
The resulting @code(Utf8String) can be assigned to a @code(String)
(or any other string type) and the encoding will be correct. }
function ReadUpto(const EndingChars: TSetOfChars): Utf8String; virtual;
{$ifndef FPC}
property Position: Int64 read GetPosition;
{$endif}
{ Line number in the file (counting from 1). }
property Line: Int64 read FLine;
{ Column number in the file (counting from 1). }
property Column: Int64 read FColumn;
end;
{ Read another stream, sequentially, always being able to back one character.
This is a simplest non-abstract implementation of
the @link(TPeekCharStream) class. }
TSimplePeekCharStream = class(TPeekCharStream)
private
PeekedChar: Integer;
IsPeekedChar: boolean;
FPosition: Int64;
protected
function GetPosition: Int64; override;
public
function Read(var Buffer; Count: Longint): Longint; override;
function PeekChar: Integer; override;
function ReadChar: Integer; override;
end;
const
DefaultReadBufferSize = 1024 * 1024;
type
{ Read another stream, sequentially, always being able to back one character,
and buffering it. This implements abstract TPeekCharStream class,
so this is a purely sequential read-only stream that reads from
underlying SourceStream and you can use PeekChar and ReadChar and
ReadUpto routines.
This stream will buffer incoming data from SourceStream.
This means that reading by a very small chunks (like e.g. byte-by-byte)
does not hurt performance. }
TBufferedReadStream = class(TPeekCharStream)
private
FPosition: Int64;
{ Always non-nil, allocated for BufferSize bytes. }
Buffer: PByteArray;
{ A position of the next unread char in Buffer,
i.e. PeekChar simply returns Buffer[BufferPos]
(unless BufferPos = BufferEnd, in which case buffer must be refilled). }
BufferPos: Cardinal;
{ Always BufferPos <= BufferEnd.
Always Buffer[BufferPos..BufferEnd - 1] is the data that still must be
returned by TBufferedReadStream.Read method. }
BufferEnd: Cardinal;
FBufferSize: Cardinal;
{ Sets Buffer contents, BufferEnd reading data from SourceStream.
BufferPos is always resetted to 0 by this. }
procedure FillBuffer;
protected
function GetPosition: Int64; override;
public
constructor Create(ASourceStream: TStream; AOwnsSourceStream: boolean;
ABufferSize: Cardinal = DefaultReadBufferSize);
destructor Destroy; override;
function Read(var LocalBuffer; Count: Longint): Longint; override;
function PeekChar: Integer; override;
function ReadChar: Integer; override;
function ReadUpto(const EndingChars: TSetOfChars): Utf8String; override;
property BufferSize: Cardinal read FBufferSize;
end;
{ ---------------------------------------------------------------------------- }
{ @section(TComponent utilities) }
{ Create Component instance, if it's @nil.
If Component = nil then it will do
@code(Component := ComponentClass.Create(Owner)). }
procedure CreateIfNeeded(var Component: TComponent;
ComponentClass: TComponentClass; Owner: TComponent);
type
{ Used by @link(TCastleComponent.PropertySections). }
TPropertySection = (psBasic, psLayout);
TPropertySections = set of TPropertySection;
TCastleComponent = class;
{ Used by @link(TCastleComponent.TranslateProperties). }
TTranslatePropertyEvent = procedure (const Sender: TCastleComponent;
const PropertyName: String; var PropertyValue: String) of object;
{ Call methods of this class within @link(TCastleComponent.CustomSerialization) override.
Do not create instances of this class yourself. }
TSerializationProcess = class abstract
public
type
TListEnumerateEvent = procedure (const Proc: TGetChildProc) of object;
TListAddEvent = procedure (const NewComponent: TComponent) of object;
TListClearEvent = procedure of object;
var
{ @exclude
Used by TCastleViewport to keep navigation/camera across undo. }
InternalPreserveDataAcrossUndo: TComponent;
{ Serialize and deserialize given simple Value.
This mechanism allows to explicitly serialize/deserialize any internal value,
without the need to make it a published property.
When deserializing, we always try to read it from file.
If it is not present, the Value is not modified.
When serializing, we write it to file only if IsStored.
Generally IsStored=false should indicate "the Value is the same as when the object
is created, thus there's no point in serializing it".
The values are guaranteed to be read/written in the same way as if a published
property with the same name (Key) and same type would be read/written.
This allows to utilize this mechanism to read, to a local/private variable,
a value that was previously a published property value.
This is a way to provide backward-compatibility for old designs: this way class
can interpret old values in design files, even though it no longer publishes
given property.
@seealso ReadWriteSubComponent
@groupBegin }
procedure ReadWriteInteger(const Key: String; var Value: Integer; const IsStored: Boolean);
overload; virtual; abstract;
procedure ReadWriteBoolean(const Key: String; var Value: Boolean; const IsStored: Boolean);
overload; virtual; abstract;
procedure ReadWriteString(const Key: String; var Value: String; const IsStored: Boolean);
overload; virtual; abstract;
procedure ReadWriteSingle(const Key: String; var Value: Single; const IsStored: Boolean);
overload; virtual; abstract;
{ @groupEnd }
{ Serialize and deserialize a subcomponent.
Being a subcomponent, we know that Value is not nil,
and it is not referenced anywhere else in the design
(so serialization/deserialization can expect class contents, not just name),
so we just serialize and deserialize the contents.
When deserializing, we always try to read it from file.
If it is not present, nothing is modified.
When serializing, we write it to file only if IsStored.
Generally IsStored=false should indicate "the Value is the same as when the object
is created, thus there's no point in serializing it".
The values are guaranteed to be read/written in the same way as if a published
property with the same name (Key) and same type would be read/written.
This allows to utilize this mechanism to read, to a local/private variable,
a value that was previously a published property value.
This is a way to provide backward-compatibility for old designs: this way class
can interpret old values in design files, even though it no longer publishes
given property.
@seealso ReadWriteInteger
@seealso ReadWriteBoolean
@seealso ReadWriteSingle
@seealso ReadWriteString }
procedure ReadWriteSubComponent(const Key: String; const Value: TComponent;
const IsStored: Boolean); virtual; abstract;
{ Make a list serialized and deserialized.
The definition of list is very flexible here, you provide callbacks
that should, when called,
@unorderedList(
@itemSpacing compact
@item enumerate (call other callback for each item),
@item clear all items (that were possibly added by previous deserialization),
@item add new item.
)
Do not worry about conflict between Key and some published property.
We internally "mangle" keys to avoid it. }
procedure ReadWriteList(const Key: String;
const ListEnumerate: TListEnumerateEvent; const ListAdd: TListAddEvent;
const ListClear: TListClearEvent); virtual; abstract;
{ Is there set with the given Key, and non-empty?
Internal, because use-case small: backward compatibility for old designs
with "Spatial" set.
@exclude}
function InternalHasNonEmptySet(const Key: String): Boolean; virtual; abstract;
end;
{ Component with various CGE extensions: can be a parent of other non-visual components
(to display them in CGE editor and serialize them to files), can be translated,
can have custom logic when serializing/deserializing (CustomSerialization).
Note that everywhere in CGE (in particular in editor and when serializing) we handle
a standard Pascal TComponent as well. So there's no need to derive all your components from
TCastleComponent, so you derive from standard TComponent too.
You can use TCastleComponent only if necessary, i.e. only if you need one of
the extra features in this class. }
TCastleComponent = class(TComponent)
strict private
type
{ Used by @link(TCastleComponent.NonVisualComponentsEnumerate).
Do not use this type explicitly, it should only be used by for..in
construction like "for C in MyComponent.NonVisualComponentsEnumerate do ...".
@exclude }
TNonVisualComponentsEnumerator = record
strict private
FParent: TCastleComponent;
FPosition: Integer;
function GetCurrent: TComponent; inline;
public
constructor Create(const AParent: TCastleComponent);
function MoveNext: Boolean; inline;
property Current: TComponent read GetCurrent;
function GetEnumerator: TNonVisualComponentsEnumerator;
end;
var
FNonVisualComponents: TComponentList;
FIsLoading: Boolean;
function GetNonVisualComponents(const Index: Integer): TComponent;
procedure SerializeNonVisualComponentsEnumerate(const Proc: TGetChildProc);
procedure SerializeNonVisualComponentsAdd(const C: TComponent);
procedure SerializeNonVisualComponentsClear;
protected
function GetInternalText: String; virtual;
procedure SetInternalText(const Value: String); virtual;
procedure SetName(const Value: TComponentName); override;
{ Enumerate all properties that are possible to translate in this component.
E.g. in @link(TCastleLabel) it will return @link(TCastleLabel.Caption),
in @link(TCastleEdit) it will return @link(TCastleEdit.Text) and
@link(TCastleEdit.Placeholder).
Returns only non-empty properties, thus assuming that if current
(by convention, English) text is empty, then there is no point
in translating it. Moreover descendants may define boolean properties
to exclude particular text from translating, e.g.
@link(TCastleLabel.CaptionTranslate),
@link(TCastleEdit.TextTranslate),
@link(TCastleEdit.PlaceholderTranslate).
It is not recursive (it doesn't enumerate children properties).
Use global @link(TranslateProperties) procedure to call this
on a hierarchy of TComponent.
You usually don't want to call this method (it is called by other engine routines).
But you may find it useful to override this, if you define new component. }
procedure TranslateProperties(const TranslatePropertyEvent: TTranslatePropertyEvent); virtual;
public
{ Internal field used by CastleComponentSerialize.
@exclude }
InternalOriginalName: String;
destructor Destroy; override;
{ Override this method to call various methods of SerializationProcess,
which in turn allows to serialize/deserialize things that are not published.
This allows to serialize/deserialize with more freedom, e.g. to serialize/deserialize
some private field. }
procedure CustomSerialization(const SerializationProcess: TSerializationProcess); virtual;
{ Main text property, that is synchronized with Name initially.
@exclude }
property InternalText: String read GetInternalText write SetInternalText;
{ Set IsLoading to @true and (only on FPC) add csLoading flag to ComponentState.
Used when deserializing.
Do not call this yourself, CastleComponentSerialize automatically calls this.
@exclude }
procedure InternalLoading;
{ Set IsLoading to @false and (only on FPC) remove csLoading flag from ComponentState
and call virtual TComponent.Loaded.
Used when deserializing.
Do not call this yourself, CastleComponentSerialize automatically calls this.
Descendants can override TComponent.Loaded to react to being loaded.
@exclude }
procedure InternalLoaded;
{ Section where to show property in the editor. }
function PropertySections(const PropertyName: String): TPropertySections; virtual;
{ Ignore this component when serializing parent's
@link(TCastleUserInterface.Controls) list or @link(TCastleTransform.List),
and do not show this component in CGE editor.
This simply sets csTransient flag in ComponentStyle.
This is useful for children that are automatically managed by the parent,
and should not be modified by user code. For example,
TCastleCheckbox is internally composed from TCastleImageControl
and TCastleLabel children, but we don't want to serialize or even
show these children to user.
Note that if you want to prevent this component from serializing as part of
@link(TCastleUserInterface.Controls) list or @link(TCastleTransform.List),
but you still want it to be visible in CGE editor,
then make it a "subcomponent" instead, by @code(SetSubComponent(true)).
Note that both csSubComponent and csTransient only disable the component
serialization as part of parent's lists enumerated by CustomSerialization
(see internal TCastleUserInterface.SerializeChildrenEnumerate ,
TCastleTransform.SerializeChildrenEnumerate,
TCastleTransform.SerializeBehaviorsEnumerate).
If you will make the component published in its own property
(which is normal for "subcomponents")
then it will be serialized anyway, just as part of it's own property
(like TCastleScrollView.ScrollArea).
So to @italic(really) avoid serializing a children component
make it csSubComponent and/or csTransient,
and do not publish it.
}
procedure SetTransient;
{ Add non-visual component to this component.
This is used to organize non-visual components in a tree hierarchy,
in CGE designs and editor.
@seealso NonVisualComponentsCount
@seealso NonVisualComponents
@seealso NonVisualComponentsEnumerate }
procedure AddNonVisualComponent(const NonVisualComponent: TComponent);
{ Insert non-visual component to this component.
This is used to organize non-visual components in a tree hierarchy,
in CGE designs and editor.
@seealso NonVisualComponentsCount
@seealso NonVisualComponents
@seealso NonVisualComponentsEnumerate }
procedure InsertNonVisualComponent(const Index: Integer; const NonVisualComponent: TComponent);
{ Removes the component previously added by AddNonVisualComponent. }
procedure RemoveNonVisualComponent(const NonVisualComponent: TComponent);
{ Index of the previously added non-visual component.
Returns -1 if the component was not found. }
function NonVisualComponentsIndexOf(const NonVisualComponent: TComponent): Integer;
{ Count of components added by AddNonVisualComponent.
@seealso AddNonVisualComponent
@seealso NonVisualComponents
@seealso NonVisualComponentsEnumerate }
function NonVisualComponentsCount: Integer;
{ Components added by AddNonVisualComponent. }
property NonVisualComponents [const Index: Integer]: TComponent read GetNonVisualComponents;
{ You can enumerate current non-visual components using loop like
@code(for C in MyComponent.NonVisualComponentsEnumerate do ...).
Do not call this method in other contexts, it is only useful for "for..in" construction.
@seealso AddNonVisualComponent }
function NonVisualComponentsEnumerate: TNonVisualComponentsEnumerator;
{ Is the component during deserialization now.
Note: We can't use @code(csLoading in ComponentState) because in Delphi
it is not possible to control it from CastleComponentSerialize. }
property IsLoading: Boolean read FIsLoading;
{ Whether the current value of this object should be written
to the stream. This should be @true if @italic(anything) inside
this object should be serialized (which means it has non-default
value or "stored" specifier indicates that it should be serialized).
This is used by CastleComponentSerialize, which is used in
Castle Game Engine for all serialization.
In simple cases, this just says whether the current value of this object
equals to some default value.
The default implementation of this class returns @true (so always write).
Descendants that override this to sometimes return @false
(so no need to write) must be very careful: any addition of a new field
requires extending this method, otherwise new field may not be saved sometimes
(when all other fields are default). Descentants of such classes
must also be aware of it.
This check must include everything that is inside this object in JSON,
including subcomponents and children objects (as done e.g. by
@link(TSerializationProcess.ReadWriteList)).
In practice, overriding this method is only reasonable for simple classes
that will not change much in the future, like TCastleVector3Persistent.
The name of this method is consistent with TPropertyEditor.ValueIsStreamed
in LCL. }
function ValueIsStreamed: Boolean; virtual;
{ Override to add information that should be visible at design-time.
Call @code(SList.Add) for each new line of information. }
procedure DesignerInfo(const SList: TStrings); virtual;
{ Override to add warnings that should be visible at design-time.
Call @code(SList.Add) for each new warning. }
procedure DesignerWarnings(const SList: TStrings); virtual;
end;
{ Enumerate all properties that are possible to translate in this component
and its children. E.g. in @link(TCastleLabel) it will return @link(TCastleLabel.Caption),
in @link(TCastleEdit) it will return @link(TCastleEdit.Text)
and @link(TCastleEdit.Placeholder).
Returns only non-empty properties, thus assuming that if current
(by convention, English) text is empty, then there is no point
in translating it. Moreover descendants may define boolean properties
to exclude particular text from translating, e.g.
@link(TCastleLabel.CaptionTranslate),
@link(TCastleEdit.TextTranslate),
@link(TCastleEdit.PlaceholderTranslate).
For every TComponent it also recursively enumerates properties
to translate in children, i.e. in all published subcomponents and children
(returned by TCastleComponent.CustomSerialization). The goal is to be 100% consistent with
CastleComponentSerialize, which is used to (de)serialize hierarchy of
components (like TCastleUserInterface or TCastleTransform).
You usually don't want to call this method (it is called by other engine routines).
Use higher-level routines in @link(CastleLocalizationGetText).
@seealso TCastleComponent.TranslateProperties }
procedure TranslateProperties(const C: TComponent;
const TranslatePropertyEvent: TTranslatePropertyEvent);
type
{ Used by @link(TCastleComponentFactory.ComponentLoadWithMap)
to return names of the loaded components.
This is a simple String -> TComponent dictionary.
The dictionary keys cannot be '' (an empty string).
The dictionary keys ignore case, just like Pascal identifiers.
The values can never be @nil.
The case-insensitivity is achieved by using a case-insensitive comparer
for the dictionary keys. This means the original case of the keys is
preserved (we don't lowercase them), and case-insensitive matching is done
by the (still hashed, so fast) ancestor methods. }
TComponentMap = class({$ifdef FPC}specialize{$endif} TDictionary<String, TComponent>)
strict private
function GetItem(const Key: String): TComponent;
public
constructor Create; {$ifdef FPC} override; {$else} reintroduce; {$endif}
procedure Add(const Key: String; const Value: TComponent);
procedure AddOrSetValue(const Key: String; const Value: TComponent);
property Items[const Key: String]: TComponent read GetItem write AddOrSetValue; default;
end;
{ ---------------------------------------------------------------------------- }
{ @section(Variables to read/write standard input/output using TStream classes.
Initialized and finalized in this unit.) }
var
{ Streams to read/write a standard input/output/error of the program.
Tip: to read the standard input as a text file,
you can use @link(TCastleTextReader) and @link(StdInStream):
@longCode(#
var
StdInReader: TCastleTextReader;
begin
StdInReader := TCastleTextReader.Create(StdInStream, false);
try
while not StdInReader.Eof do
DoSomethingWithInputLine(StdInReader.Readln);
finally FreeAndNil(StdinReader) end;
end;
#)
The advantage of using @link(TCastleTextReader) above,
compared to using the standard Pascal @code(Readln) procedure
to read from the standard Pascal @code(Input) text file,
is that you can easily modify the above code to read from @italic(any)
stream. So, instead of the standard input, you can easily read
some stream that decompresses gzip data, or downloads data from
the Internet... Actually, the overloaded constructor
@link(TCastleTextReader.Create) can accept an URL, like a @code(file://...)
or @code(http://...), and will internally use the stream returned
by @link(Download) function for this URL.
Notes @bold(only for Windows GUI applications):
@orderedList(
@item(
Some (or all) of the variables below may be @nil in a Windows GUI
application.
If you want to be on the safe side, then don't use these streams
in the GUI application (when IsConsole = false on Windows).
But (with some caveats, see below) you can sometimes use them,
if they are not-nil.
)
@item(
You @italic(can) have some of the standard streams available,
even in a GUI application.
User can run a GUI program and explicitly redirect it's standard stream,
e.g. @code(cat something | my_program.exe) for stdin or
@code(my_program.exe > output.txt) for stdout. Actually
some shells, like Cygwin's bash, always redirect some streams
under the hood.
Note that the FPC (and Delphi?) RTL may not provide the standard
Input/Output/ErrOutput in this case (because IsConsole = false),
but we try a little harder, regardless of the IsConsole value.
)
@item(
Caveat: in a GUI program under Windows you @italic(cannot)
depend on the fact that "StdOutStream <> nil means that stdout
is actually available (because user redirected stdout etc.)".
A first write to the StdOutStream may cause EWriteError,
so watch out for this.
This is tested on Windows 2000 Prof, with FPC 2.0.0 and 2.1.1 (revision 4317).
When no stdout is available, StdOutStream should be nil, because
GetStdHandle(STD_OUTPUT_HANDLE) should return 0. However,
GetStdHandle(STD_OUTPUT_HANDLE) doesn't return 0... It returns
some invalid handle (no, not INVALID_HANDLE_VALUE either)
that you can't write into (trying to write returns in ERROR_INVALID_HANDLE
WinAPI error). It seems that there is no way for me to check
whether GetStdHandle(STD_OUTPUT_HANDLE) returned valid handle
(e.g. because the program's stdout was redirected, so stdout is perfectly
available) or whether it returned something unusable.
Note that GetStdHandle(STD_INPUT_HANDLE) and GetStdHandle(STD_ERROR_HANDLE)
work correctly, so it should be OK to check StdInStream <> nil or
StdErrStream <> nil. The only problematic one is GetStdHandle(STD_OUTPUT_HANDLE).)
)
)
}
StdInStream, StdOutStream, StdErrStream: TStream;
{ ---------------------------------------------------------------------------- }
{ @section(Containers) }
type
{ Extended TObjectStack for Castle Game Engine. }
TCastleObjectStack = class(Contnrs.TObjectStack)
private
function GetCapacity: TListSize;
procedure SetCapacity(const Value: TListSize);
public
{ How many items can this hold without reallocating memory. }
property Capacity: TListSize read GetCapacity write SetCapacity;
end;
{ Extended TObjectQueue for Castle Game Engine. }
TCastleObjectQueue = class(Contnrs.TObjectQueue)
private
function GetCapacity: TListSize;
procedure SetCapacity(const Value: TListSize);
public
{ How many items can this hold without reallocating memory. }
property Capacity: TListSize read GetCapacity write SetCapacity;
end;
{ Extended TObjectList for Castle Game Engine. }
TCastleObjectList = class(Contnrs.TObjectList)
public
{ Create and fill with the contents of given array.
Since in ObjectPascal you can create open array parameter on the fly,
this constructor is often comfortable to use, for example you can
write @code(List := TCastleObjectList.Create(..., [Item1, Item2]);). }
constructor CreateFromArray(const FreeObjects: boolean;
const AItems: array of TObject);
{ Add the contents of the given array to the list. }
procedure AddRange(const A: array of TObject); overload;
procedure AddArray(const A: array of TObject); deprecated 'use AddRange, consistent with other lists';
{ Add the contents of another TObjectList instance to the list. }
procedure AddRange(AList: Contnrs.TObjectList); overload;
procedure AddList(AList: Contnrs.TObjectList); deprecated 'use AddRange, consistent with other lists';
{ Replace first found descendant of ReplaceClass with NewItem.
In case no descendant of ReplaceClass was found,
we'll we add NewItem to the list (depending on AddEnd value:
at the beginning or at the end of the list).
If NewItem is @nil, this simply removes the first found
descendant of ReplaceClass.
Returns the replaced (or removed) old item. It is removed from
the list just like the Extract method, so it's never freed.
Or @nil, if none was found (or there was @nil inside the list).
The typical use scenario for this method is when NewItem is also
a descendant from ReplaceClass, and you always keep at most one
ReplaceClass descendant on the list.
For example, you have UI controls list (like
TCastleWindow.Controls), and you want your NewItem to be the only instance
of TCastleOnScreenMenu class inside.
Moreover, in case order on the list is important (for example on
TCastleWindow.Controls order corresponds to screen depth --- what control
is under / above each other), you want to place NewItem at the same
position as previous TCastleOnScreenMenu instance, if any. }
function MakeSingle(ReplaceClass: TClass; NewItem: TObject;
AddEnd: boolean): TObject; deprecated 'this is a complicated method without clear use-case now; do not use';
{ Extract (remove from the list, but never free) given item index.
This is similar TObjectList.Extract, except it takes an index. }
function Extract(Index: Integer): TObject; overload;
{ Extract (remove from the list, but never free) first found descendant of
RemoveClass. Returns the removed item. Or @nil, if none was found
(or there was @nil inside the list and it got removed). }
function Extract(RemoveClass: TClass): TObject; overload;