summaryrefslogtreecommitdiff
path: root/docview/components/richtext/RichTextDocumentUnit.pas
blob: f5d83ddebb9371f0687e934382c9050b947b9591 (plain)
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
Unit RichTextDocumentUnit;

{$mode objfpc}{$H+}
// Declarations of tags, and parsing functions

Interface

uses
  Classes
  ,fpg_base
  ;

type
  COUNTRYCODE = string[2];

  TTagType = ( ttInvalid,
               ttBold, ttBoldOff,
               ttItalic, ttItalicOff,
               ttUnderline, ttUnderlineOff,
               ttFixedWidthOn, ttFixedWidthOff,
               ttHeading1, ttHeading2, ttHeading3, ttHeadingOff,
               ttColor, ttColorOff,
               ttBackgroundColor, ttBackgroundColorOff,
               ttRed, ttBlue, ttGreen, ttBlack,
               ttWrap,
               ttAlign,
               ttBeginLink, ttEndLink,
               ttSetLeftMargin, ttSetRightMargin,
               ttImage,
               ttFont, ttFontOff,
               ttEnd );

  TStandardColor = record
    Name: string[ 32 ];
    Color: TfpgColor;
  end;

  TTag = record
    TagType: TTagType;
    Arguments: string;
  end;

  TTextElementType = ( teText, // a character
                       teWordBreak,
                       teLineBreak, // end of para
                       teTextEnd,
                       teImage,
                       teStyle );

  TTextElement = record
    ElementType: TTextElementType;
    Character: TfpgChar;  // so we can support UTF-8 character
    Tag: TTag;
  end;

  TTextAlignment = ( taLeft,
                     taRight,
                     taCenter );

const
  TagStr: array[ ttInvalid .. ttEnd ] of string =
  (
    '', //
    'b',
    '/b',
    'i',
    '/i',
    'u',
    '/u',
    'tt',
    '/tt',
    'h1',
    'h2',
    'h3',
    '/h',
    'color',
    '/color',
    'backcolor',
    '/backcolor',
    'red',
    'blue',
    'green',
    'black',
    'wrap',
    'align',
    'link',
    '/link',
    'leftmargin',
    'rightmargin',
    'image',
    'font',
    '/font',
    ''
  );


// Returns tag pointed to by TextPointer and
// moves TextPointer to the first char after the tag.
Function ExtractTag( Var TextPointer: PChar ): TTag;

// Returns tag ending at TextPointer
// (Expects textpointer is currently pointing at the >)
// and moves TextPointer to the first char of the tag
Function ExtractPreviousTag( const TextStart: PChar; Var TextPointer: PChar ): TTag;
function ExtractNextTextElement( TextPointer: PChar; Var NextElement: PChar ): TTextElement;
function ExtractPreviousTextElement( const TextStart: PChar; TextPointer: PChar; Var NextElement: PChar ): TTextElement;

// Parse a color name or value (#hexval). Returns true if valid
function GetTagColor( const ColorParam: string; var Color: TfpgColor ): boolean;

function GetTagTextAlignment( const AlignParam: string;
                              const Default: TTextAlignment ): TTextAlignment;

function GetTagTextWrap( const WrapParam: string ): boolean;

// Search within a rich text document for the given text
// if found, returns true, pMatch is set to the first match,
//   and MatchLength returns the length of the match
//   (which may be greater than the length of Text due to
//    to skipping tags)
// if not found, returns false, pMatch is set to nil
function RichTextFindString( pRichText: PChar;
                             const Text: string;
                             var pMatch: PChar;
                             var MatchLength: longint ): boolean;

// Returns the start of the previous word,
// or the current word if pStart is in the middle of the word
function RichTextWordLeft( pRichText: PChar;
                           pStart: PChar ): PChar;

// Returns the start of the next word.
function RichTextWordRight( pStart: PChar ): PChar;

// If pStart is in the middle of a word, then
// returns true and sets the start and length of the word
function RichTextWordAt( pRichText: PChar;
                         pStart: PChar;
                         Var pWordStart: PChar;
                         Var WordLength: longint ): boolean;

