Debian Codegraph @

components/Image32/source/Img32.SVG.Core.pas

raw
1 unit Img32.SVG.Core;
2
3 (*******************************************************************************
4 * Author : Angus Johnson *
5 * Version : 4.7 *
6 * Date : 12 January 2025 *
7 * Website : http://www.angusj.com *
8 * Copyright : Angus Johnson 2019-2025 *
9 * *
10 * Purpose : Essential structures and functions to read SVG files *
11 * *
12 * License : Use, modification & distribution is subject to *
13 * Boost Software License Ver 1 *
14 * http://www.boost.org/LICENSE_1_0.txt *
15 *******************************************************************************)
16
17 interface
18
19 {$I Img32.inc}
20
21 uses
22 SysUtils, Classes, Types, Math, StrUtils,
23 {$IFDEF XPLAT_GENERICS} Generics.Collections, Generics.Defaults,{$ENDIF}
24 Img32, Img32.Vector, Img32.Text, Img32.Transform;
25
26 {$IFDEF ZEROBASEDSTR}
27 {$ZEROBASEDSTRINGS OFF}
28 {$ENDIF}
29
30 type
31 TSvgEncoding = (eUnknown, eUtf8, eUnicodeLE, eUnicodeBE);
32
33 TUnitType = (utUnknown, utNumber, utPercent, utEm, utEx, utPixel,
34 utCm, utMm, utInch, utPt, utPica, utDegree, utRadian);
35
36 //////////////////////////////////////////////////////////////////////
37 // TValue - Structure to store numerics with measurement units.
38 // See https://www.w3.org/TR/SVG/types.html#InterfaceSVGLength
39 // and https://www.w3.org/TR/SVG/types.html#InterfaceSVGAngle
40 //////////////////////////////////////////////////////////////////////
41
42 //Unfortunately unit-less values can exhibit ambiguity, especially when their
43 //values are small (eg < 1.0). These values can be either absolute values or
44 //relative values (ie relative to the supplied dimension size).
45 //The 'assumeRelValBelow' parameter (see below) attempts to address this
46 //ambiguity, such that unit-less values will be assumed to be 'relative' when
47 //'rawVal' is less than the supplied 'assumeRelValBelow' value.
48
49 TValue = {$IFDEF RECORD_METHODS} record {$ELSE} object {$ENDIF}
50 rawVal : double;
51 unitType : TUnitType;
52 procedure Init;
53 procedure SetValue(val: double; unitTyp: TUnitType = utNumber);
54 function GetValue(relSize: double; assumeRelValBelow: Double): double;
55 function GetValueXY(const relSize: TRectD; assumeRelValBelow: Double): double;
56 function IsValid: Boolean;
57 function IsRelativeValue(assumeRelValBelow: double): Boolean;
58 {$IFDEF INLINE} inline; {$ENDIF}
59 function HasFontUnits: Boolean;
60 function HasAngleUnits: Boolean;
61 end;
62
63 TValuePt = {$IFDEF RECORD_METHODS} record {$ELSE} object {$ENDIF}
64 X, Y : TValue;
65 procedure Init;
66 function GetPoint(const relSize: double; assumeRelValBelow: Double): TPointD; overload;
67 function GetPoint(const relSize: TRectD; assumeRelValBelow: Double): TPointD; overload;
68 function IsValid: Boolean;
69 end;
70
71 TValueRecWH = {$IFDEF RECORD_METHODS} record {$ELSE} object {$ENDIF}
72 left : TValue;
73 top : TValue;
74 width : TValue;
75 height : TValue;
76 procedure Init;
77 function GetRectD(const relSize: TRectD; assumeRelValBelow: Double): TRectD; overload;
78 function GetRectD(relSize: double; assumeRelValBelow: Double): TRectD; overload;
79 function GetRectD(relSizeX, relSizeY: double; assumeRelValBelow: Double): TRectD; overload;
80 function GetRectWH(const relSize: TRectD; assumeRelValBelow: Double): TRectWH;
81 function IsValid: Boolean;
82 function IsEmpty: Boolean;
83 end;
84
85 {$IFNDEF UNICODE}
86 UTF8Char = Char;
87 PUTF8Char = PChar;
88 {$ELSE}
89 {$IF COMPILERVERSION < 31}
90 UTF8Char = AnsiChar;
91 PUTF8Char = PAnsiChar;
92 {$IFEND}
93 {$ENDIF}
94
95 TSvgItalicSyle = (sfsUndefined, sfsNone, sfsItalic);
96 TFontDecoration = (fdUndefined, fdNone, fdUnderline, fdStrikeThrough);
97 TSvgTextAlign = (staUndefined, staLeft, staCenter, staRight, staJustify);
98 TSpacesInText = (sitUndefined, sitIgnore, sitPreserve);
99
100 UTF8Strings = array of UTF8String;
101
102 TSVGFontInfo = record
103 family : TFontFamily;
104 familyNames : UTF8Strings;
105 size : double;
106 spacing : double;
107 spacesInText : TSpacesInText;
108 textLength : double;
109 italic : TSvgItalicSyle;
110 weight : Integer;
111 align : TSvgTextAlign;
112 decoration : TFontDecoration;
113 baseShift : TValue;
114 end;
115
116 //////////////////////////////////////////////////////////////////////
117 // TClassStylesList: Map that stores CSS selectors with their styles
118 //////////////////////////////////////////////////////////////////////
119
120 PClassStyleListItem = ^TClassStyleListItem;
121 TClassStyleListItem = record //used internally by TClassStylesList
122 Hash : Cardinal;
123 Next : Integer;
124 Name : UTF8String;
125 Style : UTF8String;
126 end;
127
128 TClassStylesList = class
129 private
130 FNameHash: Cardinal;
131 FItems: array of TClassStyleListItem;
132 FBuckets: TArrayOfInteger;
133 FCount: Integer;
134 FMod: Cardinal;
135 procedure Grow(NewCapacity: Integer = -1);
136 function FindItemIndex(const Name: UTF8String): Integer;
137 public
138 procedure Preallocate(AdditionalItemCount: Integer);
139 procedure AddAppendStyle(const Name, Style: UTF8String);
140 function GetStyle(const Name: UTF8String): UTF8String;
141 procedure Clear;
142 end;
143
144 //////////////////////////////////////////////////////////////////////
145 // TSvgParser and associated classes - a simple parser for SVG xml
146 //////////////////////////////////////////////////////////////////////
147
148 PSvgAttrib = ^TSvgAttrib; //element attribute
149 TSvgAttrib = record
150 hash : Cardinal; //hashed name
151 name : UTF8String;
152 value : UTF8String;
153 end;
154
155 TSvgParser = class;
156
157 TXmlEl = class //base element class
158 private
159 {$IFDEF XPLAT_GENERICS}
160 attribs : TList <PSvgAttrib>;
161 {$ELSE}
162 attribs : TList;
163 {$ENDIF}
164 function GetAttrib(index: integer): PSvgAttrib;
165 function GetAttribCount: integer;
166 public
167 {$IFDEF XPLAT_GENERICS}
168 childs : TList<TXmlEl>;
169 {$ELSE}
170 childs : TList;
171 {$ENDIF}
172 name : UTF8String;
173 owner : TSvgParser;
174 hash : Cardinal;
175 text : UTF8String;
176 selfClosed : Boolean;
177 constructor Create(owner: TSvgParser); virtual;
178 destructor Destroy; override;
179 procedure Clear; virtual;
180 function ParseHeader(var c: PUTF8Char; endC: PUTF8Char): Boolean; virtual;
181 function ParseContent(var c: PUTF8Char; endC: PUTF8Char): Boolean; virtual;
182 class function ParseAttribName(c, endC: PUTF8Char; attrib: PSvgAttrib): PUTF8Char; {$IFDEF CLASS_STATIC}static;{$ENDIF}
183 class function ParseAttribValue(c, endC: PUTF8Char; attrib: PSvgAttrib): PUTF8Char; {$IFDEF CLASS_STATIC}static;{$ENDIF}
184 class function ParseAttribNameAndValue(c, endC: PUTF8Char; attrib: PSvgAttrib): PUTF8Char; {$IFDEF CLASS_STATIC}static;{$ENDIF}
185 function ParseAttributes(var c: PUTF8Char; endC: PUTF8Char): Boolean; virtual;
186 procedure ParseStyleAttribute(const style: UTF8String);
187 property Attrib[index: integer]: PSvgAttrib read GetAttrib;
188 property AttribCount: integer read GetAttribCount;
189 end;
190
191 TDocTypeEl = class(TXmlEl)
192 private
193 function SkipWord(c, endC: PUTF8Char): PUTF8Char;
194 function ParseEntities(var c, endC: PUTF8Char): Boolean;
195 public
196 function ParseAttributes(var c: PUTF8Char; endC: PUTF8Char): Boolean; override;
197 end;
198
199 TSvgXmlEl = class(TXmlEl)
200 public
201 constructor Create(owner: TSvgParser); override;
202 procedure Clear; override;
203 function ParseHeader(var c: PUTF8Char; endC: PUTF8Char): Boolean; override;
204 end;
205
206 TSvgParser = class
207 private
208 svgStream : TMemoryStream;
209 procedure ParseUtf8Stream;
210 public
211 classStyles : TClassStylesList;
212 xmlHeader : TXmlEl;
213 docType : TDocTypeEl;
214 svgTree : TSvgXmlEl;
215 constructor Create;
216 destructor Destroy; override;
217 procedure Clear;
218 function FindEntity(hash: Cardinal): PSvgAttrib;
219 function LoadFromFile(const filename: string): Boolean;
220 function LoadFromStream(stream: TStream): Boolean;
221 function LoadFromString(const str: string): Boolean;
222 end;
223
224 //////////////////////////////////////////////////////////////////////
225 // Miscellaneous SVG functions
226 //////////////////////////////////////////////////////////////////////
227
228 //general parsing functions //////////////////////////////////////////
229 function ParseNextWord(var c: PUTF8Char; endC: PUTF8Char;
230 out word: UTF8String): Boolean;
231 function ParseNextWordHash(var c: PUTF8Char; endC: PUTF8Char;
232 out hash: cardinal): Boolean; overload;
233 function ParseNextWordHash(c, endC: PUTF8Char): cardinal; overload;
234 function ParseNextWordExHash(var c: PUTF8Char; endC: PUTF8Char;
235 out hash: cardinal): Boolean;
236 function ParseNextNum(var c: PUTF8Char; endC: PUTF8Char;
237 skipComma: Boolean; out val: double): Boolean;
238 function ParseNextNumEx(var c: PUTF8Char; endC: PUTF8Char; skipComma: Boolean;
239 out val: double; out unitType: TUnitType): Boolean;
240 function GetHash(c: PUTF8Char; len: nativeint): cardinal; overload;
241 function GetHash(const name: UTF8String): cardinal; overload; {$IFDEF INLINE} inline; {$ENDIF}
242 function GetHashCaseSensitive(name: PUTF8Char; nameLen: integer): cardinal;
243 function ExtractRef(const href: UTF8String): UTF8String;
244 function IsNumPending(var c: PUTF8Char;
245 endC: PUTF8Char; ignoreComma: Boolean): Boolean;
246 function UTF8StringToColor32(const value: UTF8String; var color: TColor32): Boolean;
247 function ScaleDashArray(const dblArray: TArrayOfDouble; scale: double): TArrayOfDouble;
248 function Match(c: PUTF8Char; const compare: UTF8String): Boolean; overload;
249 function Match(const compare1, compare2: UTF8String): Boolean; overload;
250 function PosEx(const subStr: utf8String; const text: Utf8String; startIdx: integer = 1): integer;
251 procedure ToUTF8String(c, endC: PUTF8Char; var S: UTF8String;
252 spacesInText: TSpacesInText = sitUndefined);
253 function TrimMultiSpacesUtf8(const text: Utf8String): Utf8String;
254 function TrimMultiSpacesUnicode(const text: UnicodeString): UnicodeString;
255 function ConvertNewlines(const s: UTF8String): UTF8String; overload;
256 function ConvertNewlines(const s: UnicodeString): UnicodeString; overload;
257 function StripNewlines(const s: UTF8String): UTF8String; overload;
258 function StripNewlines(const s: UnicodeString): UnicodeString; overload;
259 procedure ToAsciiLowerUTF8String(c, endC: PUTF8Char; var S: UTF8String);
260 procedure ToTrimmedUTF8String(c, endC: PUTF8Char; var S: UTF8String);
261 function IsSameUTF8String(const S1, S2: UTF8String): Boolean;
262
263 //special parsing functions //////////////////////////////////////////
264 procedure ParseStyleElementContent(const value: UTF8String; stylesList: TClassStylesList);
265 function ParseTransform(const transform: UTF8String): TMatrixD;
266
267 procedure GetSvgFontInfo(const value: UTF8String; var fontInfo: TSVGFontInfo);
268 function HtmlDecode(const html: UTF8String): UTF8String;
269
270 function GetXmlEncoding(memory: Pointer; len: integer): TSvgEncoding;
271 function ClampRange(val, min, max: double): double;
272
273 function SkipBlanks(var c: PUTF8Char; endC: PUTF8Char): Boolean;
274 function SkipBlanksEx(c: PUTF8Char; endC: PUTF8Char): PUTF8Char; {$IFDEF INLINE} inline; {$ENDIF}
275 function SkipBlanksAndComma(c, endC: PUTF8Char): PUTF8Char; {$IFDEF INLINE} inline; {$ENDIF}
276
277 function GetCommaSeparatedArray(const str: UTF8String): UTF8Strings;
278 function TrimQuotes(const str: UTF8String): UTF8String;
279
280 procedure ConvertUnicodeToUtf8(memStream: TMemoryStream);
281
282 function GetScale(src, dst: double): double;
283 function GetScaleForBestFit(srcW, srcH, dstW, dstH: double): double;
284
285 function Base64Decode(const str: PAnsiChar; len: integer; memStream: TMemoryStream): Boolean;
286
287 type
288 TSetOfUTF8Char = set of UTF8Char;
289
290 function CharInSet(chr: UTF8Char; const chrs: TSetOfUTF8Char): Boolean;
291 function DecodeUtf8ToUnicode(const utf8: UTF8String): UnicodeString;
292
293 const
294 clInvalid = $00010001;
295 clCurrent = $00010002;
296 sqrt2 = 1.4142135623731;
297 quote = '''';
298 dquote = '"';
299 space = #32;
300 comma = ',';
301 SvgDecimalSeparator = '.'; //do not localize
302
303 {$I Img32.SVG.HashConsts.inc}
304
305 var
306 LowerCaseTable : array[#0..#$FF] of UTF8Char;
307
308 implementation
309
310 //------------------------------------------------------------------------------
311 // Color Constant HashMap
312 //------------------------------------------------------------------------------
313
314 type
315 PColorConst = ^TColorConst;
316 TColorConst = record
317 ColorName : UTF8String;
318 ColorValue: TColor32;
319 end;
320
321 PPColorConstMapItem = ^PColorConstMapItem;
322 PColorConstMapItem = ^TColorConstMapItem;
323 TColorConstMapItem = record
324 Hash: Cardinal;
325 Next: PColorConstMapItem;
326 Data: PColorConst;
327 end;
328
329 PColorConstMapItemArray = ^TColorConstMapItemArray;
330 TColorConstMapItemArray = array[0..MaxInt div SizeOf(TColorConstMapItem) - 1] of TColorConstMapItem;
331
332 TColorConstList = class(TObject)
333 private
334 FItems: array of TColorConstMapItem;
335 FBuckets: array of PColorConstMapItem;
336 FCount: Integer;
337 FMod: Cardinal;
338 public
339 constructor Create(Colors: PColorConst; Count: Integer);
340 function GetColorValue(const ColorName: UTF8String; var Color: TColor32): Boolean;
341 end;
342
343 var
344 ColorConstList : TColorConstList;
345
346 const
347 buffSize = 8;
348
349 //include hashed html entity constants
350 {$I Img32.SVG.HtmlHashConsts.inc}
351
352 //------------------------------------------------------------------------------
353 // Base64 (MIME) Encode & Decode and other encoding functions ...
354 //------------------------------------------------------------------------------
355
356 type
357 PFourChars = ^TFourChars;
358 TFourChars = record
359 c1: ansichar;
360 c2: ansichar;
361 c3: ansichar;
362 c4: ansichar;
363 end;
364
365 function Chr64ToVal(c: ansiChar): integer; {$IFDEF INLINE} inline; {$ENDIF}
366 begin
367 case c of
368 '+': result := 62;
369 '/': result := 63;
370 '0'..'9': result := ord(c) + 4;
371 'A'..'Z': result := ord(c) -65;
372 'a'..'z': result := ord(c) -71;
373 else Raise Exception.Create('Corrupted MIME encoded text');
374 end;
375 end;
376 //------------------------------------------------------------------------------
377
378 function FrstChr(c: PFourChars): ansichar; {$IFDEF INLINE} inline; {$ENDIF}
379 begin
380 result := ansichar(Chr64ToVal(c.c1) shl 2 or Chr64ToVal(c.c2) shr 4);
381 end;
382 //------------------------------------------------------------------------------
383
384 function ScndChr(c: PFourChars): ansichar; {$IFDEF INLINE} inline; {$ENDIF}
385 begin
386 result := ansichar(Chr64ToVal(c.c2) shl 4 or Chr64ToVal(c.c3) shr 2);
387 end;
388 //------------------------------------------------------------------------------
389
390 function ThrdChr(c: PFourChars): ansichar; {$IFDEF INLINE} inline; {$ENDIF}
391 begin
392 result := ansichar( Chr64ToVal(c.c3) shl 6 or Chr64ToVal(c.c4) );
393 end;
394 //------------------------------------------------------------------------------
395
396 function Base64Decode(const str: PAnsiChar; len: integer; memStream: TMemoryStream): Boolean;
397 var
398 i, j, extra: integer;
399 Chars4: PFourChars;
400 dst: PAnsiChar;
401 begin
402 result := false;
403 if (len = 0) or (len mod 4 > 0) or not Assigned(memStream) then exit;
404 if str[len-2] = '=' then extra := 2
405 else if str[len-1] = '=' then extra := 1
406 else extra := 0;
407 memStream.SetSize(LongInt((len div 4 * 3) - extra));
408 dst := memStream.Memory;
409 Chars4 := @str[0];
410 i := 0;
411 try
412 for j := 1 to (len div 4) -1 do
413 begin
414 dst[i] := FrstChr(Chars4);
415 dst[i+1] := ScndChr(Chars4);
416 dst[i+2] := ThrdChr(Chars4);
417 inc(pbyte(Chars4),4);
418 inc(i,3);
419 end;
420 dst[i] := FrstChr(Chars4);
421 if extra < 2 then dst[i+1] := ScndChr(Chars4);
422 if extra < 1 then dst[i+2] := ThrdChr(Chars4);
423 except
424 Exit;
425 end;
426 Result := true;
427 end;
428
429 //------------------------------------------------------------------------------
430 // Miscellaneous functions ...
431 //------------------------------------------------------------------------------
432
433 function NewSvgAttrib(): PSvgAttrib; {$IFDEF INLINE} inline; {$ENDIF}
434 begin
435 // New(Result) uses RTTI to initialize the UTF8String fields to nil.
436 // By allocating zero'ed memory we can achieve that much faster.
437 Result := AllocMem(SizeOf(TSvgAttrib));
438 end;
439 //------------------------------------------------------------------------------
440
441 procedure DisposeSvgAttrib(attrib: PSvgAttrib); {$IFDEF INLINE} inline; {$ENDIF}
442 begin
443 // Dispose(Result) uses RTTI to set the UTF8String fields to nil.
444 // By clearing them outself we can achieve that much faster.
445 attrib.name := '';
446 attrib.value := '';
447 FreeMem(attrib);
448 end;
449 //------------------------------------------------------------------------------
450
451 function GetScale(src, dst: double): double;
452 begin
453 Result := dst / src;
454 if (SameValue(Result, 1, 0.00001)) then Result := 1;
455 end;
456 //------------------------------------------------------------------------------
457
458 function GetScaleForBestFit(srcW, srcH, dstW, dstH: double): double;
459 var
460 sx,sy: double;
461 begin
462 sx := dstW / srcW;
463 sy := dstH / srcH;
464 if sy < sx then sx := sy;
465 if (SameValue(sx, 1, 0.00001)) then
466 Result := 1 else
467 Result := sx;
468 end;
469 //------------------------------------------------------------------------------
470
471 function ClampRange(val, min, max: double): double;
472 {$IFDEF INLINE} inline; {$ENDIF}
473 begin
474 if val <= min then Result := min
475 else if val >= max then Result := max
476 else Result := val;
477 end;
478 //------------------------------------------------------------------------------
479
480 function IsSameAsciiUTF8String(const S1, S2: UTF8String): Boolean;
481 var
482 Len: Integer;
483 I: Integer;
484 Ch1, Ch2: UTF8Char;
485 begin
486 Len := Length(S1);
487 Result := Len = Length(S2);
488 if Result then
489 begin
490 Result := False;
491 I := 1;
492 while True do
493 begin
494 if I > Len then
495 Break;
496
497 Ch1 := S1[I];
498 Ch2 := S2[I];
499 if Ch1 = Ch2 then
500 begin
501 Inc(I);
502 Continue;
503 end;
504
505 case Ch1 of
506 'A'..'Z', 'a'..'z':
507 ch1 := UTF8Char(Ord(ch1) xor $20); // toggle upper/lower
508 end;
509
510 if Ch1 <> Ch2 then
511 Exit;
512 Inc(I);
513 end;
514 Result := True;
515 end;
516 end;
517 //------------------------------------------------------------------------------
518
519 function IsSameUTF8StringSlow(const S1, S2: UTF8String): Boolean;
520 begin
521 Result := AnsiSameText(string(S1), string(S2));
522 end;
523 //------------------------------------------------------------------------------
524
525 function IsSameUTF8String(const S1, S2: UTF8String): Boolean;
526 var
527 Len: Integer;
528 I: Integer;
529 Ch1, Ch2: UTF8Char;
530 begin
531 Len := Length(S1);
532 Result := Len = Length(S2);
533 if Result then
534 begin
535 Result := False;
536 I := 1;
537 Ch1 := #0;
538 Ch2 := #0;
539 while True do
540 begin
541 if I > Len then
542 Break;
543
544 Ch1 := S1[I];
545 Ch2 := S2[I];
546 if Ch1 = Ch2 then
547 begin
548 Inc(I);
549 Continue;
550 end;
551
552 case Ch1 of
553 'A'..'Z', 'a'..'z':
554 ch1 := UTF8Char(Ord(ch1) xor $20); // toggle upper/lower
555 end;
556
557 if Ch1 <> Ch2 then
558 Break;
559 Inc(I);
560 end;
561 if Ch1 = Ch2 then
562 Result := True
563 else if (Ord(Ch1) or Ord(Ch2)) and $80 <> 0 then // we found non-matching, non-ASCII characters
564 Result := IsSameUTF8StringSlow(S1, S2);
565 end;
566 end;
567 //------------------------------------------------------------------------------
568
569 function CharInSet(chr: UTF8Char; const chrs: TSetOfUTF8Char): Boolean;
570 begin
571 Result := chr in chrs;
572 end;
573 //------------------------------------------------------------------------------
574
575 function Match(c: PUTF8Char; const compare: UTF8String): Boolean;
576 var
577 i: integer;
578 begin
579 Result := false;
580 for i := 1 to Length(compare) do
581 begin
582 if LowerCaseTable[c[i - 1]] <> compare[i] then Exit;
583 end;
584 Result := true;
585 end;
586 //------------------------------------------------------------------------------
587
588 function Match(const compare1, compare2: UTF8String): Boolean;
589 var
590 i, len: integer;
591 c1, c2: PUTF8Char;
592 begin
593 Result := false;
594 len := Length(compare1);
595 if len <> Length(compare2) then Exit;
596 c1 := @compare1[1]; c2 := @compare2[1];
597 for i := 1 to len do
598 begin
599 if LowerCaseTable[c1[i - 1]] <> LowerCaseTable[c2[i - 1]] then Exit;
600 end;
601 Result := true;
602 end;
603 //------------------------------------------------------------------------------
604
605 function Split(const str: UTF8String): UTF8Strings;
606 var
607 i,j,k, spcCnt, len: integer;
608 begin
609 spcCnt := 0;
610 i := 1;
611 len := Length(str);
612 while (len > 0) and (str[len] <= space) do dec(len);
613 while (i <= len) and (str[i] <= space) do inc(i);
614 for j := i + 1 to len do
615 if (str[j] <= space) and (str[j -1] > space) then inc(spcCnt);
616 SetLength(Result, spcCnt +1);
617 for k := 0 to spcCnt do
618 begin
619 j := i;
620 while (j <= len) and (str[j] > space) do inc(j);
621 SetLength(Result[k], j -i);
622 if j > i then
623 Move(str[i], Result[k][1], j -i);
624 while (j <= len) and (str[j] <= space) do inc(j);
625 i := j;
626 end;
627 end;
628 //------------------------------------------------------------------------------
629
630 function TrimQuotes(const str: UTF8String): UTF8String;
631 var
632 i, len: integer;
633 savedQuote: UTF8Char;
634 begin
635 len := Length(str);
636 i := 1;
637 while (i < len) and (str[i] <= space) do inc(i);
638 if (i < len) and (str[i] in [quote, dquote]) then
639 begin
640 savedQuote := str[i];
641 inc(i);
642 while (len > i) and (str[len] <= space) do dec(len);
643 if (len = i) or (str[len] <> savedQuote) then
644 Result := str else // oops!
645 Result := Copy(str, i, len - i);
646 end
647 else
648 Result := str
649 end;
650 //------------------------------------------------------------------------------
651
652 function GetCommaSeparatedArray(const str: UTF8String): UTF8Strings;
653 var
654 i,j,k, cnt, len: integer;
655 begin
656 // precondition: commas CANNOT be embedded
657 len := Length(str);
658 cnt := 1;
659 for i := 1 to len do
660 if (str[i] = comma) then inc(cnt);
661 SetLength(Result, cnt);
662 j := 0;
663 k := 1;
664 for i := 1 to len do
665 begin
666 if (str[i] <> comma) then Continue;
667 Result[j] := TrimQuotes(Copy(str, k, i-k));
668 inc(j);
669 k := i + 1;
670 end;
671 if len >= k then
672 Result[j] := TrimQuotes(Copy(str, k, len-k +1));
673 end;
674 //------------------------------------------------------------------------------
675
676 function GetXmlEncoding(memory: Pointer; len: integer): TSvgEncoding;
677 var
678 p, p1: PUTF8Char;
679 begin
680 Result := eUnknown;
681 if (len < 4) or not Assigned(memory) then Exit;
682 p := PUTF8Char(memory);
683 p1 := (p + 1);
684 case p^ of
685 #$EF: if (p1^ = #$BB) then
686 if ((p +2)^ = #$BF) then
687 Result := eUtf8 else
688 Exit;
689 #$FF: if (p1^ = #$FE) or (p1^ = #0) then
690 Result := eUnicodeLE;
691 #$FE: if (p1^ = #$FF) then
692 Result := eUnicodeBE;
693 end;
694 end;
695 //------------------------------------------------------------------------------
696
697 function SkipBlanks(var c: PUTF8Char; endC: PUTF8Char): Boolean;
698 var
699 cc: PUTF8Char;
700 begin
701 cc := c;
702 if (cc < endC) and (cc^ <= space) then
703 begin
704 inc(cc);
705 while (cc < endC) and (cc^ <= space) do inc(cc);
706 c := cc;
707 end;
708 Result := (cc < endC);
709 end;
710 //------------------------------------------------------------------------------
711
712 function SkipBlanksEx(c: PUTF8Char; endC: PUTF8Char): PUTF8Char;
713 begin
714 while (c < endC) and (c^ <= space) do inc(c);
715 Result := c;
716 end;
717 //------------------------------------------------------------------------------
718
719 function SkipBlanksAndComma(c, endC: PUTF8Char): PUTF8Char;
720 begin
721 Result := SkipBlanksEx(c, endC);
722 if (Result >= endC) or (Result^ <> ',') then Exit;
723 Result := SkipBlanksEx(Result + 1, endC);
724 end;
725 //------------------------------------------------------------------------------
726
727 function SkipStyleBlanks(c, endC: PUTF8Char): PUTF8Char;
728 var
729 inComment: Boolean;
730 ch: UTF8Char;
731 begin
732 //style content may include multi-line comment blocks
733 inComment := false;
734 while (c < endC) do
735 begin
736 ch := c^;
737 if inComment then
738 begin
739 if (ch = '*') and ((c +1)^ = '/') then
740 begin
741 inComment := false;
742 inc(c);
743 end;
744 end
745 else if (ch > space) then
746 begin
747 inComment := (ch = '/') and ((c +1)^ = '*');
748 if not inComment then break;
749 inc(c);
750 end;
751 inc(c);
752 end;
753 Result := c;
754 end;
755 //------------------------------------------------------------------------------
756
757 function IsDigit(c: UTF8Char): Boolean; {$IFDEF INLINE} inline; {$ENDIF}
758 begin
759 case c of
760 '0'..'9': Result := True;
761 else Result := False;
762 end;
763 end;
764 //------------------------------------------------------------------------------
765
766 function IsQuoteChar(c: UTF8Char): Boolean; {$IFDEF INLINE} inline; {$ENDIF}
767 begin
768 Result := (c = quote) or (c = dquote);
769 end;
770 //------------------------------------------------------------------------------
771
772 function IsAlpha(c: UTF8Char): Boolean; {$IFDEF INLINE} inline; {$ENDIF}
773 begin
774 case c of
775 'A'..'Z', 'a'..'z': Result := True;
776 else Result := False;
777 end;
778 end;
779 //------------------------------------------------------------------------------
780
781 function ParseStyleNameLen(c, endC: PUTF8Char): PUTF8Char;
782 var
783 c2: PUTF8Char;
784 begin
785 Result := c;
786 //nb: style names may start with a hyphen
787 c2 := Result;
788 if (c2^ = '-') then inc(c2);
789 if not IsAlpha(c2^) then Exit;
790
791 Result := c2 + 1;
792 while Result < endC do
793 begin
794 case Result^ of
795 '0'..'9', 'A'..'Z', 'a'..'z', '-': inc(Result);
796 else break;
797 end;
798 end;
799 end;
800 //------------------------------------------------------------------------------
801
802 function ParseNextWord(var c: PUTF8Char; endC: PUTF8Char; out word: UTF8String): Boolean;
803 var
804 c2, cc: PUTF8Char;
805 begin
806 cc := SkipBlanksAndComma(c, endC);
807 if cc >= endC then
808 begin
809 c := cc;
810 Result := False;
811 Exit;
812 end;
813
814 c2 := cc;
815 while cc < endC do
816 begin
817 case cc^ of
818 'A'..'Z', 'a'..'z': inc(cc);
819 else break;
820 end;
821 end;
822 c := cc;
823 ToUTF8String(c2, cc, word);
824 Result := True;
825 end;
826 //------------------------------------------------------------------------------
827
828 function ParseNextWordHash(var c: PUTF8Char; endC: PUTF8Char; out hash: cardinal): Boolean;
829 var
830 c2, cc: PUTF8Char;
831 begin
832 cc := SkipBlanksAndComma(c, endC);
833 if cc >= endC then
834 begin
835 c := cc;
836 hash := 0;
837 Result := False;
838 Exit;
839 end;
840
841 c2 := cc;
842 while cc < endC do
843 begin
844 case cc^ of
845 'A'..'Z', 'a'..'z': inc(cc);
846 else break;
847 end;
848 end;
849 c := cc;
850 hash := GetHash(c2, cc - c2);
851 Result := True;
852 end;
853 //------------------------------------------------------------------------------
854
855 function ParseNextWordHash(c, endC: PUTF8Char): cardinal;
856 var
857 c2: PUTF8Char;
858 begin
859 c := SkipBlanksAndComma(c, endC);
860 if c >= endC then
861 begin
862 Result := 0;
863 Exit;
864 end;
865
866 c2 := c;
867 while c < endC do
868 begin
869 case c^ of
870 'A'..'Z', 'a'..'z': inc(c);
871 else break;
872 end;
873 end;
874 Result := GetHash(c2, c - c2);
875 end;
876 //------------------------------------------------------------------------------
877
878 function ParseNextWordExHash(var c: PUTF8Char; endC: PUTF8Char;
879 out hash: cardinal): Boolean;
880 var
881 c2, cc: PUTF8Char;
882 begin
883 cc := SkipBlanksAndComma(c, endC);
884 if cc >= endC then
885 begin
886 c := cc;
887 hash := 0;
888 Result := False;
889 Exit;
890 end;
891
892 if cc^ = quote then
893 begin
894 inc(c);
895 c2 := cc;
896 while (cc < endC) and (cc^ <> quote) do inc(cc);
897 hash := GetHash(c2, cc - c2);
898 inc(cc);
899 end else
900 begin
901 if not IsAlpha(cc^) then
902 begin
903 hash := 0;
904 Result := False;
905 Exit;
906 end;
907 c2 := cc;
908 inc(cc);
909 while cc < endC do
910 case cc^ of
911 'A'..'Z', 'a'..'z', '-', '_': inc(cc);
912 else break;
913 end;
914 hash := GetHash(c2, cc - c2);
915 end;
916 c := cc;
917 Result := True;
918 end;
919 //------------------------------------------------------------------------------
920
921 function ParseNameLength(c: PUTF8Char; endC: PUTF8Char): PUTF8Char;
922 begin
923 inc(c);
924 while c < endC do
925 begin
926 case c^ of
927 '0'..'9', 'A'..'Z', 'a'..'z', '_', ':', '-': inc(c);
928 else break;
929 end;
930 end;
931 Result := c;
932 end;
933 //------------------------------------------------------------------------------
934
935 {$PUSH}{$Q-}{$R-}
936 function GetHash(c: PUTF8Char; len: nativeint): cardinal;
937 var
938 i: integer;
939 begin
940 //https://en.wikipedia.org/wiki/Jenkins_hash_function
941 Result := 0;
942 if c = nil then Exit;
943 for i := 1 to len do
944 begin
945 Result := (Result + Ord(LowerCaseTable[c^]));
946 Result := Result + (Result shl 10);
947 Result := Result xor (Result shr 6);
948 inc(c);
949 end;
950 Result := Result + (Result shl 3);
951 Result := Result xor (Result shr 11);
952 Result := Result + (Result shl 15);
953 end;
954 {$POP}
955 //------------------------------------------------------------------------------
956
957 function GetHash(const name: UTF8String): cardinal;
958 begin
959 // skip function call by directly casting it to Pointer
960 Result := GetHash(PUTF8Char(Pointer(name)), Length(name));
961 end;
962 //------------------------------------------------------------------------------
963
964 {$PUSH}{$Q-}{$R-}
965 function GetHashCaseSensitive(name: PUTF8Char; nameLen: integer): cardinal;
966 var
967 i: integer;
968 begin
969 Result := 0;
970 for i := 1 to nameLen do
971 begin
972 Result := (Result + Ord(name^));
973 Result := Result + (Result shl 10);
974 Result := Result xor (Result shr 6);
975 inc(name);
976 end;
977 Result := Result + (Result shl 3);
978 Result := Result xor (Result shr 11);
979 Result := Result + (Result shl 15);
980 end;
981 {$POP}
982 //------------------------------------------------------------------------------
983
984 function ParseNextWordHashed(var c: PUTF8Char; endC: PUTF8Char): cardinal;
985 var
986 c2: PUTF8Char;
987 len: integer;
988 begin
989 c2 := c;
990 c := ParseNameLength(c2, endC);
991 len := c - c2;
992 if len <= 0 then Result := 0
993 else Result := GetHash(c2, len);
994 end;
995 //------------------------------------------------------------------------------
996
997 function ParseExpDigits(c, endC: PUTF8Char; out val: Integer): PUTF8Char; {$IFDEF INLINE} inline; {$ENDIF}
998 var
999 v32: Cardinal;
1000 Digit: Integer;
1001 begin
1002 Result := c;
1003 v32 := 0;
1004 while Result < endC do
1005 begin
1006 Digit := Integer(Ord(Result^)) - Ord('0');
1007 if Cardinal(Digit) >= 10 then break;
1008 {$IFDEF FPC} // Something Delphi can optimize but FPC can't (yet?)
1009 v32 := (v32 shl 3) + (v32 shl 1) + Cardinal(Digit); // Delphi's code is even better than this
1010 {$ELSE}
1011 v32 := v32 * 10 + Cardinal(Digit);
1012 {$ENDIF FPC}
1013 inc(Result);
1014 end;
1015 val := v32;
1016 end;
1017 //------------------------------------------------------------------------------
1018
1019 function ParseDigitsToDouble(c, endC: PUTF8Char; out val: double): PUTF8Char;
1020 var
1021 v32: Cardinal;
1022 v64: Int64;
1023 Digit: Integer;
1024 blockEndC: PUTF8Char;
1025 begin
1026 // skip leading zeros
1027 while (c < endC) and (c^ = '0') do inc(c);
1028
1029 // Use Int32 first as it is fast for 64bit and 32bit CPUs
1030 Result := c;
1031 v32 := 0;
1032
1033 blockEndC := c + 9; // log10(2^31) = 9.33
1034 if blockEndC > endC then
1035 blockEndC := endC;
1036 while Result < blockEndC do
1037 begin
1038 Digit := Integer(Ord(Result^)) - Ord('0');
1039 if Cardinal(Digit) >= 10 then break;
1040 {$IFDEF FPC} // Something Delphi can optimize but FPC can't (yet?)
1041 v32 := (v32 shl 3) + (v32 shl 1) + Cardinal(Digit);
1042 {$ELSE}
1043 v32 := v32 * 10 + Cardinal(Digit);
1044 {$ENDIF FPC}
1045 inc(Result);
1046 end;
1047
1048 if (Result < endC) and (Result >= blockEndC) then
1049 begin
1050 v64 := v32;
1051
1052 blockEndC := c + 18; // log10(2^63) = 18.96
1053 if blockEndC > endC then
1054 blockEndC := endC;
1055 while Result < blockEndC do
1056 begin
1057 Digit := Integer(Ord(Result^)) - Ord('0');
1058 if Cardinal(Digit) >= 10 then break;
1059 {$IF (SizeOf(Pointer) = 4) or defined(FPC)} // neither Delphi 32bit nor FPC can optimize this
1060 v64 := (v64 shl 3) + (v64 shl 1) + Cardinal(Digit);
1061 {$ELSE}
1062 v64 := v64 * 10 + Cardinal(Digit);
1063 {$IFEND}
1064 inc(Result);
1065 end;
1066
1067 val := v64;
1068 // Use Double for the remaining digits and loose precision (we are beyong 16 digits anyway)
1069 if (Result < endC) and (Result >= blockEndC) then
1070 begin
1071 while Result < endC do
1072 begin
1073 Digit := Integer(Ord(Result^)) - Ord('0');
1074 if Cardinal(Digit) >= 10 then break;
1075 val := val * 10 + Digit;
1076 inc(Result);
1077 end;
1078 end;
1079 end
1080 else
1081 val := v32;
1082 end;
1083 //------------------------------------------------------------------------------
1084
1085 function ParseNextNumEx(var c: PUTF8Char; endC: PUTF8Char; skipComma: Boolean;
1086 out val: double; out unitType: TUnitType): Boolean;
1087 const
1088 Power10: array[0..18] of Double = (
1089 1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8, 1E9,
1090 1E10, 1E11, 1E12, 1E13, 1E14, 1E15, 1E16, 1E17, 1E18
1091 );
1092 Power10Reciprocal: array[0..18] of Double = (
1093 1/1E0, 1/1E1, 1/1E2, 1/1E3, 1/1E4, 1/1E5, 1/1E6, 1/1E7, 1/1E8, 1/1E9,
1094 1/1E10, 1/1E11, 1/1E12, 1/1E13, 1/1E14, 1/1E15, 1/1E16, 1/1E17, 1/1E18
1095 );
1096 var
1097 exp: integer;
1098 isNeg, expIsNeg: Boolean;
1099 start, decStart, cc: PUTF8Char;
1100 decimals: Double;
1101 begin
1102 Result := false;
1103 unitType := utNumber;
1104
1105 cc := c;
1106
1107 //skip white space +/- single comma
1108 if skipComma then
1109 begin
1110 while (cc < endC) and (cc^ <= space) do inc(cc);
1111 if (cc^ = ',') then inc(cc);
1112 end;
1113 while (cc < endC) and (cc^ <= space) do inc(cc);
1114 if (cc = endC) then
1115 begin
1116 c := cc;
1117 Exit;
1118 end;
1119
1120 exp := Invalid; expIsNeg := false;
1121 isNeg := cc^ = '-';
1122 if isNeg then inc(cc);
1123
1124 start := cc;
1125
1126 // Use fast parsing
1127 cc := ParseDigitsToDouble(cc, endC, val);
1128 if cc < endC then
1129 begin
1130 // Decimals
1131 if Ord(cc^) = Ord(SvgDecimalSeparator) then
1132 begin
1133 inc(cc);
1134 decStart := cc;
1135 cc := ParseDigitsToDouble(cc, endC, decimals);
1136 if cc > decStart then
1137 begin
1138 if cc - decStart <= 18 then
1139 val := val + (decimals * Power10Reciprocal[(cc - decStart)])
1140 else
1141 val := val + (decimals * Power(10, -(cc - decStart)))
1142 end;
1143 end;
1144
1145 // Exponent
1146 if (cc < endC) and ((cc^ = 'e') or (cc^ = 'E')) then
1147 begin
1148 case (cc+1)^ of
1149 '-', '0'..'9':
1150 begin
1151 inc(cc);
1152 if cc^ = '-' then
1153 begin
1154 expIsNeg := true;
1155 inc(cc);
1156 end;
1157 cc := ParseExpDigits(cc, endC, exp);
1158 end;
1159 end;
1160 end;
1161 end;
1162 Result := cc > start;
1163 if not Result then
1164 begin
1165 c := cc;
1166 Exit;
1167 end;
1168
1169 if isNeg then val := -val;
1170 if IsValid(exp) then
1171 begin
1172 if exp <= 18 then
1173 begin
1174 if expIsNeg then
1175 val := val * Power10Reciprocal[exp] else
1176 val := val * Power10[exp];
1177 end
1178 else
1179 begin
1180 if expIsNeg then
1181 val := val * Power(10, -exp) else
1182 val := val * Power(10, exp);
1183 end;
1184 end;
1185
1186 //https://oreillymedia.github.io/Using_SVG/guide/units.html
1187 case cc^ of
1188 '%':
1189 begin
1190 inc(cc);
1191 unitType := utPercent;
1192 end;
1193 'c': //convert cm to pixels
1194 if ((cc+1)^ = 'm') then
1195 begin
1196 inc(cc, 2);
1197 unitType := utCm;
1198 end;
1199 'd': //ignore deg
1200 if ((cc+1)^ = 'e') and ((cc+2)^ = 'g') then
1201 begin
1202 inc(cc, 3);
1203 unitType := utDegree;
1204 end;
1205 'e': //convert cm to pixels
1206 if ((cc+1)^ = 'm') then
1207 begin
1208 inc(cc, 2);
1209 unitType := utEm;
1210 end
1211 else if ((cc+1)^ = 'x') then
1212 begin
1213 inc(cc, 2);
1214 unitType := utEx;
1215 end;
1216 'i': //convert inchs to pixels
1217 if ((cc+1)^ = 'n') then
1218 begin
1219 inc(cc, 2);
1220 unitType := utInch;
1221 end;
1222 'm': //convert mm to pixels
1223 if ((cc+1)^ = 'm') then
1224 begin
1225 inc(cc, 2);
1226 unitType := utMm;
1227 end;
1228 'p':
1229 case (cc+1)^ of
1230 'c':
1231 begin
1232 inc(cc, 2);
1233 unitType := utPica;
1234 end;
1235 't':
1236 begin
1237 inc(cc, 2);
1238 unitType := utPt;
1239 end;
1240 'x':
1241 begin
1242 inc(cc, 2);
1243 unitType := utPixel;
1244 end;
1245 end;
1246 'r': //convert radian angles to degrees
1247 if Match(cc, 'rad') then
1248 begin
1249 inc(cc, 3);
1250 unitType := utRadian;
1251 end;
1252 end;
1253 c := cc;
1254 end;
1255 //------------------------------------------------------------------------------
1256
1257 function ParseNextNum(var c: PUTF8Char; endC: PUTF8Char;
1258 skipComma: Boolean; out val: double): Boolean;
1259 var
1260 tmp: TValue;
1261 begin
1262 tmp.Init;
1263 Result := ParseNextNumEx(c, endC, skipComma, tmp.rawVal, tmp.unitType);
1264 val := tmp.GetValue(1, 1);
1265 end;
1266 //------------------------------------------------------------------------------
1267
1268 function ExtractRef(const href: UTF8String): UTF8String; {$IFDEF INLINE} inline; {$ENDIF}
1269 var
1270 c, c2, endC: PUTF8Char;
1271 begin
1272 c := PUTF8Char(href);
1273 endC := c + Length(href);
1274 if Match(c, 'url(') then
1275 begin
1276 inc(c, 4);
1277 dec(endC); // avoid trailing ')'
1278 end;
1279 if c^ = '#' then inc(c);
1280 c2 := c;
1281 while (c < endC) and (c^ <> ')') do inc(c);
1282 ToUTF8String(c2, c, Result);
1283 end;
1284 //------------------------------------------------------------------------------
1285
1286 function ParseNextChar(var c: PUTF8Char; endC: PUTF8Char): UTF8Char;
1287 var
1288 cc: PUTF8Char;
1289 begin
1290 cc := SkipBlanksEx(c, endC);
1291 if cc >= endC then
1292 Result := #0
1293 else
1294 begin
1295 Result := cc^;
1296 c := cc + 1;
1297 end;
1298 end;
1299 //------------------------------------------------------------------------------
1300
1301 procedure ToTrimmedUTF8String(c, endC: PUTF8Char; var S: UTF8String);
1302 var
1303 len: integer;
1304 begin
1305 // trim left
1306 while (c < endC) and (c^ <= space) do Inc(c);
1307 // trim right
1308 while (endC > c) and (endC[-1] <= space) do Dec(endC);
1309
1310 len := endC - c;
1311 SetLength(S, len);
1312 if len = 0 then Exit;
1313 Move(c^, PUTF8Char(S)^, len * SizeOf(UTF8Char));
1314 end;
1315 //------------------------------------------------------------------------------
1316
1317 function PosEx(const subStr: UTF8String; const text: Utf8String; startIdx: integer): integer;
1318 var
1319 i, maxI, len, subStrLen: integer;
1320 begin
1321 len := Length(Text);
1322 subStrLen := Length(subStr);
1323 maxI := len - subStrLen +1;
1324 for i := Max(1, startIdx) to maxI do
1325 begin
1326 if (text[i] <> subStr[1]) or
1327 not CompareMem(@text[i], @subStr[1], subStrLen) then Continue;
1328 Result := i;
1329 Exit;
1330 end;
1331 Result := 0;
1332 end;
1333 //------------------------------------------------------------------------------
1334
1335 function ReversePosEx(utf8: utf8Char;
1336 const text: Utf8String; startIdx: integer): integer; overload;
1337 {$IFDEF INLINE} inline; {$ENDIF}
1338 begin
1339 Result := Max(0, Min(Length(text), startidx));
1340 while (Result > 0) and (text[Result] <> utf8) do Dec(Result);
1341 end;
1342 //------------------------------------------------------------------------------
1343
1344 function TrimMultiSpacesUtf8(const text: Utf8String): Utf8String;
1345 var
1346 i, len: integer;
1347 begin
1348 Result := text;
1349 len := Length(Result);
1350 for i := 1 to len do
1351 if Result[i] < #32 then Result[i] := #32;
1352 i := ReversePosEx(space, Result, len);
1353 while i > 1 do
1354 begin
1355 Dec(i);
1356 while (i > 0) and (Result[i] = space) do
1357 begin
1358 Delete(Result, i, 1);
1359 Dec(i);
1360 end;
1361 i := ReversePosEx(space, Result, i);
1362 end;
1363 end;
1364 //------------------------------------------------------------------------------
1365
1366 function ReversePosEx(c: WideChar;
1367 const text: UnicodeString; startIdx: integer): integer; overload;
1368 {$IFDEF INLINE} inline; {$ENDIF}
1369 begin
1370 Result := Max(0, Min(Length(text), startidx));
1371 while (Result > 0) and (text[Result] <> c) do Dec(Result);
1372 end;
1373 //------------------------------------------------------------------------------
1374
1375 function TrimMultiSpacesUnicode(const text: UnicodeString): UnicodeString;
1376 var
1377 i, len: integer;
1378 begin
1379 Result := text;
1380 len := Length(Result);
1381 for i := 1 to len do
1382 if Result[i] < #32 then Result[i] := #32;
1383 i := ReversePosEx(space, Result, len);
1384 while i > 1 do
1385 begin
1386 Dec(i);
1387 while (i > 0) and (Result[i] = space) do
1388 begin
1389 Delete(Result, i, 1);
1390 Dec(i);
1391 end;
1392 i := ReversePosEx(space, Result, i);
1393 end;
1394 end;
1395 //------------------------------------------------------------------------------
1396
1397 function StripNewlines(const s: UTF8String): UTF8String;
1398 var
1399 i: integer;
1400 begin
1401 Result := s;
1402 i := Length(Result);
1403 while i > 0 do
1404 begin
1405 if Result[i] < space then Delete(Result, i, 1);
1406 Dec(i);
1407 end;
1408 end;
1409 //------------------------------------------------------------------------------
1410
1411 function StripNewlines(const s: UnicodeString): UnicodeString;
1412 var
1413 i: integer;
1414 begin
1415 Result := s;
1416 i := Length(Result);
1417 while i > 0 do
1418 begin
1419 if Result[i] < space then Delete(Result, i, 1);
1420 Dec(i);
1421 end;
1422 end;
1423 //------------------------------------------------------------------------------
1424
1425 function ConvertNewlines(const s: UTF8String): UTF8String; overload;
1426 var
1427 i: integer;
1428 begin
1429 Result := s;
1430 i := Length(Result);
1431 while i > 0 do
1432 begin
1433 if Result[i] < space then
1434 begin
1435 if Result[i] = #10 then
1436 Result[i] := space else
1437 Delete(Result, i, 1);
1438 end;
1439 Dec(i);
1440 end;
1441 end;
1442 //------------------------------------------------------------------------------
1443
1444 function ConvertNewlines(const s: UnicodeString): UnicodeString; overload;
1445 var
1446 i: integer;
1447 begin
1448 Result := s;
1449 i := Length(Result);
1450 while i > 0 do
1451 begin
1452 if Result[i] < space then
1453 begin
1454 if Result[i] = #10 then
1455 Result[i] := space else
1456 Delete(Result, i, 1);
1457 end;
1458 Dec(i);
1459 end;
1460 end;
1461 //------------------------------------------------------------------------------
1462
1463 procedure ToUTF8String(c, endC: PUTF8Char;
1464 var S: UTF8String; spacesInText: TSpacesInText);
1465 var
1466 len: integer;
1467 begin
1468 len := endC - c;
1469 SetLength(S, len);
1470 if len = 0 then Exit;
1471 Move(c^, PUTF8Char(S)^, len * SizeOf(UTF8Char));
1472 if spacesInText <> sitPreserve then
1473 S := TrimMultiSpacesUtf8(S);
1474 S := ConvertNewlines(S);
1475 end;
1476 //------------------------------------------------------------------------------
1477
1478 procedure ToAsciiLowerUTF8String(c, endC: PUTF8Char; var S: UTF8String);
1479 // Reads a UTF8String and converts all upper case 'A'..'Z' to lower case 'a'..'z'
1480 var
1481 len: integer;
1482 p: PUTF8Char;
1483 ch: UTF8Char;
1484 begin
1485 len := endC - c;
1486 SetLength(S, len);
1487 if len = 0 then Exit;
1488
1489 // Use a pointer arithmetic trick to run forward by using a negative index
1490 p := PUTF8Char(S) + len;
1491 len := -len;
1492 while len < 0 do
1493 begin
1494 ch := endC[len];
1495 case ch of
1496 'A'..'Z':
1497 ch := UTF8Char(Byte(ch) or $20);
1498 end;
1499 p[len] := ch;
1500 inc(len);
1501 end;
1502 end;
1503 //------------------------------------------------------------------------------
1504
1505 function IsKnownEntity(owner: TSvgParser;
1506 var c: PUTF8Char; endC: PUTF8Char; out entity: PSvgAttrib): boolean;
1507 var
1508 c2, c3: PUTF8Char;
1509 begin
1510 inc(c); //skip ampersand.
1511 c2 := c; c3 := c;
1512 c3 := ParseNameLength(c3, endC);
1513 entity := owner.FindEntity(GetHash(c2, c3 - c2));
1514 Result := (c3^ = ';') and Assigned(entity);
1515 //nb: increments 'c' only if the entity is found.
1516 if Result then c := c3 +1 else dec(c);
1517 end;
1518 //------------------------------------------------------------------------------
1519
1520 function ParseQuotedString(var c: PUTF8Char; endC: PUTF8Char;
1521 out quotStr: UTF8String): Boolean;
1522 var
1523 quote: UTF8Char;
1524 c2: PUTF8Char;
1525 begin
1526 quote := c^;
1527 inc(c);
1528 c2 := c;
1529 while (c < endC) and (c^ <> quote) do inc(c);
1530 Result := (c < endC);
1531 if not Result then Exit;
1532 ToUTF8String(c2, c, quotStr);
1533 inc(c);
1534 end;
1535 //------------------------------------------------------------------------------
1536
1537 function IsNumPending(var c: PUTF8Char;
1538 endC: PUTF8Char; ignoreComma: Boolean): Boolean;
1539 var
1540 c2: PUTF8Char;
1541 begin
1542 Result := false;
1543
1544 //skip white space +/- single comma
1545 if ignoreComma then
1546 begin
1547 while (c < endC) and (c^ <= space) do inc(c);
1548 if (c^ = ',') then inc(c);
1549 end;
1550 while (c < endC) and (c^ <= ' ') do inc(c);
1551 if (c = endC) then Exit;
1552
1553 c2 := c;
1554 if (c2^ = '-') then inc(c2);
1555 if (c2^ = SvgDecimalSeparator) then inc(c2);
1556 Result := (c2 < endC) and IsDigit(c2^);
1557 end;
1558 //------------------------------------------------------------------------------
1559
1560 function ParseTransform(const transform: UTF8String): TMatrixD;
1561 var
1562 i: integer;
1563 c, endC: PUTF8Char;
1564 c2: UTF8Char;
1565 word: UTF8String;
1566 values: array[0..5] of double;
1567 mat: TMatrixD;
1568 begin
1569 c := PUTF8Char(transform);
1570 endC := c + Length(transform);
1571 Result := IdentityMatrix; //in case of invalid or referenced value
1572
1573 while ParseNextWord(c, endC, word) do
1574 begin
1575 if Length(word) < 5 then Exit;
1576 if ParseNextChar(c, endC) <> '(' then Exit; //syntax check
1577 //reset values variables
1578 for i := 0 to High(values) do values[i] := InvalidD;
1579 //and since every transform function requires at least one value
1580 if not ParseNextNum(c, endC, false, values[0]) then Break;
1581 //now get additional variables
1582 i := 1;
1583 while (i < 6) and IsNumPending(c, endC, true) and
1584 ParseNextNum(c, endC, true, values[i]) do inc(i);
1585 if ParseNextChar(c, endC) <> ')' then Exit; //syntax check
1586
1587 mat := IdentityMatrix;
1588 //scal(e), matr(i)x, tran(s)late, rota(t)e, skew(X), skew(Y)
1589 case LowerCaseTable[word[5]] of
1590 'e' : //scalE
1591 if not IsValid(values[1]) then
1592 MatrixScale(mat, values[0]) else
1593 MatrixScale(mat, values[0], values[1]);
1594 'i' : //matrIx
1595 if IsValid(values[5]) then
1596 begin
1597 mat[0,0] := values[0];
1598 mat[0,1] := values[1];
1599 mat[1,0] := values[2];
1600 mat[1,1] := values[3];
1601 mat[2,0] := values[4];
1602 mat[2,1] := values[5];
1603 end;
1604 's' : //tranSlateX, tranSlateY & tranSlate
1605 if Length(word) =10 then
1606 begin
1607 c2 := LowerCaseTable[word[10]];
1608 if c2 = 'x' then
1609 MatrixTranslate(mat, values[0], 0)
1610 else if c2 = 'y' then
1611 MatrixTranslate(mat, 0, values[0]);
1612 end
1613 else if IsValid(values[1]) then
1614 MatrixTranslate(mat, values[0], values[1])
1615 else
1616 MatrixTranslate(mat, values[0], 0);
1617 't' : //rotaTe
1618 if IsValid(values[2]) then
1619 MatrixRotate(mat, PointD(values[1],values[2]), DegToRad(values[0]))
1620 else
1621 MatrixRotate(mat, NullPointD, DegToRad(values[0]));
1622 'x' : //skewX
1623 begin
1624 MatrixSkew(mat, DegToRad(values[0]), 0);
1625 end;
1626 'y' : //skewY
1627 begin
1628 MatrixSkew(mat, 0, DegToRad(values[0]));
1629 end;
1630 end;
1631 MatrixMultiply2(mat, Result);
1632 end;
1633 end;
1634 //------------------------------------------------------------------------------
1635
1636 procedure GetSvgFontInfo(const value: UTF8String; var fontInfo: TSVGFontInfo);
1637 var
1638 c, endC: PUTF8Char;
1639 hash: Cardinal;
1640 begin
1641 c := PUTF8Char(value);
1642 endC := c + Length(value);
1643 while (c < endC) and SkipBlanks(c, endC) do
1644 begin
1645 if c = ';' then
1646 break
1647 else if IsNumPending(c, endC, true) then
1648 ParseNextNum(c, endC, true, fontInfo.size)
1649 else
1650 begin
1651 hash := ParseNextWordHashed(c, endC);
1652 case hash of
1653 hSans_045_Serif : fontInfo.family := tfSansSerif;
1654 hSerif : fontInfo.family := tfSerif;
1655 hMonospace : fontInfo.family := tfMonospace;
1656 hBold : fontInfo.weight := 600;
1657 hItalic : fontInfo.italic := sfsItalic;
1658 hNormal :
1659 begin
1660 fontInfo.weight := 400;
1661 fontInfo.italic := sfsNone;
1662 end;
1663 hStart : fontInfo.align := staLeft;
1664 hMiddle : fontInfo.align := staCenter;
1665 hEnd : fontInfo.align := staRight;
1666 hline_045_through : fontInfo.decoration := fdStrikeThrough;
1667 hUnderline : fontInfo.decoration := fdUnderline;
1668 end;
1669 end;
1670 end;
1671 end;
1672 //------------------------------------------------------------------------------
1673
1674 function HtmlDecode(const html: UTF8String): UTF8String;
1675 var
1676 val, len: integer;
1677 c,ce,endC: PUTF8Char;
1678 ch: UTF8Char;
1679 begin
1680 len := Length(html);
1681 SetLength(Result, len*3);
1682 c := PUTF8Char(html);
1683 endC := c + len;
1684 ce := c;
1685 len := 1;
1686 while (ce < endC) and (ce^ <> '&') do
1687 inc(ce);
1688
1689 while (ce < endC) do
1690 begin
1691 if ce > c then
1692 begin
1693 Move(c^, Result[len], ce - c);
1694 inc(len, ce - c);
1695 end;
1696 c := ce; inc(ce);
1697 while (ce < endC) and (ce^ <> ';') do inc(ce);
1698 if ce = endC then break;
1699
1700 val := -1; //assume error
1701 if (c +1)^ = '#' then
1702 begin
1703 val := 0;
1704 //decode unicode value
1705 if (c +2)^ = 'x' then
1706 begin
1707 inc(c, 3);
1708 while c < ce do
1709 begin
1710 ch := c^;
1711 case ch of
1712 'a'..'f':
1713 val := val * 16 + Ord(ch) - 87;
1714 'A'..'F':
1715 val := val * 16 + Ord(ch) - 55;
1716 '0'..'9':
1717 val := val * 16 + Ord(ch) - 48;
1718 else
1719 val := -1;
1720 break;
1721 end;
1722 inc(c);
1723 end;
1724 end else
1725 begin
1726 inc(c, 2);
1727 while c < ce do
1728 begin
1729 val := val * 10 + Ord(c^) - 48;
1730 inc(c);
1731 end;
1732 end;
1733 end else
1734 begin
1735 //decode html entity ...
1736 case GetHashCaseSensitive(c, ce - c) of
1737 {$I Img32.SVG.HtmlValues.inc}
1738 end;
1739 end;
1740
1741 //convert unicode value to utf8 chars
1742 //this saves the overhead of multiple UTF8String<-->string conversions.
1743 case val of
1744 0 .. $7F:
1745 begin
1746 result[len] := UTF8Char(val);
1747 inc(len);
1748 end;
1749 $80 .. $7FF:
1750 begin
1751 Result[len] := UTF8Char($C0 or (val shr 6));
1752 Result[len+1] := UTF8Char($80 or (val and $3f));
1753 inc(len, 2);
1754 end;
1755 $800 .. $7FFF:
1756 begin
1757 Result[len] := UTF8Char($E0 or (val shr 12));
1758 Result[len+1] := UTF8Char($80 or ((val shr 6) and $3f));
1759 Result[len+2] := UTF8Char($80 or (val and $3f));
1760 inc(len, 3);
1761 end;
1762 $10000 .. $10FFFF:
1763 begin
1764 Result[len] := UTF8Char($F0 or (val shr 18));
1765 Result[len+1] := UTF8Char($80 or ((val shr 12) and $3f));
1766 Result[len+2] := UTF8Char($80 or ((val shr 6) and $3f));
1767 Result[len+3] := UTF8Char($80 or (val and $3f));
1768 inc(len, 4);
1769 end;
1770 else
1771 begin
1772 //ie: error
1773 Move(c^, Result[len], ce- c +1);
1774 inc(len, ce - c +1);
1775 end;
1776 end;
1777 inc(ce);
1778 c := ce;
1779 while (ce < endC) and (ce^ <> '&') do inc(ce);
1780 end;
1781 if (c < endC) and (ce > c) then
1782 begin
1783 Move(c^, Result[len], (ce - c));
1784 inc(len, ce - c);
1785 end;
1786 setLength(Result, len -1);
1787 end;
1788 //------------------------------------------------------------------------------
1789
1790 function HexByteToInt(h: UTF8Char): Cardinal; {$IFDEF INLINE} inline; {$ENDIF}
1791 begin
1792 case h of
1793 '0'..'9': Result := Ord(h) - Ord('0');
1794 'A'..'F': Result := 10 + Ord(h) - Ord('A');
1795 'a'..'f': Result := 10 + Ord(h) - Ord('a');
1796 else Result := 0;
1797 end;
1798 end;
1799 //------------------------------------------------------------------------------
1800
1801 function IsFraction(val: double): Boolean; {$IFDEF INLINE} inline; {$ENDIF}
1802 begin
1803 Result := (val <> 0) and (Abs(val) < 1);
1804 end;
1805 //------------------------------------------------------------------------------
1806
1807 function UTF8StringToColor32(const value: UTF8String; var color: TColor32): Boolean;
1808 var
1809 i, len : integer;
1810 j : Cardinal;
1811 clr : TColor32;
1812 alpha : Byte;
1813 vals : array[0..3] of double;
1814 mus : array[0..3] of TUnitType;
1815 c, endC : PUTF8Char;
1816 begin
1817 Result := false;
1818 len := Length(value);
1819 if len < 3 then Exit;
1820 c := PUTF8Char(value);
1821
1822 if (color = clInvalid) or (color = clCurrent) or (color = clNone32) then
1823 alpha := 255 else
1824 alpha := GetAlpha(color);
1825
1826 if Match(c, 'rgb') then
1827 begin
1828 endC := c + len;
1829 inc(c, 3);
1830 if (c^ = 'a') then inc(c);
1831 if (ParseNextChar(c, endC) <> '(') or
1832 not ParseNextNumEx(c, endC, false, vals[0], mus[0]) or
1833 not ParseNextNumEx(c, endC, true, vals[1], mus[1]) or
1834 not ParseNextNumEx(c, endC, true, vals[2], mus[2]) then Exit;
1835 for i := 0 to 2 do
1836 if mus[i] = utPercent then
1837 vals[i] := vals[i] * 255 / 100;
1838
1839 if (c < endC) and (c^ <> ')') and ParseNextNumEx(c, endC, true, vals[3], mus[3]) then
1840 alpha := 255 else //stops further alpha adjustment
1841 vals[3] := 255;
1842 if ParseNextChar(c, endC) <> ')' then Exit;
1843 for i := 0 to 3 do if IsFraction(vals[i]) then
1844 vals[i] := vals[i] * 255;
1845 color := ClampByte(Integer(Round(vals[3]))) shl 24 +
1846 ClampByte(Integer(Round(vals[0]))) shl 16 +
1847 ClampByte(Integer(Round(vals[1]))) shl 8 +
1848 ClampByte(Integer(Round(vals[2])));
1849 end
1850 else if (c^ = '#') then //#RRGGBB or #RGB
1851 begin
1852 if (len = 9) then
1853 begin
1854 clr := $0;
1855 alpha := $0;
1856 for i := 1 to 6 do
1857 begin
1858 inc(c);
1859 clr := clr shl 4 + HexByteToInt(c^);
1860 end;
1861 for i := 1 to 2 do
1862 begin
1863 inc(c);
1864 alpha := alpha shl 4 + HexByteToInt(c^);
1865 end;
1866 clr := clr or alpha shl 24;
1867 end
1868 else if (len = 7) then
1869 begin
1870 clr := $0;
1871 for i := 1 to 6 do
1872 begin
1873 inc(c);
1874 clr := clr shl 4 + HexByteToInt(c^);
1875 end;
1876 clr := clr or $FF000000;
1877 end
1878 else if (len = 5) then
1879 begin
1880 clr := $0;
1881 for i := 1 to 3 do
1882 begin
1883 inc(c);
1884 j := HexByteToInt(c^);
1885 clr := clr shl 4 + j;
1886 clr := clr shl 4 + j;
1887 end;
1888 inc(c);
1889 alpha := HexByteToInt(c^);
1890 alpha := alpha + alpha shl 4;
1891 clr := clr or alpha shl 24;
1892 end
1893 else if (len = 4) then
1894 begin
1895 clr := $0;
1896 for i := 1 to 3 do
1897 begin
1898 inc(c);
1899 j := HexByteToInt(c^);
1900 clr := clr shl 4 + j;
1901 clr := clr shl 4 + j;
1902 end;
1903 clr := clr or $FF000000;
1904 end
1905 else
1906 Exit;
1907 color := clr;
1908 end else //color name lookup
1909 begin
1910 if not ColorConstList.GetColorValue(value, color) then
1911 Exit;
1912 end;
1913
1914 //and in case the opacity has been set before the color
1915 if (alpha < 255) then
1916 color := (color and $FFFFFF) or alpha shl 24;
1917 {$IF DEFINED(ANDROID)}
1918 color := SwapRedBlue(color);
1919 {$IFEND}
1920 Result := true;
1921 end;
1922 //------------------------------------------------------------------------------
1923
1924 function ScaleDashArray(const dblArray: TArrayOfDouble; scale: double): TArrayOfDouble;
1925 var
1926 i, len: integer;
1927 begin
1928 len := Length(dblArray);
1929 SetLength(Result, len);
1930 if len = 0 then Exit;
1931
1932 for i := 0 to len -1 do
1933 Result[i] := dblArray[i] * scale;
1934
1935 if Odd(len) then
1936 begin
1937 SetLength(Result, len *2);
1938 Move(Result[0], Result[len], len * SizeOf(double));
1939 end;
1940 end;
1941 //------------------------------------------------------------------------------
1942
1943 function PeekNextChar(var c: PUTF8Char; endC: PUTF8Char): UTF8Char;
1944 begin
1945 if not SkipBlanks(c, endC) then
1946 Result := #0 else
1947 Result := c^;
1948 end;
1949 //------------------------------------------------------------------------------
1950
1951 procedure ParseStyleElementContent(const value: UTF8String;
1952 stylesList: TClassStylesList);
1953 var
1954 len, cap: integer;
1955 names: array of UTF8String;
1956
1957 procedure AddName(const name: UTF8String);
1958 begin
1959 if len = cap then
1960 begin
1961 cap := cap + buffSize;
1962 SetLength(names, cap);
1963 end;
1964 names[len] := name;
1965 inc(len);
1966 end;
1967
1968 var
1969 i: integer;
1970 aclassName: UTF8String;
1971 aStyle: UTF8String;
1972 c, c2, endC: PUTF8Char;
1973 begin
1974 //https://oreillymedia.github.io/Using_SVG/guide/style.html
1975
1976 stylesList.Clear;
1977 if value = '' then Exit;
1978
1979 len := 0; cap := 0;
1980 c := @value[1];
1981 endC := c + Length(value);
1982
1983 c := SkipBlanksEx(c, endC);
1984 if c >= endC then Exit;
1985
1986 if Match(c, '<![cdata[') then inc(c, 9);
1987
1988 while True do
1989 begin
1990 c := SkipStyleBlanks(c, endC);
1991 if c >= endC then Break;
1992
1993 case c^ of
1994 SvgDecimalSeparator, '#', 'A'..'Z', 'a'..'z': ;
1995 else break;
1996 end;
1997
1998 //get one or more class names for each pending style
1999 c2 := c;
2000 c := ParseNameLength(c, endC);
2001 ToAsciiLowerUTF8String(c2, c, aclassName);
2002
2003 AddName(aclassName);
2004
2005 c := SkipStyleBlanks(c, endC);
2006 if (c < endC) and (c^ = ',') then
2007 begin
2008 inc(c);
2009 Continue;
2010 end;
2011 if len = 0 then break;
2012
2013 //now get the style
2014 if (c >= endC) or (c^ <> '{') then Break;
2015 inc(c);
2016 c2 := c;
2017 while (c < endC) and (c^ <> '}') do inc(c);
2018 if (c = endC) then break;
2019 ToTrimmedUTF8String(c2, c, aStyle);
2020 if aStyle <> '' then
2021 begin
2022 stylesList.Preallocate(len);
2023 //finally, for each class name add (or append) this style
2024 for i := 0 to len - 1 do
2025 stylesList.AddAppendStyle(names[i], aStyle);
2026 end;
2027 // Reset the used names array length, so we can reuse it to reduce the amount of SetLength calls
2028 len := 0;
2029 inc(c);
2030 end;
2031 end;
2032
2033 //------------------------------------------------------------------------------
2034 // TXmlEl classes
2035 //------------------------------------------------------------------------------
2036
2037 constructor TXmlEl.Create(owner: TSvgParser);
2038 begin
2039 {$IFDEF XPLAT_GENERICS}
2040 attribs := TList<PSvgAttrib>.Create;
2041 childs := TList<TXmlEl>.Create;
2042 {$ELSE}
2043 attribs := TList.Create;
2044 childs := TList.Create;
2045 {$ENDIF}
2046 selfClosed := true;
2047 Self.owner := owner;
2048 end;
2049 //------------------------------------------------------------------------------
2050
2051 destructor TXmlEl.Destroy;
2052 begin
2053 Clear;
2054 attribs.Free;
2055 childs.Free;
2056 inherited;
2057 end;
2058 //------------------------------------------------------------------------------
2059
2060 procedure TXmlEl.Clear;
2061 var
2062 i: integer;
2063 begin
2064 for i := 0 to attribs.Count -1 do
2065 DisposeSvgAttrib(PSvgAttrib(attribs.List[i]));
2066 attribs.Clear;
2067
2068 for i := 0 to childs.Count -1 do
2069 TXmlEl(childs[i]).free;
2070 childs.Clear;
2071 end;
2072 //------------------------------------------------------------------------------
2073
2074 function TXmlEl.ParseHeader(var c: PUTF8Char; endC: PUTF8Char): Boolean;
2075 var
2076 style: UTF8String;
2077 c2: PUTF8Char;
2078 begin
2079 c2 := SkipBlanksEx(c, endC);
2080 c := ParseNameLength(c2, endC);
2081 ToAsciiLowerUTF8String(c2, c, name);
2082
2083 //load the class's style (ie undotted style) if found.
2084 style := owner.classStyles.GetStyle(name);
2085 if style <> '' then ParseStyleAttribute(style);
2086 Result := ParseAttributes(c, endC);
2087 end;
2088 //------------------------------------------------------------------------------
2089
2090 class function TXmlEl.ParseAttribName(c: PUTF8Char;
2091 endC: PUTF8Char; attrib: PSvgAttrib): PUTF8Char;
2092 begin
2093 Result := SkipBlanksEx(c, endC);
2094 if Result >= endC then Exit;
2095 c := Result;
2096 Result := ParseNameLength(Result, endC);
2097 ToUTF8String(c, Result, attrib.Name);
2098 attrib.hash := GetHash(attrib.Name);
2099 end;
2100 //------------------------------------------------------------------------------
2101
2102 class function TXmlEl.ParseAttribValue(c, endC: PUTF8Char;
2103 attrib: PSvgAttrib): PUTF8Char;
2104 // Parse: [Whitespaces] "=" [Whitespaces] ("'" | "\"") <string> ("'" | "\"")
2105 var
2106 quoteChar: UTF8Char;
2107 c2: PUTF8Char;
2108 begin
2109 Result := endC;
2110
2111 // ParseNextChar:
2112 c := SkipBlanksEx(c, endC);
2113 if (c >= endC) or (c^ <> '=') then Exit;
2114 inc(c); // '=' parsed
2115
2116 // ParseQuoteChar:
2117 c := SkipBlanksEx(c, endC);
2118 if c >= endC then Exit;
2119 quoteChar := c^;
2120 if not (quoteChar in [quote, dquote]) then Exit;
2121 inc(c); // quote parsed
2122
2123 //trim leading and trailing spaces in the actual value
2124 c := SkipBlanksEx(c, endC);
2125 // find value end
2126 Result := c;
2127 while (Result < endC) and (Result^ <> quoteChar) do inc(Result);
2128 c2 := Result;
2129 while (c2 > c) and ((c2 -1)^ <= space) do dec(c2);
2130
2131 ToUTF8String(c, c2, attrib.value, sitPreserve);
2132 inc(Result); //skip end quote
2133 end;
2134 //------------------------------------------------------------------------------
2135
2136 class function TXmlEl.ParseAttribNameAndValue(c, endC: PUTF8Char; attrib: PSvgAttrib): PUTF8Char;
2137 begin
2138 Result := ParseAttribName(c, endC, attrib);
2139 if (Result < endC) then
2140 Result := ParseAttribValue(Result, endC, attrib);
2141 end;
2142 //------------------------------------------------------------------------------
2143
2144 function TXmlEl.ParseAttributes(var c: PUTF8Char; endC: PUTF8Char): Boolean;
2145 var
2146 i: integer;
2147 attrib, styleAttrib, classAttrib, idAttrib: PSvgAttrib;
2148 classes: UTF8Strings;
2149 ansi: UTF8String;
2150 begin
2151 Result := false;
2152 styleAttrib := nil; classAttrib := nil; idAttrib := nil;
2153
2154 while SkipBlanks(c, endC) do
2155 begin
2156 case c^ of
2157 '/', '?':
2158 begin
2159 inc(c);
2160 if (c^ <> '>') then Exit; //error
2161 selfClosed := true;
2162 inc(c);
2163 Result := true;
2164 break;
2165 end;
2166 '>':
2167 begin
2168 inc(c);
2169 Result := true;
2170 break;
2171 end;
2172 'x':
2173 if Match(c, 'xml:') then
2174 begin
2175 inc(c, 4); //ignore xml: prefixes
2176 end;
2177 end;
2178
2179 attrib := NewSvgAttrib();
2180 c := ParseAttribNameAndValue(c, endC, attrib);
2181 if c >= endC then
2182 begin
2183 DisposeSvgAttrib(attrib);
2184 Exit;
2185 end;
2186
2187 attribs.Add(attrib);
2188 case attrib.hash of
2189 hId : idAttrib := attrib;
2190 hClass : classAttrib := attrib;
2191 hStyle : styleAttrib := attrib;
2192 end;
2193 end;
2194
2195 if assigned(classAttrib) then
2196 with classAttrib^ do
2197 begin
2198 //get the 'dotted' classname(s)
2199 classes := Split(value);
2200 for i := 0 to High(classes) do
2201 begin
2202 ansi := SvgDecimalSeparator + classes[i];
2203 //get the style definition
2204 ansi := owner.classStyles.GetStyle(ansi);
2205 if ansi <> '' then ParseStyleAttribute(ansi);
2206 end;
2207 end;
2208
2209 if assigned(styleAttrib) then
2210 ParseStyleAttribute(styleAttrib.value);
2211
2212 if assigned(idAttrib) then
2213 begin
2214 //get the 'hashed' classname
2215 ansi := '#' + idAttrib.value;
2216 //get the style definition
2217 ansi := owner.classStyles.GetStyle(ansi);
2218 if ansi <> '' then ParseStyleAttribute(ansi);
2219 end;
2220
2221 end;
2222 //------------------------------------------------------------------------------
2223
2224 procedure TXmlEl.ParseStyleAttribute(const style: UTF8String);
2225 var
2226 styleName, styleVal: UTF8String;
2227 c, c2, endC: PUTF8Char;
2228 attrib: PSvgAttrib;
2229 begin
2230 //there are 4 ways to load styles (in ascending precedence) -
2231 //1. a class element style (called during element contruction)
2232 //2. a non-element class style (called via a class attribute)
2233 //3. an inline style (called via a style attribute)
2234 //4. an id specific class style
2235
2236 c := PUTF8Char(style);
2237 endC := c + Length(style);
2238 while True do
2239 begin
2240 c := SkipStyleBlanks(c, endC);
2241 if c >= endC then Break;
2242
2243 c2 := c;
2244 c := ParseStyleNameLen(c, endC);
2245 ToUTF8String(c2, c, styleName);
2246 if styleName = '' then Break;
2247
2248 // ParseNextChar
2249 c := SkipStyleBlanks(c, endC);
2250 if (c >= endC) or (c^ <> ':') then Break; //syntax check
2251 inc(c);
2252
2253 c := SkipBlanksEx(c, endC);
2254 if c >= endC then Break;
2255
2256 c2 := c;
2257 inc(c);
2258 while (c < endC) and (c^ <> ';') do inc(c);
2259 ToTrimmedUTF8String(c2, c, styleVal);
2260 inc(c);
2261
2262 attrib := NewSvgAttrib();
2263 attrib.name := styleName;
2264 attrib.value := styleVal;
2265 attrib.hash := GetHash(attrib.name);
2266 attribs.Add(attrib);
2267 end;
2268 end;
2269 //------------------------------------------------------------------------------
2270
2271 function TXmlEl.GetAttribCount: integer;
2272 begin
2273 Result := attribs.Count;
2274 end;
2275 //------------------------------------------------------------------------------
2276
2277 function TXmlEl.GetAttrib(index: integer): PSvgAttrib;
2278 begin
2279 Result := PSvgAttrib(attribs[index]);
2280 end;
2281 //------------------------------------------------------------------------------
2282
2283 function IsTextAreaTbreak(var c: PUTF8Char; endC: PUTF8Char): Boolean;
2284 const
2285 // https://www.w3.org/TR/SVGTiny12/text.html#tbreakElement
2286 tbreak: PUTF8Char = '<tbreak/>';
2287 begin
2288 Result := (c + 9 < endC) and CompareMem(c, tbreak, 9);
2289 if Result then inc(c, 8);
2290 end;
2291 //------------------------------------------------------------------------------
2292
2293 function TXmlEl.ParseContent(var c: PUTF8Char; endC: PUTF8Char): Boolean;
2294 var
2295 child : TSvgXmlEl;
2296 entity : PSvgAttrib;
2297 c2, cc : PUTF8Char;
2298 tmpC, tmpEndC : PUTF8Char;
2299 begin
2300 Result := false;
2301 // note: don't trim spaces at the start of text content.
2302 // Text space trimming will be done later IF and when required.
2303 while (hash = hText) or (hash = hTSpan) or
2304 (hash = hTextArea) or SkipBlanks(c, endC) do
2305 begin
2306 if (c^ = '<') then
2307 begin
2308 inc(c);
2309 case c^ of
2310 '!':
2311 begin
2312 cc := c;
2313 if Match(cc, '!--') then //start comment
2314 begin
2315 inc(cc, 3);
2316 while (cc < endC) and ((cc^ <> '-') or
2317 not Match(cc, '-->')) do inc(cc); //end comment
2318 inc(cc, 3);
2319 end else
2320 begin
2321 //it's very likely <![CDATA[
2322 c2 := cc - 1;
2323 if Match(cc, '![cdata[') then
2324 begin
2325 while (cc < endC) and ((cc^ <> ']') or not Match(cc, ']]>')) do
2326 inc(cc);
2327 ToUTF8String(c2, cc, text);
2328 inc(cc, 3);
2329 if (hash = hStyle) then
2330 ParseStyleElementContent(text, owner.classStyles);
2331 end else
2332 begin
2333 while (cc < endC) and (cc^ <> '<') do inc(cc);
2334 ToUTF8String(c2, cc, text);
2335 end;
2336 end;
2337 c := cc;
2338 end;
2339 '/', '?':
2340 begin
2341 //element closing tag
2342 cc := c;
2343 inc(cc);
2344 if Match(cc, name) then
2345 begin
2346 inc(cc, Length(name));
2347 //very rarely there's a space before '>'
2348 cc := SkipBlanksEx(cc, endC);
2349 Result := cc^ = '>';
2350 inc(cc);
2351 end;
2352 c := cc;
2353 Exit;
2354 end;
2355 else
2356 begin
2357 //starting a new element
2358 child := TSvgXmlEl.Create(owner);
2359 childs.Add(child);
2360 if not child.ParseHeader(c, endC) then break;
2361 if not child.selfClosed then
2362 child.ParseContent(c, endC);
2363 end;
2364 end;
2365 end
2366 else if c^ = '>' then
2367 begin
2368 break; //oops! something's wrong
2369 end
2370 else if (c^ = '&') and IsKnownEntity(owner, c, endC, entity) then
2371 begin
2372 tmpC := PUTF8Char(entity.value);
2373 tmpEndC := tmpC + Length(entity.value);
2374 ParseContent(tmpC, tmpEndC);
2375 end
2376 else if (hash = hTSpan) or (hash = hText) or (hash = hTextPath) then
2377 begin
2378 // assume this is text content, and because text can also be mixed
2379 // with any number of nested <tspan> elements, always put text
2380 // content inside a pseudo 'self closed' <tspan> element
2381 cc := c;
2382 while (cc < endC) and (cc^ <> '<') do inc(cc);
2383 child := TSvgXmlEl.Create(owner);
2384 child.name := 'tspan';
2385 child.hash := GetHash('tspan');
2386 child.selfClosed := true; ////////////////////// :)))
2387 childs.Add(child);
2388 ToUTF8String(c, cc, child.text, sitPreserve);
2389 c := cc;
2390 end
2391 else if (hash = hTextArea) then
2392 begin
2393 // also assume this is text content, but don't create
2394 // pseudo <tspan> elements inside <textarea> elements
2395 cc := c;
2396 while (cc < endC) and
2397 ((cc^ <> '<') or IsTextAreaTbreak(cc, endC)) do inc(cc);
2398 ToUTF8String(c, cc, text, sitPreserve);
2399 c := cc;
2400 end else
2401 begin
2402 cc := c;
2403 while (cc < endC) and (cc^ <> '<') do inc(cc);
2404 ToUTF8String(c, cc, text);
2405 c := cc;
2406 //if <style> element then load styles into owner.classStyles
2407 if (hash = hStyle) then
2408 ParseStyleElementContent(text, owner.classStyles);
2409 end;
2410 end;
2411 end;
2412
2413 //------------------------------------------------------------------------------
2414 // TDocTypeEl
2415 //------------------------------------------------------------------------------
2416
2417 function TDocTypeEl.SkipWord(c, endC: PUTF8Char): PUTF8Char;
2418 begin
2419 while (c < endC) and (c^ > space) do inc(c);
2420 inc(c);
2421 Result := c;
2422 end;
2423 //------------------------------------------------------------------------------
2424
2425 function TDocTypeEl.ParseEntities(var c, endC: PUTF8Char): Boolean;
2426 var
2427 attrib: PSvgAttrib;
2428 begin
2429 attrib := nil;
2430 inc(c); //skip opening '['
2431 while (c < endC) and SkipBlanks(c, endC) do
2432 begin
2433 if (c^ = ']') then break
2434 else if not Match(c, '<!entity') then
2435 begin
2436 while c^ > space do inc(c); //skip word.
2437 Continue;
2438 end;
2439 inc(c, 8);
2440 attrib := NewSvgAttrib();
2441
2442 c := ParseAttribName(c, endC, attrib);
2443 if c >= endC then break;
2444
2445 SkipBlanks(c, endC);
2446 if not IsQuoteChar(c^) then break;
2447 if not ParseQuotedString(c, endC, attrib.value) then break;
2448 attribs.Add(attrib);
2449 attrib := nil;
2450 SkipBlanks(c, endC);
2451 if c^ <> '>' then break;
2452 inc(c); //skip entity's trailing '>'
2453 end;
2454 if Assigned(attrib) then DisposeSvgAttrib(attrib);
2455 Result := (c < endC) and (c^ = ']');
2456 inc(c);
2457 end;
2458 //------------------------------------------------------------------------------
2459
2460 function TDocTypeEl.ParseAttributes(var c: PUTF8Char; endC: PUTF8Char): Boolean;
2461 var
2462 dummy : UTF8String;
2463 begin
2464 while SkipBlanks(c, endC) do
2465 begin
2466 //we're currently only interested in ENTITY declarations
2467 case c^ of
2468 '[': ParseEntities(c, endC);
2469 '"', '''': ParseQuotedString(c, endC, dummy);
2470 '>': break;
2471 else c := SkipWord(c, endC);
2472 end;
2473 end;
2474 Result := (c < endC) and (c^ = '>');
2475 inc(c);
2476 end;
2477
2478 //------------------------------------------------------------------------------
2479 // TSvgTreeEl
2480 //------------------------------------------------------------------------------
2481
2482 constructor TSvgXmlEl.Create(owner: TSvgParser);
2483 begin
2484 inherited Create(owner);
2485 selfClosed := false;
2486 end;
2487 //------------------------------------------------------------------------------
2488
2489 procedure TSvgXmlEl.Clear;
2490 var
2491 i: integer;
2492 begin
2493 for i := 0 to childs.Count -1 do
2494 TSvgXmlEl(childs[i]).free;
2495 childs.Clear;
2496 inherited;
2497 end;
2498 //------------------------------------------------------------------------------
2499
2500 function TSvgXmlEl.ParseHeader(var c: PUTF8Char; endC: PUTF8Char): Boolean;
2501 begin
2502 Result := inherited ParseHeader(c, endC);
2503 if Result then hash := GetHash(name);
2504 end;
2505 //------------------------------------------------------------------------------
2506
2507 //function TSvgTreeEl.ParseContent(var c: PUTF8Char; endC: PUTF8Char): Boolean;
2508
2509 constructor TSvgParser.Create;
2510 begin
2511 classStyles := TClassStylesList.Create;
2512 svgStream := TMemoryStream.Create;
2513 xmlHeader := TXmlEl.Create(Self);
2514 docType := TDocTypeEl.Create(Self);
2515 svgTree := nil;
2516 end;
2517 //------------------------------------------------------------------------------
2518
2519 destructor TSvgParser.Destroy;
2520 begin
2521 Clear;
2522 svgStream.Free;
2523 xmlHeader.Free;
2524 docType.Free;
2525 classStyles.Free;
2526 end;
2527 //------------------------------------------------------------------------------
2528
2529 procedure TSvgParser.Clear;
2530 begin
2531 classStyles.Clear;
2532 svgStream.Clear;
2533 xmlHeader.Clear;
2534 docType.Clear;
2535 FreeAndNil(svgTree);
2536 end;
2537 //------------------------------------------------------------------------------
2538
2539 function TSvgParser.FindEntity(hash: Cardinal): PSvgAttrib;
2540 var
2541 i: integer;
2542 begin
2543 //there are usually so few, that there seems little point sorting etc.
2544 for i := 0 to docType.attribs.Count -1 do
2545 begin
2546 Result := PSvgAttrib(docType.attribs.List[i]);
2547 if Result.hash = hash then Exit;
2548 end;
2549 Result := nil;
2550 end;
2551 //------------------------------------------------------------------------------
2552
2553 function TSvgParser.LoadFromFile(const filename: string): Boolean;
2554 var
2555 fs: TFileStream;
2556 begin
2557 Result := false;
2558 if not FileExists(filename) then Exit;
2559
2560 fs := TFileStream.Create(filename, fmOpenRead or fmShareDenyNone);
2561 try
2562 Result := LoadFromStream(fs);
2563 finally
2564 fs.Free;
2565 end;
2566 end;
2567 //------------------------------------------------------------------------------
2568
2569 procedure ConvertUnicodeToUtf8(memStream: TMemoryStream);
2570 var
2571 i, len: LongInt;
2572 encoding: TSvgEncoding;
2573 s: UnicodeString;
2574 wc: PWord;
2575 utf8: UTF8String;
2576 begin
2577 memStream.Position := 0;
2578 encoding := GetXmlEncoding(memStream.Memory, memStream.Size);
2579 case encoding of
2580 eUnicodeLE, eUnicodeBE: ;
2581 else Exit;
2582 end;
2583 SetLength(s, memStream.Size div 2);
2584 Move(memStream.Memory^, s[1], memStream.Size);
2585 if encoding = eUnicodeBE then
2586 begin
2587 wc := @s[1];
2588 for i := 1 to Length(s) do
2589 begin
2590 wc^ := Swap(wc^);
2591 inc(wc);
2592 end;
2593 end;
2594 utf8 := UTF8Encode(s);
2595 len := Length(utf8);
2596 memStream.SetSize(len);
2597 Move(utf8[1], memStream.Memory^, len);
2598 end;
2599 //------------------------------------------------------------------------------
2600
2601 function TSvgParser.LoadFromStream(stream: TStream): Boolean;
2602 begin
2603 Clear;
2604 Result := true;
2605 try
2606 svgStream.LoadFromStream(stream);
2607 // very few SVG files are unicode encoded, almost all are Utf8
2608 // so it's more efficient to parse them all as Utf8 encoded files
2609 ConvertUnicodeToUtf8(svgStream);
2610 ParseUtf8Stream;
2611 except
2612 Result := false;
2613 end;
2614 end;
2615 //------------------------------------------------------------------------------
2616
2617 function TSvgParser.LoadFromString(const str: string): Boolean;
2618 var
2619 ss: TStringStream;
2620 begin
2621 {$IFDEF UNICODE}
2622 ss := TStringStream.Create(str, TEncoding.UTF8);
2623 {$ELSE}
2624 ss := TStringStream.Create(UTF8Encode(str));
2625 {$ENDIF}
2626 try
2627 Result := LoadFromStream(ss);
2628 finally
2629 ss.Free;
2630 end;
2631 end;
2632 //------------------------------------------------------------------------------
2633
2634 procedure TSvgParser.ParseUtf8Stream;
2635 var
2636 c, endC: PUTF8Char;
2637 begin
2638 c := svgStream.Memory;
2639 endC := c + svgStream.Size;
2640 SkipBlanks(c, endC);
2641 if Match(c, '<?xml') then
2642 begin
2643 inc(c, 2); //todo: accommodate space after '<' eg using sMatchEl function
2644 if not xmlHeader.ParseHeader(c, endC) then Exit;
2645 SkipBlanks(c, endC);
2646 end;
2647 if Match(c, '<!doctype') then
2648 begin
2649 inc(c, 2);
2650 if not docType.ParseHeader(c, endC) then Exit;
2651 end;
2652 while SkipBlanks(c, endC) do
2653 begin
2654 if (c^ = '<') and Match(c, '<svg') then
2655 begin
2656 inc(c);
2657 svgTree := TSvgXmlEl.Create(self);
2658 if svgTree.ParseHeader(c, endC) and
2659 not svgTree.selfClosed then
2660 svgTree.ParseContent(c, endC);
2661 break;
2662 end;
2663 inc(c);
2664 end;
2665 end;
2666
2667 //------------------------------------------------------------------------------
2668 // Miscellaneous functions
2669 //------------------------------------------------------------------------------
2670
2671 function DecodeUtf8ToUnicode(const utf8: UTF8String): UnicodeString;
2672 var
2673 i,j, len: Integer;
2674 c, cp: Cardinal;
2675 codePoints: TArrayOfCardinal;
2676 begin
2677 Result := '';
2678 if utf8 = '' then Exit;
2679 len := Length(utf8);
2680
2681 // first decode utf8String to codepoints
2682 SetLength(codePoints, len);
2683 i := 1;
2684 j := 0;
2685 while i <= len do
2686 begin
2687 c := Ord(utf8[i]);
2688 if c and $80 = 0 then // c < 128
2689 begin
2690 codePoints[j] := c;
2691 inc(i); inc(j);
2692 end
2693 else if c and $E0 = $C0 then
2694 begin
2695 if i = len then break;
2696 codePoints[j] := (c and $1F) shl 6 + (Ord(utf8[i+1]) and $3F);
2697 inc(i, 2); inc(j);
2698 end
2699 else if c and $F0 = $E0 then
2700 begin
2701 if i > len - 2 then break;
2702 codePoints[j] := (c and $F) shl 12 +
2703 ((Ord(utf8[i+1]) and $3F) shl 6) + ((Ord(utf8[i+2]) and $3F));
2704 inc(i, 3); inc(j);
2705 end else
2706 begin
2707 if (i > len - 3) or (c shr 3 <> $1E) then break;
2708 codePoints[j] := (c and $7) shl 18 + ((Ord(utf8[i+1]) and $3F) shl 12) +
2709 ((Ord(utf8[i+2]) and $3F) shl 6) + (Ord(utf8[i+3]) and $3F);
2710 inc(i, 4); inc(j);
2711 end;
2712 end;
2713 len := j; // there are now 'j' valid codepoints
2714 j := 0;
2715
2716 // make room in the result for surrogate paired chars, and
2717 // convert codepoints into the result (a Utf16 string)
2718 SetLength(Result, len *2);
2719 for i := 0 to len -1 do
2720 begin
2721 inc(j);
2722 cp := codePoints[i];
2723 if (cp < $D7FF) or (cp = $E000) or (cp = $FFFF) then
2724 begin
2725 Result[j] := WideChar(cp);
2726 end else if (cp > $FFFF) and (cp < $110000) then
2727 begin
2728 Dec(cp, $10000);
2729 Result[j] := WideChar($D800 + (cp shr 10));
2730 inc(j);
2731 Result[j] := WideChar($DC00 + (cp and $3FF));
2732 end;
2733 end;
2734 SetLength(Result, j);
2735 end;
2736
2737 //------------------------------------------------------------------------------
2738 // TValue
2739 //------------------------------------------------------------------------------
2740
2741 function ConvertValue(const value: TValue; scale: double): double;
2742 const
2743 mm = 96 / 25.4;
2744 cm = 96 / 2.54;
2745 rad = 180 / PI;
2746 pt = 4 / 3;
2747 begin
2748 //https://oreillymedia.github.io/Using_SVG/guide/units.html
2749 //todo: still lots of units to support (eg times for animation)
2750 with value do
2751 {if not IsValid or (rawVal = 0) then // already checked by TValue.GetValue, the only function calling this code
2752 Result := 0
2753 else}
2754 case value.unitType of
2755 utNumber:
2756 Result := rawVal;
2757 utPercent:
2758 Result := rawVal * 0.01 * scale;
2759 utRadian:
2760 Result := rawVal * rad;
2761 utInch:
2762 Result := rawVal * 96;
2763 utCm:
2764 Result := rawVal * cm;
2765 utMm:
2766 Result := rawVal * mm;
2767 utEm:
2768 if scale <= 0 then
2769 Result := rawVal * 16 else
2770 Result := rawVal * scale;
2771 utEx:
2772 if scale <= 0 then
2773 Result := rawVal * 8 else
2774 Result := rawVal * scale * 0.5;
2775 utPica:
2776 Result := rawVal * 16;
2777 utPt:
2778 Result := rawVal * pt;
2779 else
2780 Result := rawVal;
2781 end;
2782 end;
2783 //------------------------------------------------------------------------------
2784
2785 procedure TValue.Init;
2786 begin
2787 rawVal := InvalidD;
2788 unitType := utNumber;
2789 end;
2790 //------------------------------------------------------------------------------
2791
2792 procedure TValue.SetValue(val: double; unitTyp: TUnitType);
2793 begin
2794 rawVal := val;
2795 unitType := unitTyp;
2796 end;
2797 //------------------------------------------------------------------------------
2798
2799 function TValue.GetValue(relSize: double; assumeRelValBelow: Double): double;
2800 begin
2801 if not IsValid or (rawVal = 0) then
2802 Result := 0
2803 else if IsRelativeValue(assumeRelValBelow) then
2804 Result := rawVal * relSize
2805 else
2806 Result := ConvertValue(self, relSize);
2807 end;
2808 //------------------------------------------------------------------------------
2809
2810 function TValue.GetValueXY(const relSize: TRectD; assumeRelValBelow: Double): double;
2811 begin
2812 //https://www.w3.org/TR/SVG11/coords.html#Units
2813 Result := GetValue(Hypot(relSize.Width, relSize.Height)/sqrt2, assumeRelValBelow);
2814 end;
2815 //------------------------------------------------------------------------------
2816
2817 function TValue.IsRelativeValue(assumeRelValBelow: double): Boolean;
2818 begin
2819 Result := (unitType = utNumber) and (Abs(rawVal) <= assumeRelValBelow);
2820 end;
2821 //------------------------------------------------------------------------------
2822
2823 function TValue.IsValid: Boolean;
2824 begin
2825 Result := (unitType <> utUnknown) and Img32.Vector.IsValid(rawVal);
2826 end;
2827 //------------------------------------------------------------------------------
2828
2829 function TValue.HasFontUnits: Boolean;
2830 begin
2831 case unitType of
2832 utEm, utEx: Result := true;
2833 else Result := False;
2834 end;
2835 end;
2836
2837 //------------------------------------------------------------------------------
2838
2839 function TValue.HasAngleUnits: Boolean;
2840 begin
2841 case unitType of
2842 utDegree, utRadian: Result := true;
2843 else Result := False;
2844 end;
2845 end;
2846
2847 //------------------------------------------------------------------------------
2848 // TValuePt
2849 //------------------------------------------------------------------------------
2850
2851 procedure TValuePt.Init;
2852 begin
2853 X.Init;
2854 Y.Init;
2855 end;
2856 //------------------------------------------------------------------------------
2857
2858 function TValuePt.GetPoint(const relSize: double; assumeRelValBelow: Double): TPointD;
2859 begin
2860 Result.X := X.GetValue(relSize, assumeRelValBelow);
2861 Result.Y := Y.GetValue(relSize, assumeRelValBelow);
2862 end;
2863 //------------------------------------------------------------------------------
2864
2865 function TValuePt.GetPoint(const relSize: TRectD; assumeRelValBelow: Double): TPointD;
2866 begin
2867 Result.X := X.GetValue(relSize.Width, assumeRelValBelow);
2868 Result.Y := Y.GetValue(relSize.Height, assumeRelValBelow);
2869 end;
2870 //------------------------------------------------------------------------------
2871
2872 function TValuePt.IsValid: Boolean;
2873 begin
2874 Result := X.IsValid and Y.IsValid;
2875 end;
2876
2877 //------------------------------------------------------------------------------
2878 // TValueRec
2879 //------------------------------------------------------------------------------
2880
2881 procedure TValueRecWH.Init;
2882 begin
2883 left.Init;
2884 top.Init;
2885 width.Init;
2886 height.Init;
2887 end;
2888 //------------------------------------------------------------------------------
2889
2890 function TValueRecWH.GetRectD(const relSize: TRectD; assumeRelValBelow: Double): TRectD;
2891 begin
2892 with GetRectWH(relSize, assumeRelValBelow) do
2893 begin
2894 Result.Left :=Left;
2895 Result.Top := Top;
2896 Result.Right := Left + Width;
2897 Result.Bottom := Top + Height;
2898 end;
2899 end;
2900 //------------------------------------------------------------------------------
2901
2902 function TValueRecWH.GetRectD(relSize: double; assumeRelValBelow: Double): TRectD;
2903 begin
2904 if not left.IsValid then
2905 Result.Left := 0 else
2906 Result.Left := left.GetValue(relSize, assumeRelValBelow);
2907
2908 if not top.IsValid then
2909 Result.Top := 0 else
2910 Result.Top := top.GetValue(relSize, assumeRelValBelow);
2911
2912 Result.Right := Result.Left + width.GetValue(relSize, assumeRelValBelow);
2913 Result.Bottom := Result.Top + height.GetValue(relSize, assumeRelValBelow);
2914 end;
2915 //------------------------------------------------------------------------------
2916
2917 function TValueRecWH.GetRectD(relSizeX, relSizeY: double; assumeRelValBelow: Double): TRectD;
2918 begin
2919 if not left.IsValid then
2920 Result.Left := 0 else
2921 Result.Left := left.GetValue(relSizeX, assumeRelValBelow);
2922
2923 if not top.IsValid then
2924 Result.Top := 0 else
2925 Result.Top := top.GetValue(relSizeY, assumeRelValBelow);
2926
2927 Result.Right := Result.Left + width.GetValue(relSizeX, assumeRelValBelow);
2928 Result.Bottom := Result.Top + height.GetValue(relSizeY, assumeRelValBelow);
2929 end;
2930 //------------------------------------------------------------------------------
2931
2932 function TValueRecWH.GetRectWH(const relSize: TRectD; assumeRelValBelow: Double): TRectWH;
2933 begin
2934 if not left.IsValid then
2935 Result.Left := 0 else
2936 Result.Left := left.GetValue(relSize.Width, assumeRelValBelow);
2937
2938 if not top.IsValid then
2939 Result.Top := 0 else
2940 Result.Top := top.GetValue(relSize.Height, assumeRelValBelow);
2941
2942 Result.Width := width.GetValue(relSize.Width, assumeRelValBelow);
2943 Result.Height := height.GetValue(relSize.Height, assumeRelValBelow);
2944 end;
2945 //------------------------------------------------------------------------------
2946
2947 function TValueRecWH.IsValid: Boolean;
2948 begin
2949 Result := width.IsValid and height.IsValid;
2950 end;
2951 //------------------------------------------------------------------------------
2952
2953 function TValueRecWH.IsEmpty: Boolean;
2954 begin
2955 Result := (width.rawVal <= 0) or (height.rawVal <= 0);
2956 end;
2957
2958 //------------------------------------------------------------------------------
2959 // TClassStylesList
2960 //------------------------------------------------------------------------------
2961
2962 procedure TClassStylesList.Grow(NewCapacity: Integer);
2963 var
2964 Len, I: Integer;
2965 Index: Integer;
2966 begin
2967 Len := Length(FItems);
2968 if NewCapacity < 0 then
2969 begin
2970 if Len < 5 then
2971 Len := 5
2972 else
2973 Len := Len * 2;
2974 end
2975 else if NewCapacity <= Len then
2976 Exit
2977 else
2978 Len := NewCapacity;
2979
2980 SetLength(FItems, Len);
2981 FMod := Cardinal(Len);
2982 if not Odd(FMod) then
2983 Inc(FMod);
2984 SetLengthUninit(FBuckets, FMod);
2985 FillChar(FBuckets[0], FMod * SizeOf(FBuckets[0]), $FF);
2986
2987 // Rehash
2988 for I := 0 to FCount - 1 do
2989 begin
2990 Index := (FItems[I].Hash and $7FFFFFFF) mod FMod;
2991 FItems[I].Next := FBuckets[Index];
2992 FBuckets[Index] := I;
2993 end;
2994 end;
2995 //------------------------------------------------------------------------------
2996
2997 procedure TClassStylesList.Preallocate(AdditionalItemCount: Integer);
2998 begin
2999 if AdditionalItemCount > 2 then
3000 Grow(Length(FItems) + AdditionalItemCount);
3001 end;
3002 //------------------------------------------------------------------------------
3003
3004 function TClassStylesList.FindItemIndex(const Name: UTF8String): Integer;
3005 begin
3006 Result := -1;
3007 FNameHash := GetHash(Name);
3008 if FMod <> 0 then
3009 begin
3010 Result := FBuckets[(FNameHash and $7FFFFFFF) mod FMod];
3011 while (Result <> -1) and
3012 ((FItems[Result].Hash <> FNameHash) or
3013 not IsSameUTF8String(FItems[Result].Name, Name)) do
3014 Result := FItems[Result].Next;
3015 end;
3016 end;
3017
3018 //------------------------------------------------------------------------------
3019
3020 procedure TClassStylesList.AddAppendStyle(const Name, Style: UTF8String);
3021 var
3022 Index: Integer;
3023 Item: PClassStyleListItem;
3024 Bucket: PInteger;
3025 begin
3026 Index := FindItemIndex(Name);
3027 if Index <> -1 then
3028 begin
3029 Item := @FItems[Index];
3030 if (Item.Style <> '') and (Item.Style[Length(Item.Style)] <> ';') then
3031 Item.Style := Item.Style + ';' + Style
3032 else
3033 Item.Style := Item.Style + Style;
3034 end
3035 else
3036 begin
3037 if FCount = Length(FItems) then
3038 Grow;
3039 Index := FCount;
3040 Inc(FCount);
3041
3042 Bucket := @FBuckets[(FNameHash and $7FFFFFFF) mod FMod];
3043 Item := @FItems[Index];
3044 Item.Next := Bucket^;
3045 Item.Hash := FNameHash;
3046 Item.Name := Name;
3047 Item.Style := style;
3048 Bucket^ := Index;
3049 end;
3050 end;
3051 //------------------------------------------------------------------------------
3052
3053 function TClassStylesList.GetStyle(const Name: UTF8String): UTF8String;
3054 var
3055 Index: Integer;
3056 begin
3057 if FCount = 0 then
3058 Result := ''
3059 else
3060 begin
3061 Index := FindItemIndex(Name);
3062 if Index <> -1 then
3063 Result := FItems[Index].Style
3064 else
3065 Result := '';
3066 end;
3067 end;
3068 //------------------------------------------------------------------------------
3069
3070 procedure TClassStylesList.Clear;
3071 begin
3072 FCount := 0;
3073 FMod := 0;
3074 FItems := nil;
3075 FBuckets := nil;
3076 end;
3077
3078 //------------------------------------------------------------------------------
3079 // TColorConstList
3080 //------------------------------------------------------------------------------
3081
3082 constructor TColorConstList.Create(Colors: PColorConst; Count: Integer);
3083 var
3084 I: Integer;
3085 Bucket: PPColorConstMapItem;
3086 Item: PColorConstMapItem;
3087 begin
3088 inherited Create;
3089 FCount := Count;
3090 SetLength(FItems, FCount);
3091
3092 FMod := FCount * 2 + 1; // gives us 3 color constants as max. bucket depth
3093 SetLength(FBuckets, FMod);
3094
3095 // Initialize FItems[] and fill the buckets
3096 for I := 0 to Count - 1 do
3097 begin
3098 Item := @FItems[I];
3099 Item.Data := Colors; // link the constant to the ColorConstMapItem
3100 Inc(Colors);
3101 Item.Hash := GetHash(Item.Data.ColorName); // case-insensitive
3102 Bucket := @FBuckets[(Cardinal(Item.Hash) and $7FFFFFFF) mod FMod];
3103 Item.Next := Bucket^;
3104 Bucket^ := Item;
3105 end;
3106 end;
3107 //------------------------------------------------------------------------------
3108
3109 function TColorConstList.GetColorValue(const ColorName: UTF8String; var Color: TColor32): Boolean;
3110 var
3111 Hash: Cardinal;
3112 Item: PColorConstMapItem;
3113 begin
3114 Hash := GetHash(ColorName);
3115 Item := FBuckets[(Cardinal(Hash) and $7FFFFFFF) mod FMod];
3116 while (Item <> nil) and
3117 not IsSameAsciiUTF8String(Item.Data.ColorName, ColorName) do
3118 Item := Item.Next;
3119 if Item <> nil then
3120 begin
3121 Color := Item.Data.ColorValue;
3122 Result := True;
3123 end
3124 else
3125 Result := False;
3126 end;
3127
3128 //------------------------------------------------------------------------------
3129 // initialization procedures
3130 //------------------------------------------------------------------------------
3131
3132 procedure MakeLowerCaseTable;
3133 var
3134 i: UTF8Char;
3135 begin
3136 for i:= #0 to #$40 do LowerCaseTable[i]:= i;
3137 for i:= #$41 to #$5A do LowerCaseTable[i]:= UTF8Char(Ord(i) + $20);
3138 for i:= #$5B to #$FF do LowerCaseTable[i]:= i;
3139 end;
3140 //------------------------------------------------------------------------------
3141
3142 procedure MakeColorConstList;
3143 {$I Img32.SVG.HtmlColorConsts.inc}
3144 begin
3145 ColorConstList := TColorConstList.Create(@ColorConsts, Length(ColorConsts));
3146 end;
3147 //------------------------------------------------------------------------------
3148
3149 procedure CleanupColorConstList;
3150 begin
3151 FreeAndNil(ColorConstList);
3152 end;
3153
3154 //------------------------------------------------------------------------------
3155 //------------------------------------------------------------------------------
3156
3157 initialization
3158 MakeLowerCaseTable;
3159 MakeColorConstList;
3160
3161 finalization
3162 CleanupColorConstList;
3163 end.