-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathCTextBlock.cpp
741 lines (561 loc) · 15.9 KB
/
CTextBlock.cpp
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
// CTextBlock.cpp
//
// CTextBlock class
// Copyright (c) 2012 by Kronosaur Productions, LLC. All Rights Reserved.
//
// EXAMPLES:
//
// {\rtf This is a line of text.}
// {\rtf This is {\b bold} text.}
// {\rtf This is {\i italic} text.}
// {\rtf This is {\b\i bold and italic} text.}
// {\rtf Use a back-slash (\\) to escape.}
// {\rtf This is a new\nline.}
// {\rtf This is {\f:Tahoma; a typeface.}}
// {\rtf {\f:Tahoma; Nesting {\b works}.}}
// {\rtf {\c:0xffffff; color}}
//
// NOTE: forward slash and backslash may both be used (so we can embbed in C code).
//
// Reserved characters (must be escaped):
//
// \ backslash
// / slash
// { open brace
// } close brace
#include <windows.h>
#include "Alchemy.h"
#include "DirectXUtil.h"
#include <math.h>
#include <stdio.h>
#include "TextFormat.h"
#define CODE_BOLD CONSTLIT("b")
#define CODE_COLOR CONSTLIT("c")
#define CODE_LINE_SPACING CONSTLIT("lineSpacing")
#define CODE_NEW_LINE CONSTLIT("n")
#define CODE_TYPEFACE CONSTLIT("f")
#define CODE_ITALIC CONSTLIT("i")
#define CODE_RTF CONSTLIT("rtf")
#define ERR_BRACE_EXPECTED CONSTLIT("'{' expected.")
#define ERR_SEMI_COLON_EXPECTED CONSTLIT("';' expected.")
#define ERR_INVALID_CODE_TERMINATOR CONSTLIT("Invalid code terminator.")
#define ERR_NULL_CODE CONSTLIT("Null code.")
#define ERR_UNEXPECTED_EOS CONSTLIT("Unexpected end of stream.")
#define ERR_UNKNOWN_CODE CONSTLIT("Unknown code: %s.")
class CRTFParser
{
public:
CRTFParser (const CString &sInput, const IFontTable &FontTable, CTextBlock *pOutput);
bool ParseBlock (const STextFormatDesc &InitFormat, CString *retsError);
private:
void AddSpan (const CString &sText, const STextFormatDesc &Desc, bool bEoP = false);
bool ParseCode (CString *retsCode, CString *retsParam, CString *retsError);
char *m_pInput;
const IFontTable &m_FontTable;
CTextBlock *m_pOutput;
};
void CTextBlock::AddTextSpan (const CString &sText, const STextFormat &Format, bool bEoP)
// AddTextSpan
//
// Adds a text span
{
STextSpan *pSpan = m_Text.Insert();
pSpan->sText = sText;
pSpan->Format = Format;
pSpan->bEoP = bEoP;
}
CString CTextBlock::Escape (const CString &sText)
// Escape
//
// Escapes all reserved characters in sText
{
char *pPos = sText.GetASCIIZPointer();
char *pEndPos = pPos + sText.GetLength();
CString sResult;
char *pDest = NULL;
char *pStart = pPos;
while (pPos < pEndPos)
{
switch (*pPos)
{
case '\\':
case '/':
case '{':
case '}':
{
// If necessary, allocate a resulting buffer (note that we can
// never be larger than twice the length of the original string).
if (pDest == NULL)
pDest = sResult.GetWritePointer(sText.GetLength() * 2);
// Write out the string up to now
char *pSrc = pStart;
while (pSrc < pPos)
*pDest++ = *pSrc++;
// Write out an escaped version of the character
*pDest++ = '\\';
*pDest++ = *pPos;
pStart = pPos + 1;
break;
}
}
pPos++;
}
// If necessary write the remaining string
if (pDest)
{
char *pSrc = pStart;
while (pSrc < pEndPos)
*pDest++ = *pSrc++;
// Truncate
sResult.Truncate((int)(pDest - sResult.GetPointer()));
// Done
return sResult;
}
// If we didn't need to escape anything then we just return the original
// string.
else
return sText;
}
void CTextBlock::Format (const SBlockFormatDesc &BlockFormat)
// Format
//
// Format the text for the given width
{
DEBUG_TRY
int i;
m_Formatted.DeleteAll();
// Keep looping until we've formatted all spans.
STextSpan *pSpan = (m_Text.GetCount() > 0 ? &m_Text[0] : NULL);
STextSpan *pSpanEnd = (pSpan ? pSpan + m_Text.GetCount() : NULL);
TArray<STextSpan> Line;
STextSpan LeftOver;
int y = 0;
int iSpanPos = 0;
int cxLeft = BlockFormat.cxWidth;
bool bLineEnd = false;
bool bLineStart = true;
while (pSpan)
{
// Build up a string with as much of the span as we can fit.
CString sOutput;
char *pOutStart = sOutput.GetWritePointer(pSpan->sText.GetLength());
char *pOut = pOutStart;
char *pPos = pSpan->sText.GetASCIIZPointer() + iSpanPos;
char *pPosEnd = pSpan->sText.GetASCIIZPointer() + pSpan->sText.GetLength();
while (pPos < pPosEnd && !bLineEnd)
{
// Find the next word
char *pStart = pPos;
while (pPos < pPosEnd && *pPos != ' ' && *pPos != '-' && *pPos != '\x97')
pPos++;
// Measure the length of the word.
//
// NOTE: We always use the advance width, even for the last character, because
// otherwise we underestimate the width (sometimes the character width is less than
// the advance width).
int cxWord = pSpan->Format.pFont->MeasureText(CString(pStart, (int)(pPos - pStart), TRUE), NULL, true);
// If the word fits, add it to the output
if (cxWord <= cxLeft || bLineStart)
{
// Add the separator
if (pPos < pPosEnd)
{
cxWord += pSpan->Format.pFont->MeasureText(CString(pPos, 1, TRUE), NULL, true);
pPos++;
}
char *pSrc = pStart;
while (pSrc < pPos)
*pOut++ = *pSrc++;
cxLeft -= cxWord;
bLineStart = false;
// Are we at the end of the span?
if (pPos == pPosEnd)
{
sOutput.Truncate((int)(pOut - pOutStart));
bLineEnd = false;
}
}
// Otherwise, we're done with the line
else
{
bLineEnd = true;
sOutput.Truncate((int)(pOut - pOutStart));
iSpanPos += sOutput.GetLength();
}
}
// At this point:
//
// sOutput is the part of the span that we should add to the line.
// bLineEnd is TRUE if we should end the line in the middle of the span.
// (If FALSE then sOutput is the entire span).
// iSpanPos is the offset into the span where we should continue adding
// (Only valid if bLineEnd is TRUE).
if (!sOutput.IsBlank() || pSpan->bEoP)
{
STextSpan *pNewSpan = Line.Insert();
pNewSpan->bEoP = (!bLineEnd && pSpan->bEoP);
pNewSpan->Format = pSpan->Format;
pNewSpan->sText = sOutput;
}
// If we've hit the end of the line, then we output everything we've
// got in the line to the formatted buffer.
if (bLineEnd || pSpan->bEoP || (pSpan + 1) == pSpanEnd)
{
// Compute metrics for each span and the line as a whole.
int cyLineAscent = 0;
int cxLine = 0;
int cyLine = 0;
int iExtraSpacing = -1;
if (Line.GetCount() == 0)
{
cyLine = pSpan->Format.pFont->GetHeight();
iExtraSpacing = pSpan->Format.iExtraLineSpacing;
}
else
{
for (i = 0; i < Line.GetCount(); i++)
{
// Compute the max ascent of the line.
int cyAscent = Line[i].Format.pFont->GetAscent();
if (cyAscent > cyLineAscent)
cyLineAscent = cyAscent;
// If this is the last span in the line, trim out any trailing
// spaces (since we don't want include trailing spaces for purposes
// of centering, etc.).
if (i == Line.GetCount() - 1)
Line[i].sText = strTrimWhitespace(Line[i].sText, false, true);
// Compute the width of each span, the total width of the line
// and the max height of the line.
int cyHeight;
Line[i].cx = Line[i].Format.pFont->MeasureText(Line[i].sText, &cyHeight);
cxLine += Line[i].cx;
if (cyHeight > cyLine)
cyLine = cyHeight;
// Always take the max
if (Line[i].Format.iExtraLineSpacing != -1 && (iExtraSpacing == -1 || Line[i].Format.iExtraLineSpacing > iExtraSpacing))
iExtraSpacing = Line[i].Format.iExtraLineSpacing;
}
}
// Compute to horz position of the line (based on block alignment)
int x;
if (BlockFormat.iHorzAlign == alignRight && BlockFormat.cxWidth != -1)
x = BlockFormat.cxWidth - cxLine;
else if (BlockFormat.iHorzAlign == alignCenter && BlockFormat.cxWidth != -1)
x = (BlockFormat.cxWidth - cxLine) / 2;
else
x = 0;
// Format all the spans for this line
for (i = 0; i < Line.GetCount(); i++)
{
SFormattedTextSpan *pFormatted = m_Formatted.Insert();
pFormatted->sText = Line[i].sText;
pFormatted->Format = Line[i].Format;
pFormatted->x = x;
pFormatted->y = y + (cyLineAscent - Line[i].Format.pFont->GetAscent());
pFormatted->cx = Line[i].cx;
pFormatted->cy = Line[i].Format.pFont->GetHeight();
// Advance the line width
x += Line[i].cx;
}
// Advance the line
if (iExtraSpacing == -1)
iExtraSpacing = BlockFormat.iExtraLineSpacing;
y += cyLine + iExtraSpacing;
Line.DeleteAll();
cxLeft = BlockFormat.cxWidth;
bLineStart = true;
}
// Next span
if (!bLineEnd)
{
pSpan++;
if (pSpan >= pSpanEnd)
pSpan = NULL;
iSpanPos = 0;
}
bLineEnd = false;
}
DEBUG_CATCH
}
void CTextBlock::GetBounds (RECT *retrcRect)
// GetBounds
//
// Returns the bounding rect
{
int i;
if (m_Formatted.GetCount() == 0)
{
retrcRect->left = 0;
retrcRect->right = 0;
retrcRect->top = 0;
retrcRect->bottom = 0;
return;
}
retrcRect->left = 100000;
retrcRect->right = -100000;
retrcRect->top = 100000;
retrcRect->bottom = -100000;
for (i = 0; i < m_Formatted.GetCount(); i++)
{
SFormattedTextSpan *pSpan = &m_Formatted[i];
if (pSpan->x < retrcRect->left)
retrcRect->left = pSpan->x;
if (pSpan->x + pSpan->cx > retrcRect->right)
retrcRect->right = pSpan->x + pSpan->cx;
if (pSpan->y < retrcRect->top)
retrcRect->top = pSpan->y;
if (pSpan->y + pSpan->cy > retrcRect->bottom)
retrcRect->bottom = pSpan->y + pSpan->cy;
}
}
bool CTextBlock::InitFromRTF (const CString &RTF, const IFontTable &FontTable, const SBlockFormatDesc &BlockFormat, CString *retsError)
// InitFromRTF
//
// Initializes the text block from an RTF stream.
{
m_Text.DeleteAll();
CRTFParser Parser(RTF, FontTable, this);
STextFormatDesc Desc;
Desc.pFont = BlockFormat.DefaultFormat.pFont;
Desc.rgbColor = BlockFormat.DefaultFormat.rgbColor;
Desc.dwOpacity = BlockFormat.DefaultFormat.dwOpacity;
CString sError;
bool bSuccess = Parser.ParseBlock(Desc, &sError);
// If we failed, then use the error as the text
if (!bSuccess)
{
m_Text.DeleteAll();
STextSpan *pText = m_Text.Insert();
pText->sText = sError;
pText->Format.dwOpacity = 255;
pText->Format.rgbColor = CG32bitPixel(255, 255, 0);
pText->Format.pFont = FontTable.GetFont(Desc);
pText->bEoP = false;
}
Format(BlockFormat);
// Done
if (retsError)
*retsError = sError;
return bSuccess;
}
CString CTextBlock::LoadAsRichText (const CString &sText)
// LoadAsRichText
//
// Takes either a RTF string (with "{\rtf...") or a plain string and returns
// a valid RTF string.
{
// If this is already an RTF string, just return it.
if (strStartsWith(sText, CONSTLIT("{\\rtf")) || strStartsWith(sText, CONSTLIT("{/rtf")))
return sText;
// Otherwise, escape the string
return strPatternSubst(CONSTLIT("{\\rtf %s}"), Escape(sText));
}
void CTextBlock::Paint (CG32bitImage &Dest, int x, int y) const
// Paint
//
// Paints the formatted text block.
{
int i;
for (i = 0; i < GetFormattedSpanCount(); i++)
{
const SFormattedTextSpan &Span = GetFormattedSpan(i);
Span.Format.pFont->DrawText(Dest,
x + Span.x,
y + Span.y,
Span.Format.rgbColor,
Span.sText);
}
}
// CRTFParser -----------------------------------------------------------------
CRTFParser::CRTFParser (const CString &sInput, const IFontTable &FontTable, CTextBlock *pOutput) :
m_pInput(sInput.GetASCIIZPointer()),
m_FontTable(FontTable),
m_pOutput(pOutput)
// CRTFParser constructor
{
}
void CRTFParser::AddSpan (const CString &sText, const STextFormatDesc &Desc, bool bEoP)
// AddSpan
//
// Adds a span of text
{
STextFormat Format;
Format.pFont = (Desc.pFont ? Desc.pFont : m_FontTable.GetFont(Desc));
Format.rgbColor = Desc.rgbColor;
Format.dwOpacity = Desc.dwOpacity;
Format.iExtraLineSpacing = Desc.iExtraLineSpacing;
m_pOutput->AddTextSpan(sText, Format, bEoP);
}
bool CRTFParser::ParseBlock (const STextFormatDesc &InitFormat, CString *retsError)
// ParseBlock
//
// Parses a block and leaves the input position at the first character after
// the end of the block.
{
DEBUG_TRY
// Keep track of the current format and text
STextFormatDesc Format = InitFormat;
// If blank, just do an empty line
if (*m_pInput == '\0')
{
AddSpan(NULL_STR, Format);
return true;
}
// Better be the beginning of a block
if (*m_pInput++ != '{')
{
*retsError = ERR_BRACE_EXPECTED;
return false;
}
// Keep looping until we hit the end of the block
bool bBlockStart = true;
while (*m_pInput != '}')
{
// End of stream
if (*m_pInput == '\0')
{
*retsError = ERR_UNEXPECTED_EOS;
return false;
}
// If an escape character then parse an op code
else if (*m_pInput == '\\' || *m_pInput == '/')
{
m_pInput++;
// Parse the code
switch (*m_pInput)
{
case '{':
case '}':
case '\\':
case '/':
AddSpan(CString(m_pInput, 1), Format);
m_pInput++;
break;
case 'n':
AddSpan(NULL_STR, Format, true);
m_pInput++;
break;
default:
{
// If this is the beginning of the block then parse some
// formatting codes.
if (bBlockStart)
{
CString sCode;
CString sParam;
if (!ParseCode(&sCode, &sParam, retsError))
return false;
// Interpret code
if (strEquals(sCode, CODE_BOLD))
Format.bBold = true;
else if (strEquals(sCode, CODE_COLOR))
{
DWORD dwRGB;
if (*sParam.GetASCIIZPointer() == '#')
dwRGB = (DWORD)strToCOLORREF(sParam);
else
dwRGB = (DWORD)strToInt(sParam, 0);
Format.rgbColor = CG32bitPixel(GetRValue(dwRGB), GetGValue(dwRGB), GetBValue(dwRGB));
}
else if (strEquals(sCode, CODE_LINE_SPACING))
{
Format.iExtraLineSpacing = strToInt(sParam, -1);
}
else if (strEquals(sCode, CODE_TYPEFACE))
{
Format.sTypeface = sParam;
Format.pFont = NULL;
}
else if (strEquals(sCode, CODE_ITALIC))
Format.bItalic = true;
else if (strEquals(sCode, CODE_RTF))
;
else
{
*retsError = strPatternSubst(ERR_UNKNOWN_CODE, sCode);
return false;
}
}
else
{
*retsError = strPatternSubst(ERR_UNKNOWN_CODE, CString(m_pInput, 1));
return false;
}
}
}
}
// Special characters
else if (*m_pInput == '\n')
{
AddSpan(NULL_STR, Format, true);
m_pInput++;
}
// If we have an open brace, then we recurse
else if (*m_pInput == '{')
{
if (!ParseBlock(Format, retsError))
return false;
bBlockStart = false;
}
// Otherwise, this is some text
else
{
char *pStart = m_pInput;
// Find the end of the span
while (*m_pInput != '\\' && *m_pInput != '/' && *m_pInput != '{' && *m_pInput != '}' && *m_pInput != '\n' && *m_pInput != '\0')
m_pInput++;
// Add the text as a span
if (pStart != m_pInput)
AddSpan(CString(pStart, (int)(m_pInput - pStart)), Format);
bBlockStart = false;
}
}
m_pInput++;
// Done
return true;
DEBUG_CATCH
}
bool CRTFParser::ParseCode (CString *retsCode, CString *retsParam, CString *retsError)
// ParseCode
//
// Parses an escape code
{
// Parse the code
char *pStart = m_pInput;
while (*m_pInput != ' ' && *m_pInput != '\\' && *m_pInput != '/' && *m_pInput != '}' && *m_pInput != '}' && *m_pInput != ';' && *m_pInput != ':' && *m_pInput != '\0')
m_pInput++;
*retsCode = CString(pStart, (int)(m_pInput - pStart));
if (retsCode->GetLength() == 0)
{
*retsError = ERR_NULL_CODE;
return false;
}
// Do we have a parameter?
if (*m_pInput == ':')
{
m_pInput++;
pStart = m_pInput;
while (*m_pInput != ';' && *m_pInput != '}' && *m_pInput != '}' && *m_pInput != '\\' && *m_pInput != '/' && *m_pInput != ':' && *m_pInput != '\0')
m_pInput++;
if (*m_pInput++ != ';')
{
*retsError = ERR_SEMI_COLON_EXPECTED;
return false;
}
*retsParam = CString(pStart, (int)((m_pInput - 1) - pStart));
}
else
*retsParam = NULL_STR;
// Parse code terminator
if (*m_pInput == ' ')
m_pInput++;
else if (*m_pInput == '\\' || *m_pInput == '/')
;
else
{
*retsError = ERR_INVALID_CODE_TERMINATOR;
return false;
}
// Done
return true;
}