// Copies plaintext of richtext starting at StartP
// to the given buffer. Returns number of characters copied.
// Buffer may be nil
// If BufferLength is negative, it is effectively ignored
function CopyPlainTextToBuffer( StartP: PChar;
                                EndP: PChar;
                                Buffer: PChar;
                                BufferLength: longint ): longint;

Implementation

uses
  SysUtils
  ,ACLStringUtility
  ,fpg_stringutils
  ;

const
  StandardColors: array[ 0..7 ] of TStandardColor =
  (
    ( Name : 'white' ; Color: clWhite   ),
    ( Name : 'black' ; Color: clBlack   ),
    ( Name : 'red'   ; Color: clRed     ),
    ( Name : 'blue'  ; Color: clBlue    ),
    ( Name : 'green' ; Color: clLime    ),
    ( Name : 'purple'; Color: clFuchsia ),
    ( Name : 'yellow'; Color: clYellow  ),
    ( Name : 'cyan'  ; Color: clAqua    )
  );

Procedure ParseTag( const Text: string;
                    Var Tag: TTag );
var
  TagType: TTagType;
  TagTypeText: string;
  SpacePos: longint;
begin
  SpacePos := Pos( ' ', Text );
  if SpacePos <> 0 then
  begin
    Tag.Arguments := trim( Copy( Text, SpacePos + 1, 255 ) );
    TagTypeText := LowerCase( Copy( Text, 1, SpacePos - 1 ) );
  end
  else
  begin
    Tag.Arguments := ''; // to save time copying when not needed
    TagTypeText := LowerCase( Text );
  end;

  for TagType := ttBold to ttEnd do
  begin
    if TagStr[ TagType ] = TagTypeText  then
    begin
      Tag.TagType := TagType;
      exit;
    end;
  end;

  // not found
  Tag.TagType := ttInvalid;
end;

var
  TagText: string;
  TagArgText: string;

Function ExtractTag( Var TextPointer: PChar ): TTag;
var
  CurrentChar: Char;
  TagTooLong: boolean;
  InQuote: boolean;
begin
//  assert( TextPointer[ 0 ] = '<' );
  TagText := '';
  TagTooLong := false;
  InQuote := false;

  repeat
    CurrentChar := TextPointer^;

    if     ( CurrentChar = '>' )
       and ( not InQuote ) then
    begin
      // found tag end.
      if TagTooLong then
        Result.TagType := ttInvalid
      else
        ParseTag( TagText, Result );
      inc( TextPointer );
      exit;
    end;

    if CurrentChar = #0 then
    begin
      // if we reach here we have reached the end of text
      // during a tag. invalid tag.
      Result.TagType := ttInvalid;
      exit;
    end;

    if CurrentChar = CharDoubleQuote then
    begin
      if not InQuote then
      begin
        InQuote := true
      end
      else
      begin
        // Could be escaped quote ""
//        if (TextPointer + 1 )^ = DoubleQuote then
        if ( TextPointer + 1 ) ^ = CharDoubleQuote then
        begin
          // yes it is
          inc( TextPointer ); // skip second one
        end
        else
        begin
          // no, not an escaped quote
          InQuote := false;
        end;
      end;

    end;

    if not TagTooLong then
      if Length( TagText ) < 200 then
        TagText := TagText + CurrentChar
      else
        TagTooLong := true; // but keep going until the end

    inc( TextPointer );
  until false;

end;

// Expects textpointer is currently pointing at the >
Function ExtractPreviousTag( const TextStart: PChar;
                             Var TextPointer: PChar ): TTag;
var
  CurrentChar: Char;
  TagTooLong: boolean;
  InQuote: boolean;
