Debian Codegraph @

src/files/castlexmlcfginternal.pas

raw
1 { Copied from FPC XmlCfg unit.
2 Adjusted to be able to read / write from / to URLs using our routines.
3 It can also encrypt / decrypt using BlowFish.
4
5 Also, removed the "deprecated" tag ---
6 In new FPC versions, XMLConf unit is advised and XMLCfg is deprecated.
7 See e.g. [http://www.mail-archive.com/[email protected]/msg09489.html].
8 But XMLConf requires adding units to your uses clause that are otherwise
9 not needed:
10
11 This binary has no unicodestrings support compiled in.
12 Recompile the application with a unicodestrings-manager in the program uses clause.
13
14 So we keep using this unit for now.
15 }
16
17 {
18 This file is part of the Free Component Library
19
20 Implementation of TXMLConfig class
21 Copyright (c) 1999 - 2005 by Sebastian Guenther, [email protected]
22
23 This file is adapted from the FPC RTL source code, as such
24 the license and copyright information of FPC RTL applies here.
25 That said, the license of FPC RTL happens to be *exactly*
26 the same as used by the "Castle Game Engine": LGPL (version 2.1)
27 with "static linking exception" (with exactly the same wording
28 of the "static linking exception").
29 See the file COPYING.txt, included in this distribution, for details about
30 the copyright of "Castle Game Engine".
31 See http://www.freepascal.org/faq.var#general-license about the copyright
32 of FPC RTL.
33
34 This program is distributed in the hope that it will be useful,
35 but WITHOUT ANY WARRANTY; without even the implied warranty of
36 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
37
38 **********************************************************************}
39
40 {
41 TXMLConfig enables applications to use XML files for storing their
42 configuration data
43 }
44
45 { @exclude Not ready for PasDoc, also internal. }
46 unit CastleXMLCfgInternal;
47
48 {$I castleconf.inc}
49
50 interface
51
52 {off $DEFINE MEM_CHECK}
53
54 uses
55 {$IFDEF MEM_CHECK}MemCheck,{$ENDIF}
56 SysUtils, Classes, DOM, XMLRead, XMLWrite,
57 CastleClassUtils;
58
59 resourcestring
60 SMissingPathName = 'A part of the pathname is invalid (missing)';
61 SEscapingNecessary = 'Invalid pathname, escaping must be enabled';
62 SWrongRootName = 'XML file has wrong root element name';
63
64 type
65
66 EXMLConfigError = class(Exception);
67
68 {"APath" is the path and name of a value: A XML configuration file is
69 hierachical. "/" is the path delimiter, the part after the last "/"
70 is the name of the value. The path components will be mapped to XML
71 elements, the name will be an element attribute.}
72
73 TXMLConfig = class(TCastleComponent)
74 private
75 FUrl: String;
76 FStartEmpty: Boolean;
77 FUseEscaping: Boolean;
78 FRootName: DOMString;
79 FBlowFishKeyPhrase: string;
80 procedure SetUrlForce(const AUrl: String; ForceReload: Boolean);
81 procedure SetUrl(const AUrl: String);
82 procedure SetStartEmpty(AValue: Boolean);
83 procedure SetRootName(const AValue: DOMString);
84 protected
85 Doc: TXMLDocument;
86 FModified: Boolean;
87 procedure Loaded; override;
88 function FindNode(const APath: String; PathHasValue: boolean): TDomNode;
89 function Escape(const s: String): String;
90 public
91 constructor Create(AOwner: TComponent); override;
92 destructor Destroy; override;
93 procedure Clear;
94 { Writes the config to XML file in @link(Url).
95 @returns(@true If the file was really written to disk.
96 Returns @false if file was not written,
97 which may happen if there were no changes in config since the last save/load,
98 or if the @link(Url) wasn't set.) }
99 function Flush : Boolean;
100 function GetValue(const APath, ADefault: String): String; overload;
101 function GetValue(const APath: String; ADefault: Integer): Integer; overload;
102 function GetValue(const APath: String; ADefault: Boolean): Boolean; overload;
103 procedure SetValue(const APath, AValue: String); overload;
104 procedure SetDeleteValue(const APath, AValue, DefValue: String); overload;
105 procedure SetValue(const APath: String; AValue: Integer); overload;
106 procedure SetDeleteValue(const APath: String; AValue, DefValue: Integer); overload;
107 procedure SetValue(const APath: String; AValue: Boolean); overload;
108 procedure SetDeleteValue(const APath: String; AValue, DefValue: Boolean); overload;
109 procedure DeletePath(const APath: string);
110 procedure DeleteValue(const APath: string);
111 property Modified: Boolean read FModified;
112
113 { Load and save config state to a TStream instance.
114 Loading changes URL to PretendUrl, and does Flush before, so it works
115 similarly to setting an URL.
116 Saving does not change any state (it also ignores the @link(Modified)
117 value), it unconditionally dumps the contents to stream.
118 @groupBegin }
119 procedure LoadFromStream(const Stream: TStream; const PretendUrl: String);
120 procedure SaveToStream(const Stream: TStream);
121 { @groupEnd }
122 published
123 property Url: String read FUrl write SetUrl;
124 { If non-empty, we will encrypt / decrypt the XML data when
125 writing / reading using BlowFish.
126 Note: only first @code(High(TBlowFishKey)+1) characters matter. }
127 property BlowFishKeyPhrase: string read FBlowFishKeyPhrase write FBlowFishKeyPhrase;
128 property StartEmpty: Boolean read FStartEmpty write SetStartEmpty;
129 property UseEscaping: Boolean read FUseEscaping write FUseEscaping
130 default True;
131 property RootName: DOMString read FRootName write SetRootName;
132 end;
133
134
135 // ===================================================================
136
137 implementation
138
139 uses CastleXmlUtils, CastleUriUtils, CastleStringUtils;
140
141 constructor TXMLConfig.Create(AOwner: TComponent);
142 begin
143 inherited Create(AOwner);
144 FUseEscaping := True;
145 FRootName := 'CONFIG';
146 Doc := TXMLDocument.Create;
147 Doc.AppendChild(Doc.CreateElement(RootName));
148 end;
149
150 destructor TXMLConfig.Destroy;
151 begin
152 if Assigned(Doc) then
153 begin
154 Flush;
155 FreeAndNil(Doc);
156 end;
157 inherited Destroy;
158 end;
159
160 procedure TXMLConfig.Clear;
161 begin
162 Doc.ReplaceChild(Doc.CreateElement(RootName), Doc.DocumentElement);
163 FModified := true;
164 end;
165
166 function TXMLConfig.Flush: Boolean;
167 begin
168 if (Url <> EmptyStr) and Modified then
169 begin
170 if BlowFishKeyPhrase <> '' then
171 // TODO: Delphi support
172 UrlWriteXML(Doc, Url{$ifdef FPC}, BlowFishKeyPhrase{$endif})
173 else
174 UrlWriteXML(Doc, Url);
175 FModified := false;
176 Result := true;
177 end else
178 Result := false;
179 end;
180
181 function TXMLConfig.GetValue(const APath, ADefault: String): String;
182 var
183 Node, Child, Attr: TDOMNode;
184 NodeName: String;
185 {$ifdef FPC}
186 PathLen: Integer;
187 StartPos, EndPos:Integer;
188 {$else}
189 NodeNames: TStrings;
190 I: Integer;
191 {$endif}
192 begin
193 Result := ADefault;
194 Node := Doc.DocumentElement;
195 {$ifdef FPC}
196 PathLen := Length(APath);
197 StartPos := 1;
198 while True do
199 begin
200 EndPos := StartPos;
201 while (EndPos <= PathLen) and (APath[EndPos] <> '/') do
202 Inc(EndPos);
203 if EndPos > PathLen then
204 break;
205 SetLength(NodeName, EndPos - StartPos);
206 Move(APath[StartPos], NodeName[1], EndPos - StartPos);
207 StartPos := EndPos + 1;
208 Child := Node.FindNode(UTF8decode(Escape(NodeName)));
209 if not Assigned(Child) then
210 Exit;
211 Node := Child;
212 end;
213 if StartPos > PathLen then
214 Exit;
215 SetLength(NodeName, PathLen - StartPos + 1);
216 Move(APath[StartPos], NodeName[1], Length(NodeName));
217 Attr := Node.Attributes.GetNamedItem(UTF8Decode(Escape(NodeName)));
218 if Assigned(Attr) then
219 Result := Attr.NodeValue8;
220 {$else}
221 NodeNames := TStringList.Create;
222 try
223 ExtractStrings(['/'], [], PWideChar(APath), NodeNames);
224
225 if NodeNames.Count = 0 then
226 Exit;
227
228 if NodeNames.Count > 1 then
229 for I := 0 to NodeNames.Count - 2 do
230 begin
231 NodeName := Escape(NodeNames[I]);
232 Child := Node.FindNode(NodeName);
233 if not Assigned(Child) then
234 Exit;
235 Node := Child;
236 end;
237 NodeName := Escape(NodeNames[NodeNames.Count - 1]);
238 Attr := Node.Attributes.GetNamedItem(Escape(NodeName));
239 if Assigned(Attr) then
240 Result := Attr.NodeValue8;
241 finally
242 FreeAndNil(NodeNames);
243 end;
244 {$endif}
245 end;
246
247 function TXMLConfig.GetValue(const APath: String; ADefault: Integer): Integer;
248 begin
249 Result := StrToIntDef(GetValue(APath, IntToStr(ADefault)), ADefault);
250 end;
251
252 function TXMLConfig.GetValue(const APath: String; ADefault: Boolean): Boolean;
253 var
254 s: String;
255 begin
256 if ADefault then
257 s := 'True'
258 else
259 s := 'False';
260
261 s := GetValue(APath, s);
262
263 if AnsiCompareText(s, 'TRUE')=0 then
264 Result := True
265 else if AnsiCompareText(s, 'FALSE')=0 then
266 Result := False
267 else
268 Result := ADefault;
269 end;
270
271 procedure TXMLConfig.SetValue(const APath, AValue: String);
272 var
273 Node, Child: TDOMNode;
274 NodeName: String;
275 {$ifdef FPC}
276 PathLen: Integer;
277 StartPos, EndPos: Integer;
278 {$else}
279 NodeNames: TStrings;
280 I: Integer;
281 {$endif}
282 begin
283 Node := Doc.DocumentElement;
284 {$ifdef FPC}
285 PathLen := Length(APath);
286 StartPos:=1;
287 while True do
288 begin
289 EndPos := StartPos;
290 while (EndPos <= PathLen) and (APath[EndPos] <> '/') do
291 Inc(EndPos);
292 if EndPos > PathLen then
293 break;
294 SetLength(NodeName, EndPos - StartPos);
295 Move(APath[StartPos], NodeName[1], EndPos - StartPos);
296 StartPos := EndPos + 1;
297 NodeName := Escape(NodeName);
298 Child := Node.FindNode(UTF8Decode(NodeName));
299 if not Assigned(Child) then
300 begin
301 Child := Doc.CreateElement(UTF8Decode(NodeName));
302 Node.AppendChild(Child);
303 end;
304 Node := Child;
305 end;
306
307 if StartPos > PathLen then
308 exit;
309 SetLength(NodeName, PathLen - StartPos + 1);
310 Move(APath[StartPos], NodeName[1], Length(NodeName));
311 NodeName := Escape(NodeName);
312 if (not Assigned(TDOMElement(Node).GetAttributeNode(UTF8Decode(NodeName)))) or
313 (TDOMElement(Node)[UTF8decode(NodeName)] <> UTF8Decode(AValue)) then
314 begin
315 TDOMElement(Node)[UTF8decode(NodeName)] := UTF8Decode(AValue);
316 FModified := True;
317 end;
318 {$else}
319 NodeNames := TStringList.Create;
320 try
321 ExtractStrings(['/'], [], PWideChar(APath), NodeNames);
322
323 if NodeNames.Count = 0 then
324 Exit;
325
326 if NodeNames.Count > 1 then
327 for I := 0 to NodeNames.Count - 2 do
328 begin
329 NodeName := Escape(NodeNames[I]);
330 Child := Node.FindNode(NodeName);
331 if not Assigned(Child) then
332 begin
333 Child := Doc.CreateElement(NodeName);
334 Node.AppendChild(Child);
335 end;
336 Node := Child;
337 end;
338 NodeName := Escape(NodeNames[NodeNames.Count - 1]);
339 if (not Assigned(TDOMElement(Node).GetAttributeNode(NodeName))) or
340 (TDOMElement(Node)[NodeName] <> AValue) then
341 begin
342 TDOMElement(Node)[NodeName] := AValue;
343 FModified := True;
344 end;
345 finally
346 FreeAndNil(NodeNames);
347 end;
348 {$endif}
349 end;
350
351 procedure TXMLConfig.SetDeleteValue(const APath, AValue, DefValue: String);
352 begin
353 if AValue = DefValue then
354 DeleteValue(APath)
355 else
356 SetValue(APath, AValue);
357 end;
358
359 procedure TXMLConfig.SetValue(const APath: String; AValue: Integer);
360 begin
361 SetValue(APath, IntToStr(AValue));
362 end;
363
364 procedure TXMLConfig.SetDeleteValue(const APath: String; AValue,
365 DefValue: Integer);
366 begin
367 if AValue = DefValue then
368 DeleteValue(APath)
369 else
370 SetValue(APath, AValue);
371 end;
372
373 procedure TXMLConfig.SetValue(const APath: String; AValue: Boolean);
374 begin
375 if AValue then
376 SetValue(APath, 'True')
377 else
378 SetValue(APath, 'False');
379 end;
380
381 procedure TXMLConfig.SetDeleteValue(const APath: String; AValue,
382 DefValue: Boolean);
383 begin
384 if AValue = DefValue then
385 DeleteValue(APath)
386 else
387 SetValue(APath,AValue);
388 end;
389
390 procedure TXMLConfig.DeletePath(const APath: string);
391 var
392 Node: TDomNode;
393 begin
394 Node := FindNode(APath, False);
395 if (Node = nil) or (Node.ParentNode = nil) then
396 exit;
397 Node.ParentNode.RemoveChild(Node);
398 FModified := True;
399 end;
400
401 procedure TXMLConfig.DeleteValue(const APath: string);
402 var
403 Node: TDomNode;
404 NodeName: String;
405 StartPos: Integer;
406 begin
407 Node := FindNode(APath, True);
408 if not Assigned(Node) then
409 Exit;
410
411 {$ifdef FPC}
412 StartPos := Length(APath);
413 while (StartPos > 0) and (APath[StartPos] <> '/') do
414 Dec(StartPos);
415 NodeName := Escape(Copy(APath, StartPos+1, Length(APath) - StartPos));
416 if (not Assigned(TDOMElement(Node).GetAttributeNode(UTF8Decode(NodeName)))) then
417 Exit;
418 TDOMElement(Node).RemoveAttribute(UTF8Decode(NodeName));
419 {$else}
420 StartPos := BackPos('/', APath);
421 if StartPos = 0 then
422 NodeName := APath
423 else
424 NodeName := Copy(APath, StartPos + 1, Length(APath) - StartPos);
425
426 if (not Assigned(TDOMElement(Node).GetAttributeNode(NodeName))) then
427 Exit;
428 TDOMElement(Node).RemoveAttribute(NodeName);
429 {$endif}
430 FModified := True;
431 end;
432
433 procedure TXMLConfig.Loaded;
434 begin
435 inherited Loaded;
436 if Length(Url) > 0 then
437 SetUrlForce(Url, true); // Load the XML config file
438 end;
439
440 function TXMLConfig.FindNode(const APath: String;
441 PathHasValue: boolean): TDomNode;
442 var
443 NodePath: String;
444 {$ifdef FPC}
445 StartPos, EndPos: integer;
446 PathLen: integer;
447 {$else}
448 NodeNames: TStrings;
449 I, Count: Integer;
450 {$endif}
451 begin
452 Result := Doc.DocumentElement;
453 {$ifdef FPC}
454 PathLen := Length(APath);
455 StartPos := 1;
456 while Assigned(Result) do
457 begin
458 EndPos := StartPos;
459 while (EndPos <= PathLen) and (APath[EndPos] <> '/') do
460 Inc(EndPos);
461 if (EndPos > PathLen) and PathHasValue then
462 exit;
463 if EndPos = StartPos then
464 break;
465 SetLength(NodePath, EndPos - StartPos);
466 Move(APath[StartPos], NodePath[1], Length(NodePath));
467 Result := Result.FindNode(UTF8Decode(Escape(NodePath)));
468 StartPos := EndPos + 1;
469 if StartPos > PathLen then
470 exit;
471 end;
472 Result := nil;
473 {$else}
474 NodeNames := TStringList.Create;
475 try
476 ExtractStrings(['/'], [], PWideChar(APath), NodeNames);
477
478 if NodeNames.Count = 0 then
479 Exit(nil);
480
481 if PathHasValue and (NodeNames.Count = 1) then
482 Exit;
483
484 if PathHasValue then
485 Count := NodeNames.Count - 1
486 else
487 Count := NodeNames.Count;
488
489 for I := 0 to Count - 1 do
490 begin
491 Result := Result.FindNode(NodeNames[I]);
492 if not Assigned(Result) then
493 Exit;
494 end;
495 finally
496 FreeAndNil(NodeNames);
497 end;
498 {$endif}
499 end;
500
501 function TXMLConfig.Escape(const s: String): String;
502 const
503 AllowedChars = ['A'..'Z', 'a'..'z', '0'..'9', '.', '-', '_'];
504 var
505 EscapingNecessary: Boolean;
506 i: Integer;
507 begin
508 if Length(s) < 1 then
509 raise EXMLConfigError.Create(SMissingPathName);
510
511 if not (s[1] in ['A'..'Z', 'a'..'z', '_']) then
512 EscapingNecessary := True
513 else
514 begin
515 EscapingNecessary := False;
516 for i := 2 to Length(s) do
517 if not (s[i] in AllowedChars) then
518 begin
519 EscapingNecessary := True;
520 break;
521 end;
522 end;
523
524 if EscapingNecessary then
525 if UseEscaping then
526 begin
527 Result := '_';
528 for i := 1 to Length(s) do
529 if s[i] in (AllowedChars - ['_']) then
530 Result := Result + s[i]
531 else
532 Result := Result + '_' + IntToHex(Ord(s[i]), 2);
533 end else
534 raise EXMLConfigError.Create(SEscapingNecessary)
535 else // No escaping necessary
536 Result := s;
537 end;
538
539 procedure TXMLConfig.SetUrlForce(const AUrl: String; ForceReload: Boolean);
540 begin
541 {$IFDEF MEM_CHECK}CheckHeapWrtMemCnt('TXMLConfig.SetUrl A '+AUrl);{$ENDIF}
542 if (not ForceReload) and (FUrl = AUrl) then
543 exit;
544 Flush;
545 FreeAndNil(Doc);
546
547 FUrl := AUrl;
548
549 if IsLoading then
550 exit;
551
552 if URIFileExists(AUrl) and (not FStartEmpty) then
553 if BlowFishKeyPhrase <> '' then
554 // TODO: Delphi support
555 UrlReadXML(Doc, AUrl{$ifdef FPC}, BlowFishKeyPhrase{$endif})
556 else
557 UrlReadXML(Doc, AUrl);
558
559 if not Assigned(Doc) then
560 Doc := TXMLDocument.Create;
561
562 if not Assigned(Doc.DocumentElement) then
563 Doc.AppendChild(Doc.CreateElement(RootName))
564 else
565 if Doc.DocumentElement.NodeName <> RootName then
566 raise EXMLConfigError.Create('XML file has wrong root element name');
567
568 {$IFDEF MEM_CHECK}CheckHeapWrtMemCnt('TXMLConfig.SetUrl END');{$ENDIF}
569 end;
570
571 procedure TXMLConfig.LoadFromStream(const Stream: TStream; const PretendUrl: String);
572 begin
573 Flush;
574 FreeAndNil(Doc);
575 FUrl := PretendUrl;
576
577 ReadXMLFile(Doc, Stream);
578
579 if not Assigned(Doc) then
580 Doc := TXMLDocument.Create;
581
582 if not Assigned(Doc.DocumentElement) then
583 Doc.AppendChild(Doc.CreateElement(RootName)) else
584 if Doc.DocumentElement.NodeName <> RootName then
585 raise EXMLConfigError.Create('XML file has wrong root element name');
586 end;
587
588 procedure TXMLConfig.SaveToStream(const Stream: TStream);
589 begin
590 WriteXMLFile(Doc, Stream);
591 end;
592
593 procedure TXMLConfig.SetUrl(const AUrl: String);
594 begin
595 SetUrlForce(AUrl, False);
596 end;
597
598 procedure TXMLConfig.SetRootName(const AValue: DOMString);
599 var
600 Cfg: TDOMElement;
601 begin
602 if AValue <> RootName then
603 begin
604 FRootName := AValue;
605 Cfg := Doc.CreateElement(AValue);
606 while Assigned(Doc.DocumentElement.FirstChild) do
607 Cfg.AppendChild(Doc.DocumentElement.FirstChild);
608 Doc.ReplaceChild(Cfg, Doc.DocumentElement);
609 FModified := True;
610 end;
611 end;
612
613 procedure TXMLConfig.SetStartEmpty(AValue: Boolean);
614 begin
615 if AValue <> StartEmpty then
616 begin
617 FStartEmpty := AValue;
618 if (not AValue) and not Modified then
619 SetUrlForce(Url, True);
620 end;
621 end;
622
623 end.