Debian Codegraph @

src/files/castleinternaldatauri.pas

raw
1 {
2 Copyright 2010-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15 { Reading data URI scheme (TDataURI). }
16 unit CastleInternalDataUri;
17
18 {$I castleconf.inc}
19
20 interface
21
22 uses SysUtils, Classes;
23
24 type
25 { Reading data URI scheme, see http://en.wikipedia.org/wiki/Data_URI_scheme.
26 Such URI specifies the MIME type and contains the data, encoded
27 in plain text or base64. That is, the data is not merely referenced / linked
28 (like with a usual URL), it's simply fully encoded inside the URI.
29 Since such URI can be used anywhere a normal URI is expected,
30 it allows you to inline any kind of data inside any container file.
31 For example, you can place images (textures) and such directly
32 inside a VRML/X3D file. }
33 TDataURI = class
34 private
35 StreamBegin: Cardinal;
36 FStream: TStream;
37 FURI: string;
38 FMimeType: string;
39 FBase64: boolean;
40 FCharset: string;
41 FValid: boolean;
42 FURIPrefix: string;
43 FForceMemoryStream: boolean;
44 procedure FreeStream;
45 procedure SetURI(const Value: String);
46 public
47 destructor Destroy; override;
48 class function IsDataURI(const URI: string; out Colon: Integer): boolean; overload;
49 class function IsDataURI(const URI: string): boolean; overload;
50
51 { Force @link(Stream) and @link(ExtractStream) to return a TMemoryStream,
52 that is always seekable and fully buffered in memory.
53 Without this, they may return TBase64DecodingStream that may not be seekable. }
54 property ForceMemoryStream: boolean
55 read FForceMemoryStream write FForceMemoryStream;
56
57 { The data URI that this class reads.
58
59 When you set this, we read the beginning of URI.
60 If this is a valid data URI, then we set @link(Valid) to @true,
61 update MimeType, Base64, Charset, URIPrefix accordingly, and you can call
62 @link(Stream) if you want to read actual contents.
63
64 If this is not a valid data URI, then we set @link(Valid) to @false,
65 make appropriate warning through WritelnWarning,
66 and reset MimeType, Base64, Charset, URIPrefix to some default values. }
67 property URI: string read FURI write SetURI;
68 property Valid: boolean read FValid;
69 property MimeType: string read FMimeType;
70 property Base64: boolean read FBase64;
71 property Charset: string read FCharset;
72 { URI without the data, nice to show to user. }
73 property URIPrefix: string read FURIPrefix;
74
75 { Read the actual data contents. If the @link(URI) is not valid
76 (includes the initial state when it's not set) then returns @nil.
77
78 The important property of this reader is that no expensive
79 encoding is done until you call this method. In particular,
80 you can set URI, check MimeType, and if you see that MimeType
81 is something not interesting for you (for example, maybe you require
82 some image type) just don't call this method. Then nothing
83 expensive will happen, e.g. data will not be base64-decoded without
84 a need. }
85 function Stream: TStream;
86
87 { Get @link(Stream) and clear it.
88 Makes the stream no longer owner by this TDataURI instance.
89
90 Do not call @link(Stream) after calling @link(ExtractStream).
91 Results are undefined.
92 (Right now, another decoding stream will then be created,
93 that will return the same thing as previous stream.
94 But do not depend on it.) }
95 function ExtractStream: TStream;
96 end;
97
98 { Return data URI String that corresponds to given Stream contents.
99 When loading, we rewind stream positon 0 zero,
100 and read the whole stream.) }
101 function StreamToDataUri(const AStream: TStream; const MimeType: String): String;
102
103 implementation
104
105 uses Base64,
106 CastleUriUtils, CastleStringUtils, CastleClassUtils, CastleLog;
107
108 { TODO: We treat non-base64 data verbatim, not interpreting %xx hex encoding
109 inside. }
110
111 procedure TDataURI.FreeStream;
112 begin
113 FreeAndNil(FStream);
114 end;
115
116 destructor TDataURI.Destroy;
117 begin
118 FreeStream;
119 inherited;
120 end;
121
122 class function TDataURI.IsDataURI(const URI: string; out Colon: Integer): boolean;
123 begin
124 Result := URIProtocolIs(URI, 'data', Colon);
125 end;
126
127 class function TDataURI.IsDataURI(const URI: string): boolean;
128 var
129 Colon: Integer; { ignored }
130 begin
131 Result := URIProtocolIs(URI, 'data', Colon);
132 end;
133
134 procedure TDataURI.SetURI(const Value: String);
135 var
136 ValidMimeType, ValidCharset: string;
137 ValidBase64: boolean;
138 PosBegin, PosNow, Colon: Integer;
139 Part: string;
140 begin
141 FreeStream;
142
143 FURI := Value;
144
145 { default values }
146 FValid := false;
147 FMimeType := 'text/plain'; { default mime-type when not specified }
148 FBase64 := false; { default encoding is not base64 }
149 FCharset := 'US-ASCII'; { default charset }
150 FURIPrefix := '';
151
152 if not IsDataURI(URI, Colon) then
153 begin
154 WritelnWarning('Data URI', 'Not a data URI scheme');
155 Exit;
156 end;
157
158 ValidMimeType := FMimeType;
159 ValidCharset := FCharset;
160 ValidBase64 := FBase64;
161
162 { First Colon characters were already parsed by URIProtocolIs as "data:".
163 Read mime-type now. }
164
165 PosBegin := Colon + 1;
166 PosNow := PosBegin;
167 while (PosNow <= Length(Value)) and
168 (Value[PosNow] <> ';') and
169 (Value[PosNow] <> ',') and
170 (Value[PosNow] <> ' ') do
171 Inc(PosNow);
172
173 if PosBegin < PosNow then
174 ValidMimeType := CopyPos(Value, PosBegin, PosNow - 1);
175
176 repeat
177 { Now, we either stand on ";" (then read charset or base64 tag)
178 or we stand on "," or " " (then read data and exit)
179 or we have end of string (then error).
180
181 Note that terminating with space is invalid, unfortunately
182 http://www.web3d.org/x3d/content/examples/Basic/Shaders/_pages/page01.html
183 uses it. }
184
185 if PosNow > Length(Value) then
186 begin
187 WritelnWarning('Data URI', 'Unexpected end (expected ",")');
188 Exit;
189 end else
190 if Value[PosNow] = ';' then
191 begin
192 PosBegin := PosNow + 1;
193 PosNow := PosBegin;
194 while (PosNow <= Length(Value)) and
195 (Value[PosNow] <> ';') and
196 (Value[PosNow] <> ',') and
197 (Value[PosNow] <> ' ') do
198 Inc(PosNow);
199
200 Part := CopyPos(Value, PosBegin, PosNow - 1);
201 if Part = 'base64' then
202 ValidBase64 := true else
203 if IsPrefix('charset=', Part) then
204 ValidCharset := SEnding(Part, Length('charset=') + 1) else
205 WritelnWarning('Data URI', Format('Invalid part "%s" (expected "base64" or "charset=...")', [Part]));
206 end else
207 if CharInSet(Value[PosNow], [',', ' ']) then
208 begin
209 if Value[PosNow] = ' ' then
210 WritelnWarning('Data URI', 'Header terminated by space, which is invalid (you should terminate with a comma)');
211 Break;
212 end;
213 until false;
214
215 FURIPrefix := Copy(Value, 1, PosNow - 1);
216
217 FValid := true;
218 FMimeType := ValidMimeType;
219 FBase64 := ValidBase64;
220 FCharset := ValidCharset;
221
222 StreamBegin := PosNow + 1;
223 end;
224
225 function TDataURI.Stream: TStream;
226 var
227 MemStream: TMemoryStream;
228 Contents: string;
229 DecodingStream: TBase64DecodingStream;
230 begin
231 if Valid then
232 begin
233 if FStream = nil then
234 begin
235 Contents := SEnding(URI, StreamBegin);
236
237 if Base64 then
238 begin
239 { Note: loads a 16-bit String into TMemoryStream on Delphi.
240 This is what TNetEncoding.Base64.Decode expects. }
241 MemStream := MemoryStreamLoadFromDefaultString(Contents);
242
243 DecodingStream := TBase64DecodingStream.Create(MemStream, bdmMIME);
244 DecodingStream.SourceOwner := true;
245 if ForceMemoryStream then
246 begin
247 FStream := TMemoryStream.Create;
248 ReadGrowingStream(DecodingStream, FStream, true);
249 FreeAndNil(DecodingStream);
250 end else
251 FStream := DecodingStream;
252 end else
253 begin
254 { In case of Delphi, using MemoryStreamLoadFromString below
255 converts now this 16-bit String into a 8-bit String.
256 This is necessary, as FileToString and ReadGrowingStreamToString
257 then treat the contents of stream as 8-bit String.
258 It may be converted back to 16-bit String later, when
259 e.g. ShaderLoadContents loads a data URI that is a shader source.
260
261 See https://github.com/castle-engine/castle-engine/issues/541
262 and TTestX3DNodes.TestInlineShaderCode autotest. }
263 MemStream := MemoryStreamLoadFromString(Contents);
264 FStream := MemStream;
265 end;
266 end;
267 Result := FStream;
268 end else
269 Result := nil;
270 end;
271
272 function TDataURI.ExtractStream: TStream;
273 begin
274 Result := Stream;
275 FStream := nil;
276 end;
277
278 { routines ------------------------------------------------------------------ }
279
280 function StreamToDataUri(const AStream: TStream; const MimeType: String): String;
281 var
282 Base64Encode: TBase64EncodingStream;
283 ResultStr: TStringStream;
284 begin
285 ResultStr := TStringStream.Create;
286 try
287 WriteStr(ResultStr, 'data:' + MimeType + ';base64,');
288 Base64Encode := TBase64EncodingStream.Create(ResultStr);
289 try
290 Base64Encode.CopyFrom(AStream, 0);
291 finally FreeAndNil(Base64Encode) end;
292 Result := ResultStr.DataString;
293 finally FreeAndNil(ResultStr) end;
294 end;
295
296 end.