Debian Codegraph @

src/files/castlexmlconfig.pas

raw
1 {
2 Copyright 2006-2022 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Storing configuration files in XML (TCastleConfig). }
17 unit CastleXMLConfig;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses SysUtils, Classes, DOM, Generics.Collections,
24 CastleUtils, CastleXMLCfgInternal, CastleXmlUtils, CastleVectors, CastleColors;
25
26 type
27 EMissingAttribute = class(Exception);
28
29 TCastleConfig = class;
30
31 TCastleConfigEvent = procedure (const Config: TCastleConfig) of object;
32
33 TCastleConfigEventList = class({$ifdef FPC}specialize{$endif} TList<TCastleConfigEvent>)
34 public
35 { Call all items. }
36 procedure ExecuteAll(const Config: TCastleConfig);
37 end;
38
39 { Store configuration in XML format.
40 Adds various Castle Game Engine extensions to the ancestor TXMLConfig
41 class:
42
43 @unorderedList(
44 @item(load/save from an URL or a TStream (not just a filename),)
45 @item(load/save to the default config file location (for user preferences),)
46 @item(load/save more types (floats, vectors, colors, URLs,
47 multiline text...),)
48 @item(PathElement and MakePathElement utility, to use powerful DOM
49 functions when needed to process something more complex,)
50 @item(encrypt/descrypt contents, just use BlowFishKeyPhrase property
51 (this is actually built-in in our modified TXMLConfig).)
52 )
53
54 See https://castle-engine.io/manual_user_prefs.php
55 for more documentation. }
56 TCastleConfig = class(TXMLConfig)
57 private
58 FOnLoad, FOnSave: TCastleConfigEventList;
59 FLoaded: boolean;
60 { Load empty config. This loads a clear content, without any saved
61 settings, but it takes care to set @link(IsLoaded) to @true,
62 run OnLoad listeners and so on. Useful if your default config
63 is broken for some reason (e.g. file corruption),
64 but you want to override it and just get into a state
65 where config is considered loaded. }
66 procedure LoadEmpty(const PretendUrl: String);
67 public
68 constructor Create(AOwner: TComponent); override;
69 destructor Destroy; override;
70
71 { Integer values reading/writing to config file.
72 @raises(EMissingAttribute Raised by GetInteger(string) (overloaded
73 version without the ADefaultValue parameter) if the attribute is missing.)
74 @raises(EConvertError If the attribute exists but has invalid format.) }
75 function GetInteger(const APath: string;
76 const ADefaultValue: Integer): Integer; overload;
77 function GetInteger(const APath: String): Integer; overload;
78
79 { Get a @italic(required) boolean attribute, raise exception if missing or invalid.
80 @raises(EMissingAttribute If the attribute is missing or empty.)
81 @raises(EConvertError If the attribute exists but has invalid format.) }
82 function GetBoolean(const APath: String): Boolean; overload;
83
84 { Get a @italic(required, non-empty) string value.
85 Value must exist and cannot be empty in XML file.
86 @raises(EMissingAttribute If value doesn't exist or is empty in XML file.) }
87 function GetStringNonEmpty(const APath: string): string;
88
89 function GetNonEmptyValue(const APath: string): string; deprecated 'use GetStringNonEmpty';
90
91 { Internal notes about GetFloat / SetFloat:
92 At the beginning I made the float methods
93 to overload existing names (GetValue, SetValue etc.).
94
95 But this turned out to be a *very* bad idea: integers are
96 casted to floats automatically, and this means that it's too
97 easy to use integer getter to read a value that may be float.
98 Consider that default value for some float parameter is of integer type
99 (e.g. because it was declared as an integer, because you forget to
100 write "0.0" instead of "0" etc.). Then
101
102 MyValue := GetValue('float_param', 0);
103
104 will choose GetValue that interprets given value as an integer.
105 If you perviously stored a float value there
106 (like by SetValue('float_param', 3.14)) then the GetValue above
107 will compile but fail miserably at runtime.
108 }
109
110 { Float values reading/writing to config file.
111
112 Note: for powerful reading of float expressions,
113 consider using @code(GetFloatExpression) instead of @code(GetFloat).
114 It can read expressions like @code("3.0 * 2.0") or @code("sin(2.0)").
115 Use CastleScriptXML unit to introduce
116 necessary class helper for this, see @link(TCastleConfigScriptHelper.GetFloatExpression).
117
118 @raises(EMissingAttribute Raised by GetFloat(string) (overloaded
119 version without the ADefaultValue parameter) if the attribute is missing.)
120
121 @groupBegin }
122 function GetFloat(const APath: string;
123 const ADefaultValue: Float): Float; overload;
124 function GetFloat(const APath: string): Float; overload;
125 procedure SetFloat(const APath: string;
126 const AValue: Float);
127 procedure SetDeleteFloat(const APath: string;
128 const AValue, ADefaultValue: Float);
129 { @groupEnd }
130
131 { Int64 values reading/writing to config file.
132 @raises(EMissingAttribute Raised by GetInt64(string) (overloaded
133 version without the ADefaultValue parameter) if the attribute is missing.) }
134 function GetInt64(const APath: string;
135 const ADefaultValue: Int64): Int64; overload;
136 function GetInt64(const APath: string): Int64; overload;
137 procedure SetInt64(const APath: string;
138 const AValue: Int64);
139 procedure SetDeleteInt64(const APath: string;
140 const AValue, ADefaultValue: Int64);
141 { @groupEnd }
142
143 { 2D, 3D, 4D vectors reading/writing to config file.
144
145 They should be expressed in XML like
146
147 @preformatted(<myVector x="1" y="2" z="3" w="4" />)
148
149 You can read such vector by
150
151 @longCode(# GetVector('example/path/to/myVector', Vector4(0, 0, 0, 0)); #)
152
153 @groupBegin }
154 function GetVector2(const APath: string;
155 const ADefaultValue: TVector2): TVector2; overload;
156 function GetVector2(const APath: string): TVector2; overload;
157 procedure SetVector2(const APath: string;
158 const AValue: TVector2); overload;
159 procedure SetDeleteVector2(const APath: string;
160 const AValue, ADefaultValue: TVector2); overload;
161
162 function GetVector3(const APath: string;
163 const ADefaultValue: TVector3): TVector3; overload;
164 function GetVector3(const APath: string): TVector3; overload;
165 procedure SetVector3(const APath: string;
166 const AValue: TVector3); overload;
167 procedure SetDeleteVector3(const APath: string;
168 const AValue, ADefaultValue: TVector3); overload;
169
170 function GetVector4(const APath: string;
171 const ADefaultValue: TVector4): TVector4; overload;
172 function GetVector4(const APath: string): TVector4; overload;
173 procedure SetVector4(const APath: string;
174 const AValue: TVector4); overload;
175 procedure SetDeleteVector4(const APath: string;
176 const AValue, ADefaultValue: TVector4); overload;
177
178 function GetValue(const APath: string;
179 const ADefaultValue: TVector2): TVector2;
180 overload; deprecated 'use GetVector2';
181 procedure SetValue(const APath: string;
182 const AValue: TVector2);
183 overload; deprecated 'use SetVector2';
184 procedure SetDeleteValue(const APath: string;
185 const AValue, ADefaultValue: TVector2);
186 overload; deprecated 'use SetDeleteVector2';
187
188 function GetValue(const APath: string;
189 const ADefaultValue: TVector3): TVector3;
190 overload; deprecated 'use GetVector3';
191 procedure SetValue(const APath: string;
192 const AValue: TVector3);
193 overload; deprecated 'use SetVector3';
194 procedure SetDeleteValue(const APath: string;
195 const AValue, ADefaultValue: TVector3);
196 overload; deprecated 'use SetDeleteVector3';
197
198 function GetValue(const APath: string;
199 const ADefaultValue: TVector4): TVector4;
200 overload; deprecated 'use GetVector4';
201 procedure SetValue(const APath: string;
202 const AValue: TVector4);
203 overload; deprecated 'use SetVector4';
204 procedure SetDeleteValue(const APath: string;
205 const AValue, ADefaultValue: TVector4);
206 overload; deprecated 'use SetDeleteVector4';
207 { @groupEnd }
208
209 { Colors reading/writing to config file.
210
211 This is very similar to 3D / 4D vector reading/writing to config file,
212 however
213
214 @orderedList(
215 @itemSpacing Compact
216 @item(attribute names are better for colors
217 (@italic(red, green, blue, alpha) instead of @italic(x, y, z, w)),)
218 @item(we allow alternative color specification as hex.)
219 @item(and we limit component values to 0..1 range.)
220 )
221
222 They should be expressed in XML like
223
224 @preformatted(
225 <myColor red="1" green="0.5" blue="0.25" alpha="1" />
226 <myColorRGB red="1" green="0.5" blue="0.25" />
227 )
228
229 or as hex colors (see @link(HexToColor)) like
230
231 @preformatted(
232 <myColor hex="ff804011" />
233 <myColorRGB hex="ff8040" />
234 )
235
236 You can read such colors by
237
238 @longCode(#
239 Color := GetColor('example/path/to/myColor', Black);
240 ColorRGB := GetColorRGB('example/path/to/myColorRGB', BlackRGB);
241 #)
242
243 @groupBegin }
244 function GetColorRGB(const APath: string;
245 const ADefaultColor: TCastleColorRGB): TCastleColorRGB; overload;
246 function GetColorRGB(const APath: string): TCastleColorRGB; overload;
247 procedure SetColorRGB(const APath: string;
248 const AColor: TCastleColorRGB); overload;
249 procedure SetDeleteColorRGB(const APath: string;
250 const AColor, ADefaultColor: TCastleColorRGB); overload;
251
252 function GetColor(const APath: string;
253 const ADefaultColor: TCastleColor): TCastleColor; overload;
254 function GetColor(const APath: string): TCastleColor; overload;
255 procedure SetColor(const APath: string;
256 const AColor: TCastleColor); overload;
257 procedure SetDeleteColor(const APath: string;
258 const AColor, ADefaultColor: TCastleColor); overload;
259 { @groupEnd }
260
261 { For a given path, return corresponding DOM element of XML tree.
262 This is useful if you want to mix XMLConfig style operations
263 on the file and then use some real DOM functions to more directly
264 operate/read on XML document.
265
266 Note that for paths that you pass to various
267 SetValue / SetColor / SetFloat / SetVector versions,
268 the last path component is the attribute name. You do not pass
269 this here. Path passed here should end with the name of final
270 element.
271
272 Path passed here may but doesn't have to be terminated by a final slash.
273 In fact, for now the path is just splitted using slash character
274 as a separator, so a path like @code(/some////path/) is equivalent
275 to a path like (some/path). But don't depend on this behavior.
276
277 If there is no such element:
278 when RaiseExceptionWhenMissing=@true, raises exception.
279 when RaiseExceptionWhenMissing=@false, returns @nil.
280
281 Remember that XMLConfig idea of XML document is limited.
282 That's intentional (XMLConfig is supposed to offer only a simple limited
283 XML access), and this means that some XML trees may confuse XMLConfig.
284 For example, if there are two elements with the same TagName as a children
285 of the same element: XMLConfig will (probably ?) just always ignore
286 the second one. Which means that if you use this method to change
287 some XML content, you should be careful when accessing this content
288 from regular XMLConfig GetValue / SetValue methods.
289
290 Note that if you modify the DOM contents this way,
291 you must manually call MarkModified afterwards, to make sure
292 it will get saved later. }
293 function PathElement(const APath: string;
294 const RaiseExceptionWhenMissing: boolean = false): TDOMElement;
295
296 { Similar to PathElement,
297 but creates the necessary elements along the way as needed. }
298 function MakePathElement(const APath: string): TDOMElement;
299
300 {$ifdef FPC}
301 { For a given path, return corresponding children elements of a given
302 DOM element of XML tree. For example, you have an XML like this:
303
304 @preformatted(
305 <?xml version="1.0" encoding="UTF-8"?>
306 <CONFIG>
307 <game_configuration>
308 <locations>
309 <location name="location_1st">...</location>
310 <location name="location_2nd">...</location>
311 </locations>
312 </game_configuration>
313 </CONFIG>
314 )
315
316 You could use @code(PathElement('game_configuration/locations'))
317 to get the @code(<locations>) DOM element.
318 Or you could use this method @code(PathChildren('game_configuration/locations',
319 'location')) to get a list of <location> elements.
320
321 Raises exception if element indicated by APath does not exist.
322 (But it is OK if it is empty.)
323 Never returns @nil. }
324 function PathChildren(const APath: string; const ChildName: string): TDOMNodeList;
325 deprecated 'use PathChildrenIterator';
326 {$endif}
327
328 { For a given path, return iterator for elements of a given name.
329
330 For example, assume you have an XML like this:
331
332 @preformatted(
333 <?xml version="1.0" encoding="UTF-8"?>
334 <CONFIG>
335 <game_configuration>
336 <locations>
337 <location name="location_1st">...</location>
338 <location name="location_2nd">...</location>
339 </locations>
340 </game_configuration>
341 </CONFIG>
342 )
343
344 You can process it like this:
345
346 @longCode(#
347 var
348 I: TXMLElementIterator;
349 begin
350 I := PathChildrenIterator('game_configuration/locations', 'location');
351 try
352 while I.GetNext do
353 begin
354 // ... here goes your code to process I.Current ...
355 end;
356 finally FreeAndNil(I) end;
357 end;
358 #)
359
360 Raises exception if element indicated by APath does not exist.
361 (But it is OK if it is empty.)
362 Never returns @nil. }
363 function PathChildrenIterator(const APath: string;
364 const ChildName: string): TXMLElementIterator;
365
366 { Read an URL from an XML attribute.
367 The attribute in an XML file may be an absolute or relative URL,
368 (we will look at own TXMLConfig.FileName directory to resolve relative
369 URLs). The returned URL is always an absolute URL.
370
371 If EmptyIfNoAttribute, then this will just set URL to ''
372 if appropriate XML attribute not found. Otherwise
373 (when EmptyIfNoAttribute = @false, this is default),
374 error will be raised.
375
376 @raises(EMissingAttribute If EmptyIfNoAttribute = @false and no such attribute.) }
377 function GetUrl(const APath: string;
378 const EmptyIfNoAttribute: boolean = false): string;
379
380 { Read string from a text content of given element.
381 The text may be multiline, line endings are guaranteed to be converted
382 to current OS newlines. }
383 function GetMultilineText(const APath: string; const DefaultValue: String): string; overload;
384
385 { Read @italic(required, non-empty) string from a text content of given element.
386 The text may be multiline, line endings are guaranteed to be converted
387 to current OS newlines. }
388 function GetMultilineText(const APath: string): string; overload;
389
390 procedure NotModified;
391 procedure MarkModified;
392
393 function Document: TDOMDocument;
394
395 { Listeners, automatically called at the @link(Load) or @link(Save)
396 calls.
397
398 @bold(If the config file is already loaded when you call
399 AddLoadListener, then the Listener is called immediately.)
400 This is useful to make sure that Listener is always called,
401 regardless of the order. (Regardless if you call Config.Load
402 or Config.AddLoadListener first.)
403
404 @groupBegin }
405 procedure AddLoadListener(const Listener: TCastleConfigEvent);
406 procedure AddSaveListener(const Listener: TCastleConfigEvent);
407 procedure RemoveLoadListener(const Listener: TCastleConfigEvent);
408 procedure RemoveSaveListener(const Listener: TCastleConfigEvent);
409 { @groupEnd }
410
411 property IsLoaded: boolean read FLoaded;
412
413 { Load the current persistent data (user preferences, savegames etc.).
414
415 All these methods call the listeners (from AddLoadListener).
416 All these methods update the @link(IsLoaded) property and the URL property.
417 All these methods are secured to never raise exception in case of a currupted
418 config file -- in this case, they silently load an empty config
419 (but keep the new URL, so that following
420 @link(Save) call with overwrite the config location with a good save.)
421
422 @italic(Never call the ancestor load / save methods,
423 like TXMLConfig.LoadFromStream and TXMLConfig.SaveToStream, to be on the safe side.
424 Use the methods below to load / save user config.)
425
426 @unorderedList(
427 @item(The overloaded @code(Load) parameter-less version chooses
428 a default filename for storing application user preferences.
429
430 It uses ApplicationName to pick a filename that is unique
431 to your application. Usually you want to assign
432 @link(TCastleApplicationProperties.ApplicationName ApplicationProperties.ApplicationName),
433 unless you're fine with the default name derived from ParamStr(0).
434
435 It uses @link(ApplicationConfig) to determine location of this file.)
436
437 @item(The overloaded @code(Load) version with URL
438 sets @code(TXMLConfig.Url), loading the file from given URL.
439 The URL may use any supported protocol,
440 see https://castle-engine.io/manual_network.php .
441 It can also just be a filename. )
442
443 @item(The overloaded @code(Load) version with TStream loads from a stream.
444 URL is set to PretendUrl (just pass empty string if you don't
445 need to be able to save it back).)
446 )
447
448 @groupBegin }
449 procedure Load; overload;
450 procedure Load(const AUrl: String); overload;
451 procedure Load(const Stream: TStream; const PretendUrl: String); overload;
452 procedure LoadFromString(const Data: string; const PretendUrl: String);
453 { @groupEnd }
454
455 { Save the user persistent configuration.
456 Calls all the listeners (registered by AddSaveListener).
457
458 @unorderedList(
459 @item(The overloaded parameter-less version flushes
460 the changes to disk, thus saving them back to the file from which
461 they were read (in @code(TXMLConfig.Url) property).)
462
463 @item(The overloaded version with TStream parameter saves to a stream.
464 If does not use inherited Flush method, instead it always
465 unconditionally dumps contents to stream.)
466 )
467
468 @groupBegin }
469 procedure Save; overload;
470 procedure Save(const Stream: TStream); overload;
471 function SaveToString: string;
472 { @groupEnd }
473 end;
474
475 implementation
476
477 uses //Base64,
478 CastleStringUtils, CastleFilesUtils, CastleLog, CastleUriUtils;
479
480 { TCastleConfigEventList ----------------------------------------------------- }
481
482 procedure TCastleConfigEventList.ExecuteAll(const Config: TCastleConfig);
483 var
484 I: Integer;
485 begin
486 for I := 0 to Count - 1 do
487 Items[I](Config);
488 end;
489
490 { TCastleConfig -------------------------------------------------------------- }
491
492 constructor TCastleConfig.Create(AOwner: TComponent);
493 begin
494 inherited;
495 FOnLoad := TCastleConfigEventList.Create;
496 FOnSave := TCastleConfigEventList.Create;
497 end;
498
499 destructor TCastleConfig.Destroy;
500 begin
501 FreeAndNil(FOnLoad);
502 FreeAndNil(FOnSave);
503 inherited;
504 end;
505
506 function TCastleConfig.GetInteger(const APath: string;
507 const ADefaultValue: Integer): Integer;
508 var
509 ResultString: string;
510 begin
511 ResultString := GetValue(APath, IntToStr(ADefaultValue));
512 Result := StrToIntDef(ResultString, ADefaultValue);
513 end;
514
515 function TCastleConfig.GetInteger(const APath: String): Integer;
516 begin
517 Result := StrToInt(GetStringNonEmpty(APath));
518 end;
519
520 function TCastleConfig.GetBoolean(const APath: String): Boolean;
521 var
522 S: String;
523 begin
524 S := GetStringNonEmpty(APath);
525 if AnsiCompareText(S, 'TRUE') = 0 then
526 Result := true else
527 if AnsiCompareText(s, 'FALSE') = 0 then
528 Result := false else
529 raise EConvertError.CreateFmt('Invalid boolean value "%s" in XML attribute "%s"',
530 [S, APath]);
531 end;
532
533 function TCastleConfig.GetStringNonEmpty(const APath: string): string;
534 begin
535 Result := GetValue(APath, '');
536 if Result = '' then
537 raise EMissingAttribute.CreateFmt('Missing attribute "%s" in XML file', [APath]);
538 end;
539
540 function TCastleConfig.GetNonEmptyValue(const APath: string): string;
541 begin
542 Result := GetStringNonEmpty(APath);
543 end;
544
545 { get/set floats ------------------------------------------------------------ }
546
547 function TCastleConfig.GetFloat(const APath: string;
548 const ADefaultValue: Float): Float;
549 var
550 ResultString: string;
551 begin
552 ResultString := GetValue(APath, FloatToStrDot(ADefaultValue));
553 Result := StrToFloatDefDot(ResultString, ADefaultValue);
554 end;
555
556 function TCastleConfig.GetFloat(const APath: string): Float;
557 begin
558 Result := StrToFloatDot(GetStringNonEmpty(APath));
559 end;
560
561 procedure TCastleConfig.SetFloat(const APath: string;
562 const AValue: Float);
563 begin
564 SetValue(APath, FloatToStrDot(AValue));
565 end;
566
567 procedure TCastleConfig.SetDeleteFloat(const APath: string;
568 const AValue, ADefaultValue: Float);
569 begin
570 SetDeleteValue(APath, FloatToStrDot(AValue), FloatToStrDot(ADefaultValue));
571 end;
572
573 { get/set Int64s ------------------------------------------------------------ }
574
575 function TCastleConfig.GetInt64(const APath: string;
576 const ADefaultValue: Int64): Int64;
577 var
578 ResultString: string;
579 begin
580 ResultString := GetValue(APath, IntToStr(ADefaultValue));
581 Result := StrToInt64Def(ResultString, ADefaultValue);
582 end;
583
584 function TCastleConfig.GetInt64(const APath: string): Int64;
585 begin
586 Result := StrToInt64(GetStringNonEmpty(APath));
587 end;
588
589 procedure TCastleConfig.SetInt64(const APath: string;
590 const AValue: Int64);
591 begin
592 SetValue(APath, IntToStr(AValue));
593 end;
594
595 procedure TCastleConfig.SetDeleteInt64(const APath: string;
596 const AValue, ADefaultValue: Int64);
597 begin
598 SetDeleteValue(APath, IntToStr(AValue), IntToStr(ADefaultValue));
599 end;
600
601 { get/set vectors ------------------------------------------------------------ }
602
603 const
604 VectorComponentPaths: array [0..3] of string =
605 ('/x', '/y', '/z', '/w');
606
607 function TCastleConfig.GetVector2(const APath: string;
608 const ADefaultValue: TVector2): TVector2;
609 var
610 I: Integer;
611 begin
612 for I := 0 to ADefaultValue.Count - 1 do
613 Result.Data[I] := GetFloat(APath + VectorComponentPaths[I], ADefaultValue.Data[I]);
614 end;
615
616 function TCastleConfig.GetVector2(const APath: string): TVector2;
617 var
618 I: Integer;
619 begin
620 for I := 0 to Result.Count - 1 do
621 Result.Data[I] := GetFloat(APath + VectorComponentPaths[I]);
622 end;
623
624 procedure TCastleConfig.SetVector2(const APath: string;
625 const AValue: TVector2);
626 var
627 I: Integer;
628 begin
629 for I := 0 to AValue.Count - 1 do
630 SetFloat(APath + VectorComponentPaths[I], AValue.Data[I]);
631 end;
632
633 procedure TCastleConfig.SetDeleteVector2(const APath: string;
634 const AValue, ADefaultValue: TVector2);
635 var
636 I: Integer;
637 begin
638 for I := 0 to AValue.Count - 1 do
639 SetDeleteFloat(APath + VectorComponentPaths[I], AValue.Data[I], ADefaultValue.Data[I]);
640 end;
641
642 function TCastleConfig.GetVector3(const APath: string;
643 const ADefaultValue: TVector3): TVector3;
644 var
645 I: Integer;
646 begin
647 for I := 0 to ADefaultValue.Count - 1 do
648 Result.Data[I] := GetFloat(APath + VectorComponentPaths[I], ADefaultValue.Data[I]);
649 end;
650
651 function TCastleConfig.GetVector3(const APath: string): TVector3;
652 var
653 I: Integer;
654 begin
655 for I := 0 to Result.Count - 1 do
656 Result.Data[I] := GetFloat(APath + VectorComponentPaths[I]);
657 end;
658
659 procedure TCastleConfig.SetVector3(const APath: string;
660 const AValue: TVector3);
661 var
662 I: Integer;
663 begin
664 for I := 0 to AValue.Count - 1 do
665 SetFloat(APath + VectorComponentPaths[I], AValue.Data[I]);
666 end;
667
668 procedure TCastleConfig.SetDeleteVector3(const APath: string;
669 const AValue, ADefaultValue: TVector3);
670 var
671 I: Integer;
672 begin
673 for I := 0 to AValue.Count - 1 do
674 SetDeleteFloat(APath + VectorComponentPaths[I], AValue.Data[I], ADefaultValue.Data[I]);
675 end;
676
677 function TCastleConfig.GetVector4(const APath: string;
678 const ADefaultValue: TVector4): TVector4;
679 var
680 I: Integer;
681 begin
682 for I := 0 to ADefaultValue.Count - 1 do
683 Result.Data[I] := GetFloat(APath + VectorComponentPaths[I], ADefaultValue.Data[I]);
684 end;
685
686 function TCastleConfig.GetVector4(const APath: string): TVector4;
687 var
688 I: Integer;
689 begin
690 for I := 0 to Result.Count - 1 do
691 Result.Data[I] := GetFloat(APath + VectorComponentPaths[I]);
692 end;
693
694 procedure TCastleConfig.SetVector4(const APath: string;
695 const AValue: TVector4);
696 var
697 I: Integer;
698 begin
699 for I := 0 to AValue.Count - 1 do
700 SetFloat(APath + VectorComponentPaths[I], AValue.Data[I]);
701 end;
702
703 procedure TCastleConfig.SetDeleteVector4(const APath: string;
704 const AValue, ADefaultValue: TVector4);
705 var
706 I: Integer;
707 begin
708 for I := 0 to AValue.Count - 1 do
709 SetDeleteFloat(APath + VectorComponentPaths[I], AValue.Data[I], ADefaultValue.Data[I]);
710 end;
711
712 { deprecated get/set on vectors ---------------------------------------------- }
713
714 function TCastleConfig.GetValue(const APath: string;
715 const ADefaultValue: TVector2): TVector2;
716 var
717 I: Integer;
718 begin
719 for I := 0 to ADefaultValue.Count - 1 do
720 Result.Data[I] := GetFloat(APath + VectorComponentPaths[I], ADefaultValue.Data[I]);
721 end;
722
723 procedure TCastleConfig.SetValue(const APath: string;
724 const AValue: TVector2);
725 var
726 I: Integer;
727 begin
728 for I := 0 to AValue.Count - 1 do
729 SetFloat(APath + VectorComponentPaths[I], AValue.Data[I]);
730 end;
731
732 procedure TCastleConfig.SetDeleteValue(const APath: string;
733 const AValue, ADefaultValue: TVector2);
734 var
735 I: Integer;
736 begin
737 for I := 0 to AValue.Count - 1 do
738 SetDeleteFloat(APath + VectorComponentPaths[I], AValue.Data[I], ADefaultValue.Data[I]);
739 end;
740
741 function TCastleConfig.GetValue(const APath: string;
742 const ADefaultValue: TVector3): TVector3;
743 var
744 I: Integer;
745 begin
746 for I := 0 to ADefaultValue.Count - 1 do
747 Result.Data[I] := GetFloat(APath + VectorComponentPaths[I], ADefaultValue.Data[I]);
748 end;
749
750 procedure TCastleConfig.SetValue(const APath: string;
751 const AValue: TVector3);
752 var
753 I: Integer;
754 begin
755 for I := 0 to AValue.Count - 1 do
756 SetFloat(APath + VectorComponentPaths[I], AValue.Data[I]);
757 end;
758
759 procedure TCastleConfig.SetDeleteValue(const APath: string;
760 const AValue, ADefaultValue: TVector3);
761 var
762 I: Integer;
763 begin
764 for I := 0 to AValue.Count - 1 do
765 SetDeleteFloat(APath + VectorComponentPaths[I], AValue.Data[I], ADefaultValue.Data[I]);
766 end;
767
768 function TCastleConfig.GetValue(const APath: string;
769 const ADefaultValue: TVector4): TVector4;
770 var
771 I: Integer;
772 begin
773 for I := 0 to ADefaultValue.Count - 1 do
774 Result.Data[I] := GetFloat(APath + VectorComponentPaths[I], ADefaultValue.Data[I]);
775 end;
776
777 procedure TCastleConfig.SetValue(const APath: string;
778 const AValue: TVector4);
779 var
780 I: Integer;
781 begin
782 for I := 0 to AValue.Count - 1 do
783 SetFloat(APath + VectorComponentPaths[I], AValue.Data[I]);
784 end;
785
786 procedure TCastleConfig.SetDeleteValue(const APath: string;
787 const AValue, ADefaultValue: TVector4);
788 var
789 I: Integer;
790 begin
791 for I := 0 to AValue.Count - 1 do
792 SetDeleteFloat(APath + VectorComponentPaths[I], AValue.Data[I], ADefaultValue.Data[I]);
793 end;
794
795 { get/set colors ------------------------------------------------------------- }
796
797 const
798 ColorComponentPaths: array [0..3] of string =
799 ('/red', '/green', '/blue', '/alpha');
800 HexPath = '/hex';
801
802 function TCastleConfig.GetColorRGB(const APath: string;
803 const ADefaultColor: TCastleColorRGB): TCastleColorRGB;
804 var
805 I: Integer;
806 Hex: string;
807 begin
808 Hex := GetValue(APath + HexPath, '');
809 if Hex <> '' then
810 Result := HexToColorRGB(Hex) else
811 begin
812 Hex := GetValue(APath + HexPath, '');
813 if Hex <> '' then
814 Result := HexToColorRGB(Hex) else
815 begin
816 for I := 0 to ADefaultColor.Count - 1 do
817 Result.Data[I] := Clamped(GetFloat(APath + ColorComponentPaths[I], ADefaultColor.Data[I]), 0.0, 1.0);
818 end;
819 end;
820 end;
821
822 function TCastleConfig.GetColorRGB(const APath: string): TCastleColorRGB;
823 var
824 I: Integer;
825 Hex: string;
826 begin
827 Hex := GetValue(APath + HexPath, '');
828 if Hex <> '' then
829 Result := HexToColorRGB(Hex) else
830 begin
831 Hex := GetValue(APath, '');
832 if Hex <> '' then
833 Result := HexToColorRGB(Hex) else
834 begin
835 for I := 0 to Result.Count - 1 do
836 Result.Data[I] := Clamped(GetFloat(APath + ColorComponentPaths[I]), 0.0, 1.0);
837 end;
838 end;
839 end;
840
841 procedure TCastleConfig.SetColorRGB(const APath: string;
842 const AColor: TCastleColorRGB);
843 var
844 I: Integer;
845 begin
846 SetValue(APath + HexPath, ColorRGBToHex(AColor));
847 for I := 0 to AColor.Count - 1 do
848 DeleteValue(APath + ColorComponentPaths[I]);
849 end;
850
851 procedure TCastleConfig.SetDeleteColorRGB(const APath: string;
852 const AColor, ADefaultColor: TCastleColorRGB);
853 var
854 I: Integer;
855 begin
856 SetDeleteValue(APath + HexPath, ColorRGBToHex(AColor), ColorRGBToHex(ADefaultColor));
857 for I := 0 to AColor.Count - 1 do
858 DeleteValue(APath + ColorComponentPaths[I]);
859 end;
860
861 function TCastleConfig.GetColor(const APath: string;
862 const ADefaultColor: TCastleColor): TCastleColor;
863 var
864 I: Integer;
865 Hex: string;
866 begin
867 Hex := GetValue(APath + HexPath, '');
868 if Hex <> '' then
869 Result := HexToColor(Hex) else
870 begin
871 Hex := GetValue(APath, '');
872 if Hex <> '' then
873 Result := HexToColor(Hex) else
874 begin
875 for I := 0 to ADefaultColor.Count - 1 do
876 Result.Data[I] := Clamped(GetFloat(APath + ColorComponentPaths[I], ADefaultColor.Data[I]), 0.0, 1.0);
877 end;
878 end;
879 end;
880
881 function TCastleConfig.GetColor(const APath: string): TCastleColor;
882 var
883 I: Integer;
884 Hex: string;
885 begin
886 Hex := GetValue(APath + HexPath, '');
887 if Hex <> '' then
888 Result := HexToColor(Hex) else
889 begin
890 Hex := GetValue(APath, '');
891 if Hex <> '' then
892 Result := HexToColor(Hex) else
893 begin
894 for I := 0 to Result.Count - 1 do
895 Result.Data[I] := Clamped(GetFloat(APath + ColorComponentPaths[I]), 0.0, 1.0);
896 end;
897 end;
898 end;
899
900 procedure TCastleConfig.SetColor(const APath: string;
901 const AColor: TCastleColor);
902 var
903 I: Integer;
904 begin
905 SetValue(APath + HexPath, ColorToHex(AColor));
906 for I := 0 to AColor.Count - 1 do
907 DeleteValue(APath + ColorComponentPaths[I]);
908 end;
909
910 procedure TCastleConfig.SetDeleteColor(const APath: string;
911 const AColor, ADefaultColor: TCastleColor);
912 var
913 I: Integer;
914 begin
915 SetDeleteValue(APath + HexPath, ColorToHex(AColor), ColorToHex(ADefaultColor));
916 for I := 0 to AColor.Count - 1 do
917 DeleteValue(APath + ColorComponentPaths[I]);
918 end;
919
920 { others --------------------------------------------------------------------- }
921
922 function TCastleConfig.PathElement(const APath: string;
923 const RaiseExceptionWhenMissing: boolean): TDOMElement;
924 var
925 SeekPos: Integer;
926 PathComponent: string;
927 begin
928 Result := Document.DocumentElement;
929 SeekPos := 1;
930 while Result <> nil do
931 begin
932 PathComponent := NextToken(APath, SeekPos, ['/']);
933 if PathComponent = '' then break;
934 Result := Result.ChildElement(PathComponent, false);
935 end;
936
937 if (Result = nil) and RaiseExceptionWhenMissing then
938 raise Exception.CreateFmt('Missing element "%s" in file "%s"', [APath, Url]);
939 end;
940
941 function TCastleConfig.MakePathElement(const APath: string): TDOMElement;
942 var
943 SeekPos: Integer;
944 PathComponent: string;
945 NewResult: TDOMElement;
946 begin
947 Result := Document.DocumentElement;
948 SeekPos := 1;
949 { only exits by break, for consistency with PathElement implementation above }
950 while true do
951 begin
952 PathComponent := NextToken(APath, SeekPos, ['/']);
953 if PathComponent = '' then break;
954 NewResult := Result.ChildElement(PathComponent, false);
955 { create child if necessary }
956 if NewResult = nil then
957 begin
958 NewResult := Document.CreateElement({$ifdef FPC}UTF8Decode({$endif}PathComponent{$ifdef FPC}){$endif});
959 Result.AppendChild(NewResult);
960 end;
961 Result := NewResult;
962 end;
963 end;
964
965 {$ifdef FPC}
966 function TCastleConfig.PathChildren(const APath: string;
967 const ChildName: string): TDOMNodeList;
968 begin
969 Result := PathElement(APath, true).GetElementsByTagName(UTF8Decode(ChildName));
970 end;
971 {$endif}
972
973
974 function TCastleConfig.PathChildrenIterator(const APath: string;
975 const ChildName: string): TXMLElementIterator;
976 begin
977 Result := PathElement(APath, true).ChildrenIterator(ChildName);
978 end;
979
980 function TCastleConfig.GetUrl(const APath: string;
981 const EmptyIfNoAttribute: boolean): string;
982 begin
983 Result := GetValue(APath, '');
984 if Result = '' then
985 begin
986 if not EmptyIfNoAttribute then
987 raise EMissingAttribute.CreateFmt('Missing attribute "%s" in XML file', [APath]);
988 end else
989 Result := CombineURI(Url, Result);
990 end;
991
992 function TCastleConfig.GetMultilineText(const APath: string;
993 const DefaultValue: String): string;
994 var
995 E: TDOMElement;
996 begin
997 E := PathElement(APath, false);
998 if E = nil then
999 Result := DefaultValue else
1000 Result := UTF8Encode(E.TextContent);
1001 { convert all to Unix-line endings }
1002 StringReplaceAllVar(Result, #13, '', false);
1003 { in case we're not on Unix, convert to current line endings }
1004 {$warnings off} { don't warn about dead code on OSes where NL = #10 }
1005 if #10 <> NL then
1006 StringReplaceAllVar(Result, #10, NL, false);
1007 {$warnings on}
1008 end;
1009
1010 function TCastleConfig.GetMultilineText(const APath: string): string;
1011 begin
1012 Result := GetMultilineText(APath, '');
1013 if Result = '' then
1014 raise EMissingAttribute.CreateFmt('Missing multi-line text context of element "%s" in XML file', [APath]);
1015 end;
1016
1017 procedure TCastleConfig.NotModified;
1018 begin
1019 FModified := false;
1020 end;
1021
1022 procedure TCastleConfig.MarkModified;
1023 begin
1024 FModified := true;
1025 end;
1026
1027 function TCastleConfig.Document: TDOMDocument;
1028 begin
1029 Result := Doc;
1030 end;
1031
1032 { loading and saving --------------------------------------------------------- }
1033
1034 procedure TCastleConfig.AddLoadListener(const Listener: TCastleConfigEvent);
1035 begin
1036 if IsLoaded then
1037 Listener(Self);
1038 FOnLoad.Add(Listener);
1039 end;
1040
1041 procedure TCastleConfig.AddSaveListener(const Listener: TCastleConfigEvent);
1042 begin
1043 FOnSave.Add(Listener);
1044 end;
1045
1046 procedure TCastleConfig.RemoveLoadListener(const Listener: TCastleConfigEvent);
1047 begin
1048 FOnLoad.Remove(Listener);
1049 end;
1050
1051 procedure TCastleConfig.RemoveSaveListener(const Listener: TCastleConfigEvent);
1052 begin
1053 FOnSave.Remove(Listener);
1054 end;
1055
1056 procedure TCastleConfig.Load;
1057 begin
1058 Load(ApplicationConfig(ApplicationName + '.conf'));
1059 end;
1060
1061 procedure TCastleConfig.Load(const AUrl: String);
1062
1063 procedure BackupCorruptedUserConfig(const AUrl: String);
1064 var
1065 CurrentFileName, NewFileName: String;
1066 begin
1067 CurrentFileName := UriToFilenameSafe(AUrl);
1068 if (CurrentFileName <> '') and RegularFileExists(CurrentFileName) then
1069 begin
1070 NewFileName := FileNameAutoInc(CurrentFileName, '.corrupted.%d');
1071 if RenameFile(CurrentFileName, NewFileName) then
1072 WritelnLog('UserConfig', 'Renamed corrupted user config file "' + CurrentFileName + '" to "' + NewFileName + '"')
1073 else
1074 WritelnWarning('UserConfig', 'Cannot rename corrupted user config file "' + CurrentFileName + '" to "' + NewFileName + '"');
1075 end;
1076 end;
1077
1078 begin
1079 try
1080 Url := AUrl; // use ancestor method to load
1081 except
1082 on E: Exception do
1083 begin
1084 BackupCorruptedUserConfig(AUrl);
1085 WritelnWarning('UserConfig', 'User config in "' + AUrl + '" corrupted (will load defaults): ' + E.Message);
1086 LoadEmpty(AUrl);
1087 Exit;
1088 end;
1089 end;
1090
1091 FOnLoad.ExecuteAll(Self);
1092 FLoaded := true;
1093 { This is used for various files (not just user preferences,
1094 also resource.xml files). Logging this may get talkative, but it's also
1095 useful for now... }
1096 WritelnLog('Config', 'Loaded configuration from "%s"', [AUrl]);
1097 end;
1098
1099 procedure TCastleConfig.Load(const Stream: TStream; const PretendUrl: String);
1100 begin
1101 try
1102 LoadFromStream(Stream, PretendUrl); // use ancestor method to load
1103 except
1104 on E: Exception do
1105 begin
1106 WritelnWarning('UserConfig', 'User config in stream corrupted (will load defaults): ' + E.Message);
1107 LoadEmpty(PretendUrl);
1108 Exit;
1109 end;
1110 end;
1111
1112 FOnLoad.ExecuteAll(Self);
1113 FLoaded := true;
1114 WritelnLog('Config', 'Loaded configuration from stream, pretending the Url is "%s"', [PretendUrl]);
1115 end;
1116
1117 procedure TCastleConfig.LoadFromString(const Data: string; const PretendUrl: String);
1118 var
1119 InputStream: TStringStream;
1120 begin
1121 InputStream := TStringStream.Create(Data);
1122 try
1123 Load(InputStream, PretendUrl);
1124 finally FreeAndNil(InputStream) end;
1125 end;
1126
1127 procedure TCastleConfig.LoadEmpty(const PretendUrl: String);
1128 const
1129 EmptyConfig = '<?xml version="1.0" encoding="utf-8"?>' + LineEnding +
1130 '<CONFIG>' + LineEnding +
1131 '</CONFIG>';
1132 begin
1133 LoadFromString(EmptyConfig, PretendUrl);
1134 end;
1135
1136 procedure TCastleConfig.Save;
1137 begin
1138 FOnSave.ExecuteAll(Self);
1139 if Flush then //use ancestor method to save
1140 WriteLnLog('Config', 'Saving configuration to "%s"', [UriDisplay(Url)])
1141 else
1142 if Url <> '' then
1143 WriteLnLog('Config', 'No changes in config to save "%s"', [UriDisplay(Url)])
1144 else
1145 WriteLnWarning('Config', 'Configuration was not saved, because no URL is specified. Call TCastleConfig.Load or explicitly set TCastleConfig.Url before calling TCastleConfig.Save.');
1146 end;
1147
1148 procedure TCastleConfig.Save(const Stream: TStream);
1149 begin
1150 FOnSave.ExecuteAll(Self);
1151 SaveToStream(Stream); // use ancestor method to save
1152 WritelnLog('Config', 'Saving configuration to stream');
1153 end;
1154
1155 function TCastleConfig.SaveToString: string;
1156 var
1157 ResultStream: TStringStream;
1158 begin
1159 ResultStream := TStringStream.Create('');
1160 try
1161 Save(ResultStream);
1162 Result := ResultStream.DataString;
1163 finally FreeAndNil(ResultStream) end;
1164 end;
1165
1166 end.