summaryrefslogtreecommitdiff
path: root/plugins/Utils.pas/rtfutils.pas
blob: 9f545fc8658f52e10b3e50bf71df95f41f6003f4 (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
unit rtfutils;

interface

uses
  richedit,
  windows;


function IsRTF(const Value: PWideChar): Boolean;

//used for Export only
function GetRichRTFW(RichEditHandle: THANDLE; var RTFStream: PWideChar;
                    SelectionOnly, PlainText, NoObjects, PlainRTF: Boolean): Integer;
function GetRichRTFA(RichEditHandle: THANDLE; var RTFStream: PAnsiChar;
                    SelectionOnly, PlainText, NoObjects, PlainRTF: Boolean): Integer;

function GetRichString(RichEditHandle: THANDLE; SelectionOnly: Boolean = false): PWideChar;

function SetRichRTFW(RichEditHandle: THANDLE; const RTFStream: PWideChar;
                    SelectionOnly, PlainText, PlainRTF: Boolean): Integer;
function SetRichRTFA(RichEditHandle: THANDLE; const RTFStream: PAnsiChar;
                    SelectionOnly, PlainText, PlainRTF: Boolean): Integer;

function FormatString2RTFW(Source: PWideChar; Suffix: PAnsiChar = nil): PAnsiChar;
function FormatString2RTFA(Source: PAnsiChar; Suffix: PAnsiChar = nil): PAnsiChar;

procedure ReplaceCharFormatRange(RichEditHandle: THANDLE;
     const fromCF, toCF: CHARFORMAT2; idx, len: Integer);
procedure ReplaceCharFormat(RichEditHandle: THANDLE; const fromCF, toCF: CHARFORMAT2);

function GetTextLength(RichEditHandle:THANDLE): Integer;
function GetTextRange (RichEditHandle:THANDLE; cpMin,cpMax: Integer): PWideChar;

function BitmapToRTF(pict: HBITMAP): PAnsiChar;

implementation

uses
  common;

function IsRTF(const Value: PWideChar): Boolean;
const
  RTF_BEGIN_1  = '{\RTF';
  RTF_BEGIN_2  = '{URTF';
begin
  Result := (StrPosW(Value,RTF_BEGIN_1) = Value)
         or (StrPosW(Value,RTF_BEGIN_2) = Value);
end;

type
  PTextStream = ^TTextStream;
  TTextStream = record
    Size: Integer;
    case Boolean of
      false: (Data:  PAnsiChar);
      true:  (DataW: PWideChar);
  end;

function RichEditStreamLoad(dwCookie: DWORD_PTR; pbBuff: PByte; cb: Longint; var pcb: Longint): dword; stdcall;
var
  pBuff: PAnsiChar;
begin
  with PTextStream(dwCookie)^ do
  begin
    pBuff := Data;
    pcb := Size;
    if pcb > cb then
      pcb := cb;
    Move(pBuff^, pbBuff^, pcb);
    Inc(Data, pcb);
    Dec(Size, pcb);
  end;
  Result := 0;
end;

function RichEditStreamSave(dwCookie: DWORD_PTR; pbBuff: PByte; cb: Longint; var pcb: Longint): dword; stdcall;
var
  prevSize: Integer;
begin
  with PTextStream(dwCookie)^ do
  begin
    prevSize := Size;
    Inc(Size,cb);
    ReallocMem(Data,Size);
    Move(pbBuff^,(Data+prevSize)^,cb);
    pcb := cb;
  end;
  Result := 0;
end;

function _GetRichRTF(RichEditHandle: THANDLE; TextStream: PTextStream;
                    SelectionOnly, PlainText, NoObjects, PlainRTF, Unicode: Boolean): Integer;
var
  es: TEditStream;
  Format: Longint;
begin
  format := 0;
  if SelectionOnly then
    Format := Format or SFF_SELECTION;
  if PlainText then
  begin
    if NoObjects then
      Format := Format or SF_TEXT
    else
      Format := Format or SF_TEXTIZED;
    if Unicode then
      Format := Format or SF_UNICODE;
  end
  else
  begin
    if NoObjects then
      Format := Format or SF_RTFNOOBJS
    else
      Format := Format or SF_RTF;
    if PlainRTF then
      Format := Format or SFF_PLAINRTF;
    // if Unicode then   format := format or SF_USECODEPAGE or (CP_UTF16 shl 16);
  end;
  TextStream^.Size := 0;
  TextStream^.Data := nil;
  es.dwCookie := DWORD_PTR(TextStream);
  es.dwError := 0;
  es.pfnCallback := @RichEditStreamSave;
  SendMessage(RichEditHandle, EM_STREAMOUT, format, LPARAM(@es));
  Result := es.dwError;
end;

function GetRichRTFW(RichEditHandle: THANDLE; var RTFStream: PWideChar;
                    SelectionOnly, PlainText, NoObjects, PlainRTF: Boolean): Integer;
var
  Stream: TTextStream;
begin
  Result := _GetRichRTF(RichEditHandle, @Stream,
                        SelectionOnly, PlainText, NoObjects, PlainRTF, PlainText);
  if Assigned(Stream.DataW) then
  begin
    if PlainText then
      StrDupW(RTFStream, Stream.DataW, Stream.Size div SizeOf(WideChar))
    else
      AnsiToWide(Stream.Data, RTFStream, CP_ACP);
    FreeMem(Stream.Data, Stream.Size);
  end
  else
    RTFStream := nil;
end;

function GetRichRTFA(RichEditHandle: THANDLE; var RTFStream: PAnsiChar;
                    SelectionOnly, PlainText, NoObjects, PlainRTF: Boolean): Integer;
var
  Stream: TTextStream;
begin
  Result := _GetRichRTF(RichEditHandle, @Stream,
                        SelectionOnly, PlainText, NoObjects, PlainRTF, False);
  if Assigned(Stream.Data) then
  begin
    StrDup(RTFStream, Stream.Data, Stream.Size - 1);
    FreeMem(Stream.Data, Stream.Size);
  end
  else
    RTFStream := nil;
end;

function GetRichString(RichEditHandle: THANDLE; SelectionOnly: Boolean = false): PWideChar;
begin
  GetRichRTFW(RichEditHandle,Result,SelectionOnly,True,True,False);
end;


function _SetRichRTF(RichEditHandle: THANDLE; TextStream: PTextStream;
                    SelectionOnly, PlainText, PlainRTF, Unicode: Boolean): Integer;
var
  es: TEditStream;
  Format: Longint;
begin
  Format := 0;
  if SelectionOnly then
    Format := Format or SFF_SELECTION;
  if PlainText then
  begin
    Format := Format or SF_TEXT;
    if Unicode then
      Format := Format or SF_UNICODE;
  end
  else
  begin
    Format := Format or SF_RTF;
    if PlainRTF then
      Format := Format or SFF_PLAINRTF;
    // if Unicode then  format := format or SF_USECODEPAGE or (CP_UTF16 shl 16);
  end;
  es.dwCookie := LPARAM(TextStream);
  es.dwError := 0;
  es.pfnCallback := @RichEditStreamLoad;
  SendMessage(RichEditHandle, EM_STREAMIN, format, LPARAM(@es));
  Result := es.dwError;
end;

function SetRichRTFW(RichEditHandle: THANDLE; const RTFStream: PWideChar;
                    SelectionOnly, PlainText, PlainRTF: Boolean): Integer;
var
  Stream: TTextStream;
  Buffer: PAnsiChar;
begin
  if PlainText then
  begin
    Stream.DataW := RTFStream;
    Stream.Size  := StrLenW(RTFStream) * SizeOf(WideChar);
    Buffer := nil;
  end
  else
  begin
    WideToAnsi(RTFStream, Buffer, CP_ACP);
    Stream.Data := Buffer;
    Stream.Size := StrLen(Buffer);
  end;
  Result := _SetRichRTF(RichEditHandle, @Stream,
                        SelectionOnly, PlainText, PlainRTF, PlainText);
  mFreeMem(Buffer);
end;

function SetRichRTFA(RichEditHandle: THANDLE; const RTFStream: PAnsiChar;
                    SelectionOnly, PlainText, PlainRTF: Boolean): Integer;
var
  Stream: TTextStream;
begin
  Stream.Data := RTFStream;
  Stream.Size := StrLen(RTFStream);
  Result := _SetRichRTF(RichEditHandle, @Stream,
                        SelectionOnly, PlainText, PlainRTF, False);
end;

function FormatString2RTFW(Source: PWideChar; Suffix: PAnsiChar = nil): PAnsiChar;
var
  Text: PWideChar;
  res: PAnsiChar;
  buf: array [0..15] of AnsiChar;
  len: integer;
begin
  // calculate len
  len:=Length('{\uc1 ');
  Text := PWideChar(Source);
  while Text[0] <> #0 do
  begin
    if (Text[0] = #13) and (Text[1] = #10) then
    begin
      inc(len,Length('\par '));
      Inc(Text);
    end
    else
      case Text[0] of
        #10: inc(len,Length('\par '));
        #09: inc(len,Length('\tab '));
        '\', '{', '}':
          inc(len,2);
      else
        if Word(Text[0]) < 128 then
          inc(len)
        else
          inc(len,3+IntStrLen(Word(Text[0]),10));
      end;
    Inc(Text);
  end;
  inc(len,StrLen(Suffix)+2);

  // replace
  Text := PWideChar(Source);
  GetMem(Result,len);
  res:=StrCopyE(Result,'{\uc1 ');
  while Text[0] <> #0 do
  begin
    if (Text[0] = #13) and (Text[1] = #10) then
    begin
      res:=StrCopyE(res,'\par ');
      Inc(Text);
    end
    else
      case Text[0] of
        #10: res:=StrCopyE(res,'\par ');
        #09: res:=StrCopyE(res,'\tab ');
        '\', '{', '}': begin
          res^:='\'; inc(res);
          res^:=AnsiChar(Text[0]); inc(res);
        end;
      else
        if Word(Text[0]) < 128 then
        begin
          res^:=AnsiChar(Word(Text[0])); inc(res);
        end
        else
        begin
          res:=StrCopyE(
            StrCopyE(res,'\u'),
            IntToStr(buf,Word(Text[0])));
          res^:='?'; inc(res);
        end;
      end;
    Inc(Text);
  end;

  res:=StrCopyE(res, Suffix);
  res^:='}'; inc(res); res^:=#0;
end;

function FormatString2RTFA(Source: PAnsiChar; Suffix: PAnsiChar = nil): PAnsiChar;
var
  Text,res: PAnsiChar;
  len: integer;
begin
  // calculate len
  len:=1;
  Text := PAnsiChar(Source);
  while Text[0] <> #0 do
  begin
    if (Text[0] = #13) and (Text[1] = #10) then
    begin
      inc(len,Length('\line '));
      Inc(Text);
    end
    else
      case Text[0] of
        #10: inc(len,Length('\line '));
        #09: inc(len,Length('\tab '));
        '\', '{', '}':
          inc(len,2);
      else
        inc(len);
      end;
    Inc(Text);
  end;
  inc(len,StrLen(Suffix)+2);

  // replace
  Text := PAnsiChar(Source);
  GetMem(Result,len);
  res:=Result;
  res^ := '{'; inc(res);
  while Text[0] <> #0 do
  begin
    if (Text[0] = #13) and (Text[1] = #10) then
    begin
      res:=StrCopyE(res,'\line ');
      Inc(Text);
    end
    else
      case Text[0] of
        #10: res:=StrCopyE(res,'\line ');
        #09: res:=StrCopyE(res,'\tab ');
        '\', '{', '}': begin
          res^:='\'; inc(res);
          res^:=Text[0]; inc(res);
        end;
      else
        res^:=Text[0]; inc(res);
      end;
    Inc(Text);
  end;

  res:=StrCopyE(res, Suffix);
  res^:='}'; inc(res); res^:=#0;
end;

function GetTextLength(RichEditHandle: THANDLE): Integer;
var
  gtxl: GETTEXTLENGTHEX;
begin
  gtxl.flags    := GTL_DEFAULT or GTL_PRECISE;
  gtxl.codepage := 1200; // Unicode
  gtxl.flags    := gtxl.flags or GTL_NUMCHARS;
  Result := SendMessage(RichEditHandle, EM_GETTEXTLENGTHEX, WPARAM(@gtxl), 0);
end;

procedure ReplaceCharFormatRange(RichEditHandle: THANDLE;
     const fromCF, toCF: CHARFORMAT2; idx, len: Integer);
var
  cr: CHARRANGE;
  cf: CHARFORMAT2;
  loglen: Integer;
  res: DWord;
begin
  if len = 0 then
    exit;
  cr.cpMin := idx;
  cr.cpMax := idx + len;
  SendMessage(RichEditHandle, EM_EXSETSEL, 0, LPARAM(@cr));
  ZeroMemory(@cf, SizeOf(cf));
  cf.cbSize := SizeOf(cf);
  cf.dwMask := fromCF.dwMask;
  res := SendMessage(RichEditHandle, EM_GETCHARFORMAT, SCF_SELECTION, LPARAM(@cf));
  if (res and fromCF.dwMask) = 0 then
  begin
    if len = 2 then
    begin
      // wtf, msdn tells that cf will get the format of the first AnsiChar,
      // and then we have to select it, if format match or second, if not
      // instead we got format of the last AnsiChar... weired
      if (cf.dwEffects and fromCF.dwEffects) = fromCF.dwEffects then
        Inc(cr.cpMin)
      else
        Dec(cr.cpMax);
      SendMessage(RichEditHandle, EM_EXSETSEL, 0, LPARAM(@cr));
      SendMessage(RichEditHandle, EM_SETCHARFORMAT, SCF_SELECTION, LPARAM(@toCF));
    end
    else
    begin
      loglen := len div 2;
      ReplaceCharFormatRange(RichEditHandle, fromCF, toCF, idx, loglen);
      ReplaceCharFormatRange(RichEditHandle, fromCF, toCF, idx + loglen, len - loglen);
    end;
  end
  else if (cf.dwEffects and fromCF.dwEffects) = fromCF.dwEffects then
    SendMessage(RichEditHandle, EM_SETCHARFORMAT, SCF_SELECTION, LPARAM(@toCF));
end;

procedure ReplaceCharFormat(RichEditHandle: THANDLE; const fromCF, toCF: CHARFORMAT2);
begin
  ReplaceCharFormatRange(RichEditHandle,fromCF,toCF,0,GetTextLength(RichEditHandle));
end;


function GetTextRange(RichEditHandle: THANDLE; cpMin,cpMax: Integer): PWideChar;
var
  tr: TextRangeW;
begin
  tr.chrg.cpMin := cpMin;
  tr.chrg.cpMax := cpMax;
  GetMem(Result,(cpMax-cpMin+1)*SizeOf(WideChar));
  tr.lpstrText := Result;

  SendMessageW(RichEditHandle,EM_GETTEXTRANGE,0,LPARAM(@tr));
end;

{ Direct Bitmap to RTF insertion }

function BytesPerScanline(PixelsPerScanline, BitsPerPixel, Alignment: Longint): Longint;
begin
  Dec(Alignment);
  Result := ((PixelsPerScanline * BitsPerPixel) + Alignment) and not Alignment;
  Result := Result div 8;
end;

procedure InitializeBitmapInfoHeader(Bitmap: HBITMAP; var BI: TBitmapInfoHeader; Colors: Integer);
var
  DS: TDIBSection;
  Bytes: Integer;
begin
  DS.dsbmih.biSize := 0;
  Bytes := GetObject(Bitmap, SizeOf(DS), @DS);
  if Bytes = 0 then {InvalidBitmap}
  else if (Bytes >= (sizeof(DS.dsbm) + sizeof(DS.dsbmih))) and
    (DS.dsbmih.biSize >= DWORD(sizeof(DS.dsbmih))) then
    BI := DS.dsbmih
  else
  begin
    FillChar(BI, sizeof(BI), 0);
    with BI, DS.dsbm do
    begin
      biSize := SizeOf(BI);
      biWidth := bmWidth;
      biHeight := bmHeight;
    end;
  end;
  case Colors of
    2: BI.biBitCount := 1;
    3..16:
      begin
        BI.biBitCount := 4;
        BI.biClrUsed := Colors;
      end;
    17..256:
      begin
        BI.biBitCount := 8;
        BI.biClrUsed := Colors;
      end;
  else
    BI.biBitCount := DS.dsbm.bmBitsPixel * DS.dsbm.bmPlanes;
  end;
  BI.biPlanes := 1;
  if BI.biClrImportant > BI.biClrUsed then
    BI.biClrImportant := BI.biClrUsed;
  if BI.biSizeImage = 0 then
    BI.biSizeImage := BytesPerScanLine(BI.biWidth, BI.biBitCount, 32) * Abs(BI.biHeight);
end;

procedure InternalGetDIBSizes(Bitmap: HBITMAP; var InfoHeaderSize: DWORD;
  var ImageSize: DWORD; Colors: Integer);
var
  BI: TBitmapInfoHeader;
begin
  InitializeBitmapInfoHeader(Bitmap, BI, Colors);
  if BI.biBitCount > 8 then
  begin
    InfoHeaderSize := SizeOf(TBitmapInfoHeader);
    if (BI.biCompression and BI_BITFIELDS) <> 0 then
      Inc(InfoHeaderSize, 12);
  end
  else
    if BI.biClrUsed = 0 then
      InfoHeaderSize := SizeOf(TBitmapInfoHeader) +
        SizeOf(TRGBQuad) * (1 shl BI.biBitCount)
    else
      InfoHeaderSize := SizeOf(TBitmapInfoHeader) +
        SizeOf(TRGBQuad) * BI.biClrUsed;
  ImageSize := BI.biSizeImage;
end;

procedure GetDIBSizes(Bitmap: HBITMAP; var InfoHeaderSize: DWORD; var ImageSize: DWORD);
begin
  InternalGetDIBSizes(Bitmap, InfoHeaderSize, ImageSize, 0);
end;

function InternalGetDIB(Bitmap: HBITMAP; Palette: HPALETTE;
  var BitmapInfo; var Bits; Colors: Integer): Boolean;
var
  OldPal: HPALETTE;
  DC: HDC;
begin
  InitializeBitmapInfoHeader(Bitmap, TBitmapInfoHeader(BitmapInfo), Colors);
  OldPal := 0;
  DC := CreateCompatibleDC(0);
  try
    if Palette <> 0 then
    begin
      OldPal := SelectPalette(DC, Palette, False);
      RealizePalette(DC);
    end;
    Result := GetDIBits(DC, Bitmap, 0, TBitmapInfoHeader(BitmapInfo).biHeight, @Bits,
      TBitmapInfo(BitmapInfo), DIB_RGB_COLORS) <> 0;
  finally
    if OldPal <> 0 then SelectPalette(DC, OldPal, False);
    DeleteDC(DC);
  end;
end;

function GetDIB(Bitmap: HBITMAP; Palette: HPALETTE; var BitmapInfo; var Bits): Boolean;
begin
  Result := InternalGetDIB(Bitmap, Palette, BitmapInfo, Bits, 0);
end;

const
  HexDigitChr: array [0..15] of AnsiChar = ('0','1','2','3','4','5','6','7',
                                            '8','9','A','B','C','D','E','F');

function BitmapToRTF(pict: HBITMAP): PAnsiChar;
const
  prefix  = '{\rtf1 {\pict\dibitmap ';
  postfix = ' }}';
var
  tmp, bi, bb, rtf: PAnsiChar;
  bis, bbs: cardinal;
  len,cnt: integer;
begin
  GetDIBSizes(pict, bis, bbs);
  GetMem(bi, bis);
  GetMem(bb, bbs);
  GetDIB(pict, {pict.Palette}0, bi^, bb^);

  len:=(bis+bbs)*2+cardinal(Length(prefix)+Length(postfix))+1;
  GetMem(result,len);

  rtf:=StrCopyE(result,prefix);
  tmp:=bi;
  for cnt := 0 to bis-1 do
  begin
    rtf^ := HexDigitChr[ord(tmp^) shr  4]; inc(rtf);
    rtf^ := HexDigitChr[ord(tmp^) and $F]; inc(rtf);
    inc(tmp);
  end;
  tmp:=bb;
  for cnt := 0 to bbs-1 do
  begin
    rtf^ := HexDigitChr[ord(tmp^) shr  4]; inc(rtf);
    rtf^ := HexDigitChr[ord(tmp^) and $F]; inc(rtf);
    inc(tmp);
  end;
  StrCopy(rtf,postfix);

  FreeMem(bi);
  FreeMem(bb);
end;


initialization
finalization

end.