-
Notifications
You must be signed in to change notification settings - Fork 24
/
Cromis.PageProducer.pas
625 lines (542 loc) · 19.2 KB
/
Cromis.PageProducer.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
{
==================================================================================
Cromis.PageProducer.pas
----------------------------
Copyright © 2008-2010 Kacin Iztok ([email protected])
Feel free to do anything you want with this source code, but don't
distribute modified versions without clearly marking them as such.
==================================================================================
Page producing component. It reads content from file or stream and processes special tags.
It can take parameters and can hold internal content inside the tag markers. Very Fast
==================================================================================
7/3/2008:
* Initial implementation.
8/3/2008:
* Added new tag type "$" for extended tags. Kept the TPageProducer compatibility
11/3/2008
* support for two types of parameter notation (without or with " chars)
* reorganized the command parsing code
27/11/2008
* support for extra tags that allows to parse some of the html or similar code
30/09/2009
* unicode compatibility, treat all string and chars according to delphi version
26/01/2010
* Extra tags can have in depth processing
01/10/2010
* Unlimited in depth parsing even for same nested tags
* reorganized how trim inner content works
* can control how much indentation the inner content has
18/12/2013
* Parse inner contenct is now part of the callback handler
* Fixed automatic inner content parsing
19/12/2013
* Improved parameters parsing and support
==================================================================================
}
unit Cromis.PageProducer;
interface
uses
SysUtils, Classes, Math,
// library units
Cromis.Streams,
Cromis.Unicode;
const
SIZE_BUFFER = 65536;
CHAR_TAG_CMDNEW = '$';
CHAR_TAG_CMDOLD = '#';
CHAR_TAG_BEGIN = '<';
CHAR_TAG_CLOSE = '>';
CHAR_TAG_END = '/';
CHAR_PARAM_DELIM = '=';
CHAR_PARAM_CLOSE = '"';
CHAR_INDENT_BEGIN = '[';
CHAR_INDENT_CLOSE = ']';
type
TSourceType = (stStream, stString);
TContentTagEvent = procedure(const Sender: TObject;
const TagString: string;
const TagParams: TStrings;
const PageParams: TStrings;
const TagContent: string;
const ContentStream: TStream;
var ParseInnerContent: Boolean
) of Object;
TContentReader = class
private
FBytesRead: Integer;
FSourceStream: TStream;
FEndOfContent: Boolean;
FContentPosition: Integer;
FContentBuffer: array [0..SIZE_BUFFER - 1] of Byte;
public
constructor Create;
function GetNextChar: Char;
function PeekNextChar: Char;
property EndOfContent: Boolean read FEndOfContent write FEndOfContent;
property SourceStream: TStream read FSourceStream write FSourceStream;
end;
TPageProducerEx = class
private
FTagName: string;
FCurrChar: Char;
FExtraTags: TStringList;
FTagContent: string;
FExtraData: Pointer;
FSourceType: TSourceType;
FParseAllTags: Boolean;
FSourceString: string;
FSourceStream: TStream;
FOnContentTag: TContentTagEvent;
FContentIndent: Integer;
FExtraTagCheck: Boolean;
FTagParameters: TStringList;
FContentReader: TContentReader;
FPageParameters: TStringList;
FTrimInnerContent: Boolean;
FTrimTrailingCRLF: Boolean;
FExtraTagsExtended: Boolean;
procedure TrimRightEx(var TagContent: string);
procedure ParseCurrentTagName(var TagName: string;
var EndIndicator: Boolean;
var ContenIndent: Integer);
procedure ParseCurrentTagParameters(var EndIndicator: Boolean);
procedure ParseInnerTagContent(const TagContent: string; const DstStream: TStream);
procedure ParseCurrentTagContent(var EndIndicator: Boolean; const Extended: Boolean);
function CheckForClosingTagMatch(var EndTagContent: string; var TagCount: Integer): Boolean;
public
constructor Create;
destructor Destroy; override;
function ProduceContent: string; overload;
procedure ProduceContent(var DstString: string); overload;
procedure ProduceContent(const DstStream: TStream); overload;
procedure ProduceContent(const SrcStream, DstStream: TStream); overload;
property ExtraTags: TStringList read FExtraTags;
property PageParams: TStringList read FPageParameters;
property ExtraData: Pointer read FExtraData write FExtraData;
property SourceType: TSourceType read FSourceType write FSourceType;
property ParseAllTags: Boolean read FParseAllTags write FParseAllTags;
property SourceString: string read FSourceString write FSourceString;
property SourceStream: TStream read FSourceStream write FSourceStream;
property OnContentTag: TContentTagEvent read FOnContentTag write FOnContentTag;
property TrimInnerContent: Boolean read FTrimInnerContent write FTrimInnerContent;
property TrimTrailingCRLF: Boolean read FTrimTrailingCRLF write FTrimTrailingCRLF;
property ExtraTagsExtended: Boolean read FExtraTagsExtended write FExtraTagsExtended;
end;
implementation
{ TPageProducerEx }
function TPageProducerEx.CheckForClosingTagMatch(var EndTagContent: string; var TagCount: Integer): Boolean;
begin
EndTagContent := '';
while not FContentReader.EndOfContent do
begin
FCurrChar := FContentReader.GetNextChar;
case FCurrChar <> CHAR_TAG_CLOSE of
True: EndTagContent := EndTagContent + FCurrChar;
False: Break;
end;
end;
TagCount := TagCount - Integer(EndTagContent = FTagName);
Result := TagCount = 0;
end;
constructor TPageProducerEx.Create;
begin
FPageParameters := TStringList.Create;
FTagParameters := TStringList.Create;
FExtraTags := TStringList.Create;
FPageParameters.CaseSensitive := False;
FTagParameters.CaseSensitive := False;
FTrimInnerContent := False;
end;
destructor TPageProducerEx.Destroy;
begin
FreeAndNil(FExtraTags);
FreeAndNil(FTagParameters);
FreeAndNil(FPageParameters);
inherited;
end;
procedure TPageProducerEx.ParseCurrentTagContent(var EndIndicator: Boolean; const Extended: Boolean);
var
NestedTag: string;
SpaceCount: Integer;
IndentString: string;
EndTagContent: string;
ContentIndent: Integer;
NestedTagCount: Integer;
FoundLineStart: Boolean;
FoundLineContent: Boolean;
FoundContentStart: Boolean;
begin
FoundContentStart := False;
FoundLineContent := False;
FoundLineStart := False;
NestedTagCount := 1;
FTagContent := '';
SpaceCount := 0;
// parse the tag content
if not EndIndicator and Extended then
begin
while not FContentReader.EndOfContent do
begin
EndIndicator := FCurrChar = CHAR_TAG_BEGIN;
FCurrChar := FContentReader.GetNextChar;
// check for start
if not FoundContentStart then
begin
// check if the start was alread found and set it
if not (CharInSet(FCurrChar, [#13, #10, #32])) then
begin
FoundContentStart := True;
FoundLineStart := True;
end;
end;
if FTrimInnerContent and CharInSet(FCurrChar, [#13, #10, #32])
then
begin
if CharInSet(FCurrChar, [#13, #10]) and FoundContentStart then
begin
FTagContent := FTagContent + FCurrChar;
FoundLineContent := False;
FoundLineStart := True;
SpaceCount := 0;
end
else if FCurrChar = #32 then
begin
if (FContentIndent = -1) or (SpaceCount < FContentIndent) or FoundLineContent then
begin
FTagContent := FTagContent + FCurrChar;
Inc(SpaceCount);
end;
end;
end
else
begin
if FoundLineStart and FTrimInnerContent then
begin
FTagContent := FTagContent + StringOfChar(#32, Max(0, FContentIndent - SpaceCount));
FoundLineContent := True;
FoundLineStart := False;
end;
if not CharInSet(FCurrChar, [CHAR_TAG_END, CHAR_TAG_BEGIN]) then
begin
if EndIndicator and not (FCurrChar = CHAR_TAG_END) then
begin
FTagContent := FTagContent + CHAR_TAG_BEGIN;
if FCurrChar = CHAR_TAG_CMDNEW then
begin
ParseCurrentTagName(NestedTag, EndIndicator, ContentIndent);
FTagContent := FTagContent + CHAR_TAG_CMDNEW + NestedTag;
NestedTagCount := NestedTagCount + Integer(NestedTag = FTagName);
if ContentIndent > -1 then
begin
IndentString := Format('%s%d', [CHAR_INDENT_BEGIN, ContentIndent]);
FTagContent := FTagContent + IndentString;
end;
end;
end;
FTagContent := FTagContent + FCurrChar;
end
else if EndIndicator and (FCurrChar = CHAR_TAG_END) then
begin
case CheckForClosingTagMatch(EndTagContent, NestedTagCount) of
False: FTagContent := FTagContent + CHAR_TAG_BEGIN +
CHAR_TAG_END +
EndTagContent +
CHAR_TAG_CLOSE;
True: Break;
end;
end
else if FCurrChar = CHAR_TAG_END then
FTagContent := FTagContent + FCurrChar;
end;
end;
// always trim spaces null chars
TrimRightEx(FTagContent);
// check if we need to trim
if FTrimTrailingCRLF then
begin
if FContentReader.PeekNextChar = #13 then
FCurrChar := FContentReader.GetNextChar;
if FContentReader.PeekNextChar = #10 then
FCurrChar := FContentReader.GetNextChar;
end;
end;
end;
procedure TPageProducerEx.ParseCurrentTagName(var TagName: string;
var EndIndicator: Boolean;
var ContenIndent: Integer);
var
Indent: string;
begin
if FExtraTagCheck then
TagName := FCurrChar
else
TagName := '';
// parse the name of the tag
while not FContentReader.EndOfContent do
begin
EndIndicator := FCurrChar = CHAR_TAG_END;
FCurrChar := FContentReader.GetNextChar;
ContenIndent := -1;
Indent := '';
if FCurrChar = CHAR_INDENT_BEGIN then
begin
while not FContentReader.EndOfContent do
begin
FCurrChar := FContentReader.GetNextChar;
case FCurrChar <> CHAR_INDENT_CLOSE of
True: Indent := Indent + FCurrChar;
False: Break;
end;
end;
// always calculate the current indent
ContenIndent := StrToIntDef(Indent, -1);
end;
case not CharInSet(FCurrChar, [#32, CHAR_TAG_CLOSE, CHAR_INDENT_CLOSE]) of
True: TagName := TagName + FCurrChar;
False: Break;
end;
end;
end;
procedure TPageProducerEx.ParseCurrentTagParameters(var EndIndicator: Boolean);
var
ParamStr: string;
ParsingParams: Boolean;
BeginParamValue: Boolean;
procedure SetParsedParameter(const EndOfParameters: Boolean);
begin
if Trim(ParamStr) <> EmptyStr then
begin
if EndOfParameters and EndIndicator then
SetLength(ParamStr, Length(ParamStr) - 1);
FTagParameters.Add(ParamStr);
end;
BeginParamValue := False;
ParsingParams := False;
ParamStr := '';
end;
begin
BeginParamValue := False;
ParsingParams := False;
FTagParameters.Clear;
if FCurrChar <> CHAR_TAG_CLOSE then
begin
ParamStr := EmptyStr;
// parse the tag parameters
while not FContentReader.EndOfContent do
begin
EndIndicator := FCurrChar = CHAR_TAG_END;
FCurrChar := FContentReader.GetNextChar;
// break if we encountered close char
if (FCurrChar = CHAR_TAG_CLOSE) and not BeginParamValue then
begin
SetParsedParameter(True);
Break;
end;
// check all the possible states and combinations
if (FCurrChar = CHAR_PARAM_CLOSE) and not BeginParamValue then
BeginParamValue := True
else if (FCurrChar = CHAR_PARAM_CLOSE) and BeginParamValue then
SetParsedParameter(False)
else if not (FCurrChar = #32) or BeginParamValue then
begin
ParamStr := ParamStr + FCurrChar;
ParsingParams := True;
end
else if FCurrChar = #32 then
SetParsedParameter(False);
end;
end;
end;
procedure TPageProducerEx.ParseInnerTagContent(const TagContent: string; const DstStream: TStream);
var
ContentParser: TPageProducerEx;
begin
ContentParser := TPageProducerEx.Create;
try
ContentParser.OnContentTag := Self.OnContentTag;
ContentParser.ExtraTags.Assign(FExtraTags);
ContentParser.SourceString := TagContent;
ContentParser.FSourceType := stString;
// parse the content. can be recursive
ContentParser.ProduceContent(DstStream);
finally
ContentParser.Free;
end;
end;
function TPageProducerEx.ProduceContent: string;
begin
ProduceContent(Result);
end;
procedure TPageProducerEx.ProduceContent(var DstString: string);
var
MS: TMemoryStream;
begin
MS := TMemoryStream.Create;
try
Self.ProduceContent(MS);
{$IFDEF UNICODE}
DstString := UTF8ToString(ReadFromStreamAsUTF8(MS));
{$ELSE}
DstString := ReadFromStreamAsUTF8(MS);
{$ENDIF}
finally
MS.Free;
end;
end;
procedure TPageProducerEx.ProduceContent(const DstStream: TStream);
var
PrevChar: Char;
EndIndicator: Boolean;
ExtendedCommand: Boolean;
ParseInnerContent: Boolean;
UTF8BOM: array [0..2] of Byte;
begin
if FSourceType = stString then
begin
FSourceStream := TMemoryStream.Create;
Cromis.Streams.WriteToStreamAsUTF8(FSourceStream, FSourceString);
end;
if (FSourceType = stStream) and (FSourceStream = nil) then
raise Exception.Create('No source stream specified!');
if DstStream = nil then
raise Exception.Create('No destination stream specified!');
if not Assigned(FOnContentTag) then
raise Exception.Create('OnContentTag not assigned!');
FContentReader := TContentReader.Create;
try
FContentReader.SourceStream := FSourceStream;
FSourceStream.Position := 0;
FCurrChar := #0;
if FSourceStream.Position = 0 then
begin
FSourceStream.Read(UTF8BOM, SizeOf(UTF8BOM));
if not ((UTF8BOM[0] = 239) and
(UTF8BOM[1] = 187) and
(UTF8BOM[2] = 191)) then
FSourceStream.Position := 0;
end;
while not FContentReader.EndOfContent do
begin
PrevChar := FCurrChar;
FCurrChar := FContentReader.GetNextChar;
if not FContentReader.EndOfContent then
begin
if (PrevChar = CHAR_TAG_BEGIN) and CharInSet(FCurrChar, [CHAR_TAG_CMDNEW, CHAR_TAG_CMDOLD]) then
begin
ExtendedCommand := FCurrChar = CHAR_TAG_CMDNEW;
ParseInnerContent := True;
EndIndicator := False;
FContentIndent := -1;
ParseCurrentTagName(FTagName, EndIndicator, FContentIndent);
ParseCurrentTagParameters(EndIndicator);
ParseCurrentTagContent(EndIndicator, ExtendedCommand);
// call the listening application and pass all the parameters
FOnContentTag(Self, FTagName, FTagParameters, FPageParameters, FTagContent, DstStream, ParseInnerContent);
if ParseInnerContent and (Trim(FTagContent) <> '') then
ParseInnerTagContent(FTagContent, DstStream);
end
else if (PrevChar = CHAR_TAG_BEGIN) then
begin
// do we check for extra tags
FExtraTagCheck := ((FExtraTags.Count > 0) and (FCurrChar <> CHAR_TAG_END)) or FParseAllTags;
EndIndicator := False;
if FExtraTagCheck then
begin
ParseCurrentTagName(FTagName, EndIndicator, FContentIndent);
case not FParseAllTags of
True: FExtraTagCheck := FExtraTags.IndexOf(FTagName) > -1;
False: FExtraTagCheck := True;
end;
if FExtraTagCheck then
begin
ParseInnerContent := True;
ParseCurrentTagParameters(EndIndicator);
ParseCurrentTagContent(EndIndicator, FExtraTagsExtended);
FOnContentTag(Self, FTagName, FTagParameters, FPageParameters, FTagContent, DstStream, ParseInnerContent);
if ParseInnerContent and (Trim(FTagContent) <> '') then
ParseInnerTagContent(FTagContent, DstStream);
end
else
begin
// write both chars and tag to the stream
DstStream.Write(PrevChar, SizeOf(AnsiChar));
DstStream.Write(FTagName[1], SizeOf(AnsiChar) * Length(FTagName));
DstStream.Write(FCurrChar, SizeOf(AnsiChar));
end;
end
else
begin
// write both chars to the stream
DstStream.Write(PrevChar, SizeOf(AnsiChar));
DstStream.Write(FCurrChar, SizeOf(AnsiChar));
end;
end
else if FCurrChar <> CHAR_TAG_BEGIN then
DstStream.Write(FCurrChar, SizeOf(AnsiChar));
end;
end;
// clean behind ourselves
if FSourceType = stString then
begin
FreeAndNil(FSourceStream);
FSourceString := '';
end;
finally
FContentReader.Free;
end;
end;
procedure TPageProducerEx.ProduceContent(const SrcStream, DstStream: TStream);
begin
SourceStream := SrcStream;
ProduceContent(DstStream);
end;
procedure TPageProducerEx.TrimRightEx(var TagContent: string);
var
StrLength: Integer;
begin
StrLength := Length(TagContent);
while (StrLength > 0) and (CharInSet(TagContent[StrLength], [#32, #0])) do
Dec(StrLength);
if StrLength < Length(TagContent) then
SetLength(TagContent, StrLength);
end;
{ TContentReader }
constructor TContentReader.Create;
begin
FContentPosition := SIZE_BUFFER;
FEndOfContent := False;
end;
function TContentReader.GetNextChar: Char;
begin
Result := #0;
if FContentPosition >= FBytesRead then
begin
// read the next block of bytes from the source stream
FBytesRead := FSourceStream.Read(FContentBuffer, SIZE_BUFFER);
case FBytesRead > 0 of
True: FContentPosition := 0;
False: FEndOfContent := True;
end;
end;
if not FEndOfContent then
begin
Result := Chr(FContentBuffer[FContentPosition]);
Inc(FContentPosition);
end;
end;
function TContentReader.PeekNextChar: Char;
begin
Result := #0;
if FContentPosition >= FBytesRead then
begin
// read the next block of bytes from the source stream
FBytesRead := FSourceStream.Read(FContentBuffer, SIZE_BUFFER);
case FBytesRead > 0 of
True: FContentPosition := 0;
False: FEndOfContent := True;
end;
end;
if not FEndOfContent then
Result := Chr(FContentBuffer[FContentPosition]);
end;
end.