begin
  TagText := '';
  TagTooLong := false;
  InQuote := false;

  repeat
    dec( TextPointer );
    if TextPointer < TextStart then
    begin
      // if we reach here we have reached the end of text
      // during a tag. invalid tag.
      Result.TagType := ttInvalid;
      exit;
    end;
    CurrentChar := TextPointer^;

    if     ( CurrentChar = '<' )
       and ( not InQuote ) then
    begin
      // found tag end.
      if TagTooLong then
        Result.TagType := ttInvalid
      else
        ParseTag( TagText, Result );
      exit;
    end;

    if CurrentChar = CharDoubleQuote then
    begin
      if not InQuote then
      begin
        InQuote := true
      end
      else
      begin
        // Could be escaped quote ""
        if TextPointer <= TextStart then
        begin
          // start of text... somethin weird
          InQuote := false;
        end
        else if ( TextPointer - 1 ) ^ = CharDoubleQuote then
        begin
          // yes it is
          dec( TextPointer ); // skip second one
        end
        else
        begin
          // no, not an escaped quote
          InQuote := false;
        end;
      end;

    end;

    if not TagTooLong then
      if Length( TagText ) < 200 then
        TagText := CurrentChar + TagText
      else
        TagTooLong := true; // but keep going until the end

  until false;

end;

function ExtractNextTextElement( TextPointer: PChar; Var NextElement: PChar ): TTextElement;
var
  TheChar: TfpgChar;
  NextChar: TfpgChar;
  CharLength: integer;
  s1, s2: TfpgString;
  c: Char;
begin
  with Result do
  begin
    CharLength := UTF8CharacterLength(TextPointer);
    s1 := TextPointer;
    TheChar := UTF8Copy(s1, 1, 1);
    c := TextPointer^;
    Character := TheChar;
    inc( TextPointer, CharLength );

    if (TheChar = ' ') and (c <> #0) then
    begin
      // ---- Space (word break) found ----
      ElementType := teWordBreak;
    end
    else if (TheChar = #10) or (TheChar = #13) then
    begin
      // ---- End of line found ----
      begin
        ElementType := teLineBreak;
        if TheChar = #13 then
        begin
          TheChar := TextPointer^;
          if TheChar = #10 then
            // skip CR following LF
            inc( TextPointer );
        end;
      end;
    end
    else if (TheChar = '') and (c = #0) then
    begin
      // ---- end of text found ----
      ElementType := teTextEnd;
    end
    else if TheChar = '<' then
    begin
      // ---- tag found? ----
      CharLength := UTF8CharacterLength(TextPointer);
      s2 := TextPointer;
      NextChar := UTF8Copy(s2, 1, 1);
      if NextChar = '<' then
      begin
        // no, just a literal <
        ElementType := teText;
        inc( TextPointer );
      end
      else
      begin
        Tag := ExtractTag( TextPointer );
        if Tag.TagType = ttImage then
          ElementType := teImage
        else
          ElementType := teStyle;
      end;
    end
    else if TheChar = '>' then
    begin
      // check - should be double
      begin
        ElementType := teText;
        NextChar := TextPointer^;
        if NextChar = '>' then
          inc( TextPointer );
      end;
    end
    else
      ElementType := teText;

  end; // with
  NextElement := TextPointer;
end;

function ExtractPreviousTextElement( const TextStart: PChar;
                                     TextPointer: PChar;
                                     Var NextElement: PChar ): TTextElement;
var
  TheChar: Char;
  PreviousChar: Char;
  FoundTag: boolean;
begin
  with Result do
  begin
    dec( TextPointer );
    TheChar := TextPointer^;
    Character := TheChar;
    if TextPointer < TextStart then
    begin
      ElementType := teTextEnd;
      exit;
    end;

    case TheChar of
      ' ': // ---- Space (word break) found ----
        ElementType := teWordBreak;

      #10, #13: // ---- End of line found ----
      begin
        ElementType := teLineBreak;
        if TheChar = #10 then
        begin
          dec( TextPointer );
          TheChar := TextPointer^;
          if TheChar = #13 then
          begin
            // skip CR preceeding LF
          end
          else
            inc( TextPointer );
        end;
      end;

      '>': // ---- tag found ----
      begin
        FoundTag := true;
        if TextPointer > TextStart then
        begin
          PreviousChar := ( TextPointer - 1 )^;
          if PreviousChar = '>' then
          begin
            // no. just a literal >
            FoundTag := false;
            ElementType := teText;
            dec( TextPointer );
          end
        end;

        if FoundTag then
        begin
          Tag := ExtractPreviousTag( TextStart, TextPointer );
          if Tag.TagType = ttImage then
            ElementType := teImage
          else
            ElementType := teStyle;
        end;
      end;

      '<': // should be double
      begin
        ElementType := teText;
        if TextPointer > TextStart then
        begin
          PreviousChar := TextPointer^;
          if PreviousChar = '<' then
            dec( TextPointer );
        end;
      end
      else
        ElementType := teText;
    end;
  end; // with
  NextElement := TextPointer;
end;

function GetTagColor( const ColorParam: string;
                      var Color: TfpgColor ): boolean;
var
  ColorIndex: longint;
begin
  Result := false;
  if ColorParam <> '' then
  begin
    if ColorParam[ 1 ] = '#' then
    begin
      try
        Color := HexToInt( StrRightFrom( ColorParam, 2 ) );
        Result := true;
      except
      end;
    end
    else
    begin
      for ColorIndex := 0 to High( StandardColors ) do
      begin
        if StringsSame( ColorParam, StandardColors[ ColorIndex ].Name ) then
        begin
          Color := StandardColors[ ColorIndex ].Color;
          Result := true;
          break;
        end;
      end;
    end;
  end;
end;

function GetTagTextAlignment( const AlignParam: string;
                              const Default: TTextAlignment ): TTextAlignment;
begin
  if StringsSame( AlignParam, 'left' ) then
    Result := taLeft
  else if StringsSame( AlignParam, 'center' ) then
    Result := taCenter
  else if StringsSame( AlignParam, 'right' ) then
    Result := taRight
  else
    Result := Default;
end;

function GetTagTextWrap( const WrapParam: string ): boolean;
begin
  Result := StringsSame( WrapParam, 'yes' );
end;

function RichTextFindString( pRichText: PChar;
                             const Text: string;
                             var pMatch: PChar;
                             var MatchLength: longint ): boolean;
var
  P: PChar;
  NextP: PChar;
  Element: TTextElement;
  pMatchStart: pchar;
  pMatchStartNext: pchar;
  MatchIndex: longint;
  C: Char;
begin
  if Length( Text ) = 0 then
  begin
    // null string always matches
    Result := true;
    pMatch := pRichText;
    MatchLength := 0;
    exit;
  end;

  P := pRichText;
  MatchIndex := 1;

  // Now search, case insensitively
  while true do
  begin
    Element := ExtractNextTextElement( P, NextP );

    case Element.ElementType of
      teTextEnd:
        // end of text
        break;

      teImage,
      teLineBreak:
        // breaks a potential match
        MatchIndex := 1;

      teStyle:
        ; // ignore, matches can continue

      else
      begin
        if Uppercase(Element.Character) = UpperCase(Text[Matchindex]) then
        begin
          // found a match
          if MatchIndex = 1 then
          begin
            pMatchStart := P; // store start of match
            pMatchStartNext := NextP;
          end;

          inc( MatchIndex );
          if MatchIndex > Length( Text ) then
          begin
            // found a complete match
            Result := true;
            pMatch := pMatchStart;
            MatchLength := PCharDiff( P, pMatchStart )
                           + 1; // include this char
            exit;
          end;
        end
        else
        begin
          // not a match
          if MatchIndex > 1 then
          begin
            // go back to start of match, + 1
            NextP := pMatchStartNext;
            MatchIndex := 1;
          end;
        end;
      end;
    end;

    P := NextP;
  end;

  // no match found
  Result := false;
  pMatch := nil;
  MatchLength := 0;
end;

function RichTextWordLeft( pRichText: PChar;
                           pStart: PChar ): PChar;
Var
  P: PChar;
  NextP: PChar;
  Element: TTextElement;
begin
  P := pStart;

  // skip whitespace/tags...
  Element := ExtractPreviousTextElement( pRichText, P, NextP );
  P := NextP;
  while Element.ElementType in [ teWordBreak, teLineBreak, teImage, teStyle ] do
  begin
    Element := ExtractPreviousTextElement( pRichText, P, NextP );
    P := NextP;
  end;
  if Element.ElementType = teTextEnd then
  begin
    Result := P;
    // out of text
    exit;
  end;

  // back to start of word, skip text/tags
  while true do
  begin
    Element := ExtractPreviousTextElement( pRichText, P, NextP );
    if not ( Element.ElementType in [ teText, teStyle ] ) then
      break;
    P := NextP;
  end;
  Result := P;
end;

function RichTextWordRight( pStart: PChar ): PChar;
Var
  P: PChar;
  NextP: PChar;
  Element: TTextElement;
begin
  P := pStart;

  // skip text/tags...
  Element := ExtractNextTextElement( P, NextP );
  while Element.ElementType in [ teStyle, teText ] do
  begin
    P := NextP;
    Element := ExtractNextTextElement( P, NextP );
  end;
  if Element.ElementType <> teTextEnd then
  begin
    // skip whitespace
    Element := ExtractNextTextElement( P, NextP );
    while Element.ElementType in [ teWordBreak, teLineBreak, teImage, teStyle ] do
    begin
      P := NextP;
      Element := ExtractNextTextElement( P, NextP );
    end;
  end;

  Result := P;
end;

function RichTextWordAt( pRichText: PChar;
                         pStart: PChar;
                         Var pWordStart: PChar;
                         Var WordLength: longint ): boolean;
Var
  P: PChar;
  NextP: PChar;
  Element: TTextElement;
  pWordEnd: PChar;
begin
  P := pStart;
  Element := ExtractNextTextElement( P, NextP );
  if not ( Element.ElementType in [ teStyle, teText ] ) then
  begin
    // not in a word.
    result := false;
    pWordStart := nil;
    WordLength := 0;
    exit;
  end;
  // find end of the word
  while Element.ElementType in [ teStyle, teText ] do
  begin
    P := NextP;
    Element := ExtractNextTextElement( P, NextP );
  end;
  pWordEnd := P;

  P := pStart;
  Element := ExtractPreviousTextElement( pRichText, P, NextP );
  while Element.ElementType in [ teStyle, teText ] do
  begin
    P := NextP;
    Element := ExtractPreviousTextElement( pRichText, P, NextP );
  end;
  pWordStart := P;
  WordLength := PCharDiff( pWordEnd, pWordStart );
  Result := true;
end;

// TODO: Rewrite this to work with fpGUI and AnsiString/TfpgString
function CopyPlainTextToBuffer( StartP: PChar;
                                EndP: PChar;
                                Buffer: PChar;
                                BufferLength: longint ): longint;
var
  Q: PChar;
  EndQ: Pchar;
  P: PChar;
  NextP: PChar;
  Element: TTextElement;
begin
 (*
  P := StartP;
  Q := Buffer;
  EndQ := Buffer + BufferLength;

  while P < EndP do
  begin
    Element := ExtractNextTextElement( P, NextP );
    case Element.ElementType of
      teText, teWordBreak:
      begin
        // copy char
        if Buffer <> nil then
          Q[ 0 ] := Element.Character;
        inc( Q );
      end;

      teLineBreak:
      begin
        if Buffer <> nil then
          Q[ 0 ] := #13;
        inc( Q );
        if Q = EndQ then
          // end of buffer
          break;

        if Buffer <> nil then
          Q[ 0 ] := #10;
        inc( Q );
      end;
    end;

   if Q = EndQ then
     // end of buffer
     break;

    P := NextP;
  end;
  result := PCharDiff( Q, Buffer );
  *)
end;

Initialization
End.