-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimpleHtml.h
920 lines (860 loc) · 31.6 KB
/
SimpleHtml.h
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
#if !defined(AFX_SIMPLEHTMLCTRL_H__20020223_765E_434E_641B_0080AD509054__INCLUDED_)
#define AFX_SIMPLEHTMLCTRL_H__20020223_765E_434E_641B_0080AD509054__INCLUDED_
#pragma once
/////////////////////////////////////////////////////////////////////////////
// CSimpleHtmlCtrl - A RTF-based HTML Viewer
//
// Written by Bjarke Viksoe ([email protected])
// Copyright (c) 2002 Bjarke Viksoe.
//
// Note:
// This control handles ASCII text only. It
// will not handle MBCS nor UTF-8 HTML
// correctly.
//
// This code may be used in compiled form in any way you desire. This
// source file may be redistributed by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name is included.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability if it causes any damage to you or your
// computer whatsoever. It's free, so don't hassle me about it.
//
// Beware of bugs.
//
#ifndef __cplusplus
#error WTL requires C++ compilation (use a .cpp suffix)
#endif
#ifndef __ATLAPP_H__
#error SimpleHtmlCtrl.h requires atlapp.h to be included first
#endif
#ifndef __ATLCTRLS_H__
#error SimpleHtmlCtrl.h requires atlctrls.h to be included first
#endif
#if _RICHEDIT_VER < 0x0200
#pragma message("Warning: The SimpleHtmlCtrl is limited without RichEdit Version 2")
#endif
#include "finddlg.h"
/////////////////////////////////////////////////////////////////////////////
// Convert HTML to RTF
class CHtmlToRtf
{
public:
typedef struct LINK {
TCHAR szURL[4096];
int nStart;
int nEnd;
}LINK;
protected:
typedef struct CONTEXT
{
TCHAR szFaceName[LF_FACESIZE];
int lFontSize;
int lTextColor;
int lBackColor;
int lCellSpacing;
int lCellPadding;
int lBorder;
int lLeftIndent;
int lRightIndent;
int lTopIndent;
int lBottomIndent;
}CONTEXT;
CSimpleValArray<LOGFONT> m_aFonts;
CSimpleValArray<COLORREF> m_aColors;
CSimpleValArray<LINK> m_aLinks;
COLORREF m_clrText;
COLORREF m_clrBack;
int m_nCharPos;
bool m_bEndLine;
bool m_bWasSpace;
public:
LPCTSTR Convert(LPCTSTR pstrHTML, LOGFONT lf, COLORREF& clrText, COLORREF& clrBack)
{
// Create a new output buffer
// We assume that we can create a corretly sized output
// buffer before we convert HTML to RTF...
const int SIZE_FACTOR = 2;
size_t nTextSize = _tcslen(pstrHTML);
size_t nSize = nTextSize * SIZE_FACTOR;
if( nSize < 1000 ) nSize = 1000;
LPTSTR pstrBuffer = (LPTSTR) malloc( nSize*sizeof(TCHAR) );
ATLASSERT(pstrBuffer);
// Initialize structures
m_aFonts.RemoveAll();
m_aFonts.Add(lf);
m_aColors.RemoveAll();
m_aColors.Add(clrText);
m_aColors.Add(clrBack);
m_aLinks.RemoveAll();
// Parse HTML and convert it into RTF
LPTSTR pstrDest = pstrBuffer;
m_clrBack = clrBack;
bool bRes = Parse(pstrHTML, pstrDest);
*pstrDest = _T('\0');
ATLASSERT(_tcslen(pstrBuffer) < nSize);
if( !bRes ) {
free(pstrBuffer);
return NULL;
}
clrBack = m_clrBack;
// Construct the actual return buffer
LPTSTR pstrText = (LPTSTR) malloc( nSize*sizeof(TCHAR) );
ATLASSERT(pstrText);
// Prepare RTF document...
pstrDest = pstrText;
AddOutput(pstrDest, _T("{\\rtf1\\ansi"));
// Add fonts
AddOutput(pstrDest, _T("\\deff0{\\fonttbl"));
for( int i=0; i<m_aFonts.GetSize(); i++ ) {
LOGFONT lf = m_aFonts[i];
AddOutputV(pstrDest, _T("{\\f%d\\fnil\\fcharset0 %s;}"), i, lf.lfFaceName);
}
AddOutput(pstrDest, _T("}"));
// Add colors
AddOutput(pstrDest, _T("{\\colortbl ;"));
for(int i=0; i<m_aColors.GetSize(); i++ ) {
COLORREF clr = m_aColors[i];
AddOutputV(pstrDest, _T("\\red%d\\green%d\\blue%d;"),
GetRValue(clr), GetGValue(clr), GetBValue(clr));
}
AddOutput(pstrDest, _T("}"));
// Some other stuff
AddOutput(pstrDest, _T("\\pard\\plain\\tx0"));
AddOutputV(pstrDest, _T("\\fs%d"), GetFontSize(lf.lfHeight));
// Add converted buffer
AddOutput(pstrDest, pstrBuffer);
// Almost done
AddOutput(pstrDest, _T("}"));
*pstrDest = _T('\0');
free(pstrBuffer);
return pstrText;
}
bool GetLink(int iIndex, LINK& link) const
{
if( iIndex<0 || iIndex>=m_aLinks.GetSize() ) return false;
link = m_aLinks[iIndex];
return true;
}
bool Parse(LPCTSTR pszStart, LPTSTR& pstrDest)
{
// This method builds the RTF document based on the input HTML.
// A lot of it is basic conversion, but a few tags require special
// attention. We also keep track of the assumed character-position while
// generating the RTF. This is particular difficult since this is specific
// to the Microsoft RTF-specification implementation. We need to do this
// because we later on must change the text formatting of links (anchor tags).
CSimpleArray<CONTEXT> aContexts;
CONTEXT Context = { 0 };
_tcscpy( Context.szFaceName, m_aFonts[0].lfFaceName );
Context.lFontSize = GetFontSize( m_aFonts[0].lfHeight );
Context.lTextColor = 0;
Context.lBackColor = 1;
Context.lLeftIndent = Context.lRightIndent = Context.lTopIndent = Context.lBottomIndent = 0;
int nCellPos = 0;
long lTwipFactor = (1L * 1440L) / ::GetDeviceCaps(::GetDC(NULL), LOGPIXELSX);
m_bEndLine = false;
m_bWasSpace = true;
m_nCharPos = 0;
LINK Link;
TCHAR szAppendScope[4096]; // Attribute string currently being built
TCHAR szValue[4096]; // Tag value buffer
while( *pszStart ) {
// Add text before next tag
AddText(pstrDest, pszStart);
if( *pszStart == _T('\0') ) return true; // No more tags present?!
ATLASSERT(*pszStart == _T('<'));
pszStart++;
// Extract the complete start-tag
TCHAR szTag[4096];
LPTSTR pszTag = szTag;
while( *pszStart && *pszStart!=_T('>') ) *pszTag++ = *pszStart++;
ATLASSERT(*pszStart == _T('>'));
*pszTag = _T('\0');
pszStart++;
//::CharLowerBuff(szTag, _tcslen(szTag));
// Extract the tag-name
TCHAR szTagName[4096];
LPTSTR pszTagName = szTagName;
pszTag = szTag;
while( *pszTag && (*pszTag == _T('/') || _istalnum(*pszTag)) ) *pszTagName++ = *pszTag++;
*pszTagName = _T('\0');
// Tag attributes starts where tag-name ends
pszTag = szTag + _tcslen(szTagName);
while( _istspace(*pszTag) ) *pszTag++;
// Parse tag...
CONTEXT OldContext = Context; // Store old context (for comparison later)
LPTSTR pszAppendScope = szAppendScope;
bool bNewContext = false; // New Scope defined?
bool bRestoreContext = false; // Closed scope?
bool bHadEndLine = m_bEndLine; // Keep track of EOF for space trimming.
m_bEndLine = false;
if( szTagName[0]!=_T('/') ) {
//
// Open tags
//
if( _tcscmp(szTagName, _T("b")) == 0 || _tcscmp(szTagName, _T("strong")) == 0 ) {
AddOutput(pszAppendScope, _T("\\b1 "));
}
else if( _tcscmp(szTagName, _T("i")) == 0 ) {
AddOutput(pszAppendScope, _T("\\i1 "));
}
else if( _tcscmp(szTagName, _T("u")) == 0 ) {
AddOutput(pszAppendScope, _T("\\ul1 "));
}
else if( _tcscmp(szTagName, _T("br")) == 0 ) {
AddOutput(pszAppendScope, _T("\\line "));
m_nCharPos++;
m_bEndLine = true;
m_bWasSpace = true;
}
else if( _tcscmp(szTagName, _T("p")) == 0 ) {
if( !bHadEndLine ) {
AddOutput(pszAppendScope, _T("\\par"));
m_nCharPos++;
}
AddOutput(pszAppendScope, _T("\\par "));
m_nCharPos++;
m_bEndLine = true;
m_bWasSpace = true;
}
else if( _tcscmp(szTagName, _T("body")) == 0 ) {
if( GetAttribute(pszTag, _T("bgcolor"), szValue) ) {
Context.lBackColor = GetColor(szValue);
// Assign this color to the control's background
m_clrBack = m_aColors[Context.lBackColor];
}
Context.lLeftIndent =
Context.lRightIndent =
Context.lTopIndent =
Context.lBottomIndent = 8;
if( GetAttribute(pszTag, _T("leftmargin"), szValue) ) {
Context.lLeftIndent = GetInteger(szValue);
}
if( GetAttribute(pszTag, _T("rightmargin"), szValue) ) {
Context.lRightIndent = GetInteger(szValue);
}
if( GetAttribute(pszTag, _T("topmargin"), szValue) ) {
Context.lTopIndent = GetInteger(szValue);
}
if( GetAttribute(pszTag, _T("bottommargin"), szValue) ) {
Context.lBottomIndent = GetInteger(szValue);
}
AddOutputV(pszAppendScope, _T("\\margt%d"), Context.lTopIndent * lTwipFactor);
AddOutputV(pszAppendScope, _T("\\margb%d"), Context.lBottomIndent * lTwipFactor);
AddOutputV(pszAppendScope, _T("\\li%d"), Context.lLeftIndent * lTwipFactor);
AddOutputV(pszAppendScope, _T("\\ri%d"), Context.lRightIndent * lTwipFactor);
bNewContext = true;
}
else if( _tcscmp(szTagName, _T("font")) == 0 ) {
if( GetAttribute(pszTag, _T("color"), szValue) ) {
Context.lTextColor = GetColor(szValue);
}
if( GetAttribute(pszTag, _T("size"), szValue) ) {
Context.lFontSize = GetFontSize(szValue);
}
if( GetAttribute(pszTag, _T("face"), szValue) ) {
_tcscpy( Context.szFaceName, szValue );
}
bNewContext = true;
}
else if( _tcscmp(szTagName, _T("a")) == 0 ) {
if( GetAttribute(pszTag, _T("href"), szValue) ) {
// Add the actual URL as a hidden test
Link.nStart = m_nCharPos;
_tcscpy( Link.szURL, szValue );
}
bNewContext = true;
}
else if( _tcscmp(szTagName, _T("span")) == 0 ) {
bNewContext = true;
}
else if( _tcscmp(szTagName, _T("div")) == 0 ) {
if( !bHadEndLine ) {
AddOutput(pszAppendScope, _T("\\par "));
m_nCharPos++;
m_bEndLine = true;
m_bWasSpace = true;
}
if( GetAttribute(pszTag, _T("align"), szValue) ) {
if( _tcscmp(szValue, _T("center")) == 0 ) AddOutput(pszAppendScope, _T("\\qc "));
else if( _tcscmp(szValue, _T("left")) == 0 ) AddOutput(pszAppendScope, _T("\\ql "));
else if( _tcscmp(szValue, _T("right")) == 0 ) AddOutput(pszAppendScope, _T("\\qr "));
else if( _tcscmp(szValue, _T("justify")) == 0 ) AddOutput(pszAppendScope, _T("\\qj "));
}
if( GetAttribute(pszTag, _T("nowrap"), szValue) ) {
AddOutput(pszAppendScope, _T("\\nowwrap "));
}
bNewContext = true;
}
else if( _tcscmp(szTagName, _T("table")) == 0 ) {
Context.lLeftIndent = 0;
Context.lRightIndent = 0;
int lBorder = 0;
if( GetAttribute(pszTag, _T("border"), szValue) ) {
lBorder = GetInteger(szValue);
}
if( GetStyleAttribute(pszTag, _T("table-layout"), szValue) ) {
ATLASSERT(_tcscmp(szValue, _T("fixed")) == 0);
}
AddOutput(pszAppendScope, _T("\\par\\trowd \\trgaph108\\trleft-108"));
AddOutputV(pszAppendScope, _T("\\trbrdrt\\brdrs\\brdrw%d "), lBorder);
AddOutputV(pszAppendScope, _T("\\trbrdrl\\brdrs\\brdrw%d "), lBorder);
AddOutputV(pszAppendScope, _T("\\trbrdrb\\brdrs\\brdrw%d "), lBorder);
AddOutputV(pszAppendScope, _T("\\trbrdrr\\brdrs\\brdrw%d "), lBorder);
nCellPos = 0;
m_nCharPos++;
m_bWasSpace = true;
bNewContext = true;
}
else if( _tcscmp(szTagName, _T("col")) == 0 ) {
int lWidth = 0;
if( GetAttribute(pszTag, _T("width"), szValue) ) {
lWidth = GetInteger(szValue);
}
ATLASSERT(lWidth>0);
nCellPos += lWidth * lTwipFactor;
AddOutput(pszAppendScope, _T("\\clbrdrt\\brdrw15\\brdrs\\clbrdrl\\brdrw15\\brdrs\\clbrdrb\\brdrw15\\brdrs\\clbrdrr\\brdrw15\\brdrs"));
AddOutputV(pszAppendScope, _T("\\cellx%ld"), nCellPos);
m_bWasSpace = true;
}
else if( _tcscmp(szTagName, _T("tr")) == 0 ) {
AddOutput(pszAppendScope, _T("\\intbl "));
m_bWasSpace = true;
}
else if( _tcscmp(szTagName, _T("td")) == 0 ) {
AddOutput(pszAppendScope, _T("\\par "));
m_nCharPos++;
m_bWasSpace = true;
}
// Containers may also include these styles...
if( bNewContext ) {
if( _tcsstr(pszTag, _T("style=")) != NULL ) {
if( GetStyleAttribute(pszTag, _T("color"), szValue) ) {
Context.lTextColor = GetColor(szValue);
}
if( GetStyleAttribute(pszTag, _T("background-color"), szValue) ) {
Context.lBackColor = GetColor(szValue);
}
}
}
}
else {
//
// Closing tags
//
if( _tcscmp(szTagName, _T("/b")) == 0 || _tcscmp(szTagName, _T("/strong")) == 0) {
AddOutput(pszAppendScope, _T("\\b0 "));
}
else if( _tcscmp(szTagName, _T("/i")) == 0 ) {
AddOutput(pszAppendScope, _T("\\i0 "));
}
else if( _tcscmp(szTagName, _T("/u")) == 0 ) {
AddOutput(pszAppendScope, _T("\\ulnone "));
}
else if( _tcscmp(szTagName, _T("/tr")) == 0 ) {
AddOutput(pszAppendScope, _T("\\row "));
m_nCharPos++;
m_bWasSpace = true;
}
else if( _tcscmp(szTagName, _T("/td")) == 0 ) {
AddOutput(pszAppendScope, _T("\\cell "));
m_nCharPos++;
m_bWasSpace = true;
}
else if( _tcscmp(szTagName, _T("/body")) == 0 ) {
bRestoreContext = true;
}
else if( _tcscmp(szTagName, _T("/font")) == 0 ) {
bRestoreContext = true;
}
else if( _tcscmp(szTagName, _T("/a")) == 0 ) {
Link.nEnd = m_nCharPos;
m_aLinks.Add(Link);
//ATLTRACE("Link: %d - %d\n", Link.nStart, Link.nEnd);
bRestoreContext = true;
}
else if( _tcscmp(szTagName, _T("/span")) == 0 ) {
bRestoreContext = true;
}
else if( _tcscmp(szTagName, _T("/div")) == 0 ) {
AddOutput(pszAppendScope, _T("\\par "));
m_nCharPos++;
bRestoreContext = true;
m_bEndLine = true;
m_bWasSpace = true;
}
else if( _tcscmp(szTagName, _T("/table")) == 0 ) {
bRestoreContext = true;
m_bEndLine = true;
m_bWasSpace = true;
}
}
// Appended all we wanted?
*pszAppendScope = _T('\0');
// Keep track of current rendering context
if( bNewContext ) {
// Push new context on stack
aContexts.Add(OldContext);
// Append attributes to output...
AddOutput(pstrDest, _T("{"));
AddOutput(pstrDest, szAppendScope);
}
else if( bRestoreContext ) {
// Pop context from stack
OldContext = Context;
int lLast = aContexts.GetSize()-1;
ATLASSERT(aContexts.GetSize()>0); // unmatched open/close tags
if( aContexts.GetSize() == 0 ) return false;
Context = aContexts[lLast];
aContexts.RemoveAt(lLast);
// Append attributes to output...
AddOutput(pstrDest, szAppendScope);
AddOutput(pstrDest, _T("}\r\n"));
}
else {
// No context change, just append the
// attributes...
AddOutput(pstrDest, szAppendScope);
}
// If context change, we match any changes in rendering and
// and RTF comamnds...
if( bNewContext ) {
bool bChanged = false;
if( OldContext.lTextColor != Context.lTextColor ) {
AddOutputV(pstrDest, _T("\\cf%d"), Context.lTextColor + 1);
bChanged = true;
}
if( OldContext.lBackColor != Context.lBackColor ) {
AddOutputV(pstrDest, _T("\\highlight%d"), Context.lBackColor + 1);
bChanged = true;
}
if( OldContext.lFontSize != Context.lFontSize ) {
AddOutputV(pstrDest, _T("\\fs%d"), Context.lFontSize);
bChanged = true;
}
if( _tcscmp(OldContext.szFaceName, Context.szFaceName)!=0 ) {
AddOutputV(pstrDest, _T("\\f%d"), GetFontFace(Context.szFaceName));
bChanged = true;
}
if( bChanged ) AddOutput(pstrDest, _T(" "));
}
}
return true;
}
void AddText(LPTSTR& pstrDest, LPCTSTR& pszHTML)
{
while( *pszHTML && *pszHTML!=_T('<') ) {
switch( *pszHTML ) {
case _T('&'):
{
static LPCTSTR szPseudo[] =
{
_T(" "), _T("\\~"),
_T("""), _T("\""),
_T("&"), _T("&"),
_T("<"), _T("<"),
_T(">"), _T(">"),
NULL, NULL
};
LPCTSTR* ppstrPseudo = szPseudo;
while( *ppstrPseudo ) {
if( _tcsnicmp(pszHTML, *ppstrPseudo, ::lstrlen(*ppstrPseudo)) == 0 ) {
pszHTML += ::lstrlen(*ppstrPseudo);
AddOutput(pstrDest, *(ppstrPseudo + 1));
m_nCharPos++;
m_bWasSpace = false;
break;
}
ppstrPseudo += 2;
}
ATLASSERT(*ppstrPseudo); // Found a replacement?
}
break;
case _T('\\'):
*pstrDest++ = _T('\\');
*pstrDest++ = _T('\\');
pszHTML++;
m_nCharPos++;
m_bWasSpace = false;
break;
case _T('{'):
*pstrDest++ = _T('\\');
*pstrDest++ = _T('{');
pszHTML++;
m_nCharPos++;
m_bWasSpace = false;
break;
case _T('}'):
*pstrDest++ = _T('\\');
*pstrDest++ = _T('}');
pszHTML++;
m_nCharPos++;
m_bWasSpace = false;
break;
case _T('\t'):
case _T(' '):
// Ignore spaces as long as this is the start of a new line
// Not exactly HTML compatible, but at good try...
if( !m_bEndLine && !m_bWasSpace) {
*pstrDest++ = _T(' ');
m_nCharPos++;
}
pszHTML++;
m_bWasSpace = true;
break;
case _T('\r'):
pszHTML++;
break;
case _T('\n'):
if( !m_bWasSpace ) {
*pstrDest++ = _T(' ');
m_nCharPos++;
}
pszHTML++;
break;
default:
*pstrDest++ = *pszHTML++;
m_nCharPos++;
m_bEndLine = false;
m_bWasSpace = false;
}
}
}
inline void AddOutput(LPTSTR& pstrDest, LPCTSTR pszSrc) const
{
while( *pszSrc ) *pstrDest++ = *pszSrc++;
}
void AddOutputV(LPTSTR& pstrDest, LPCTSTR pszFormat, ...) const
{
va_list argptr;
va_start( argptr, pszFormat );
int nCount = ::wvsprintf( pstrDest, pszFormat, argptr );
va_end( argptr );
pstrDest += nCount;
}
bool GetAttribute(LPCTSTR pszTag, LPCTSTR pszName, LPTSTR pszValue) const
{
*pszValue = _T('\0');
LPCTSTR p = _tcsstr(pszTag, pszName);
if( p==NULL ) return false;
p += _tcslen(pszName);
while( _istspace(*p) ) p++;
if( *p!=_T('=') ) return true;
p++;
while( _istspace(*p) ) p++;
TCHAR c = *p;
switch( c ) {
case _T('\"'):
case _T('\''):
p++;
while( *p && *p!=c ) *pszValue++ = *p++;
break;
default:
while( *p && (_istalnum(*p) || *p == _T('-')) ) *pszValue++ = *p++;
break;
}
*pszValue = _T('\0');
return true;
}
bool GetStyleAttribute(LPCTSTR pszTag, LPCTSTR pszName, LPTSTR pszValue) const
{
// NOTE: The handling of the STYLE attribute is a bit simplistic
// and will only work for well-behaved and simple HTML.
*pszValue = _T('\0');
LPCTSTR p = _tcsstr(pszTag, pszName);
if( p==NULL ) return false;
p += _tcslen(pszName);
while( _istspace(*p) ) p++;
if( *p!=_T(':') ) return false;
ATLASSERT(_tcsstr(pszTag, _T("style="))!=NULL);
p++;
while( _istspace(*p) ) p++;
TCHAR c = *p;
switch( c ) {
case _T('\"'):
case _T('\''):
p++;
while( *p && *p!=c ) *pszValue++ = *p++;
break;
default:
while( *p && (_istalnum(*p) || *p == _T('-')) ) *pszValue++ = *p++;
break;
}
*pszValue = _T('\0');
return true;
}
int GetColor(LPCTSTR pszValue)
{
COLORREF clr;
if( *pszValue == _T('#') ) {
pszValue++;
LPTSTR pstrStop;
DWORD BGR = _tcstol(pszValue, &pstrStop, 16); // convert hex value
clr = RGB( (BGR & 0xFF0000) >> 16, (BGR & 0xFF00) >> 8, BGR & 0xFF);
}
else {
// TODO: Implement more colors-by-name
if( _tcscmp(pszValue, _T("window")) == 0 ) clr = ::GetSysColor(COLOR_WINDOW);
else if( _tcscmp(pszValue, _T("windowtext")) == 0 ) clr = ::GetSysColor(COLOR_WINDOWTEXT);
else if( _tcscmp(pszValue, _T("buttonface")) == 0 ) clr = ::GetSysColor(COLOR_BTNFACE);
else if( _tcscmp(pszValue, _T("buttontext")) == 0 ) clr = ::GetSysColor(COLOR_BTNTEXT);
else if( _tcscmp(pszValue, _T("green")) == 0 ) { DWORD BGR = 0x228B22; clr = RGB( (BGR & 0xFF0000) >> 16, (BGR & 0xFF00) >> 8, BGR & 0xFF);}
else if( _tcscmp(pszValue, _T("blue")) == 0 ) { DWORD BGR = 0x00BFFF; clr = RGB( (BGR & 0xFF0000) >> 16, (BGR & 0xFF00) >> 8, BGR & 0xFF);}
else clr = RGB(0,0,0);
}
int iIndex = m_aColors.Find(clr);
if( iIndex>=0 ) return iIndex;
m_aColors.Add(clr);
return m_aColors.GetSize() - 1;
}
int GetFontFace(LPCTSTR pszValue)
{
for( int i = 0; i < m_aFonts.GetSize(); i++ ) {
if( _tcsicmp(m_aFonts[i].lfFaceName, pszValue) == 0 ) return i;
}
LOGFONT lf = { 0 };
_tcscpy( lf.lfFaceName, pszValue );
m_aFonts.Add(lf);
return m_aColors.GetSize() - 1;
}
int GetFontSize(LPCTSTR pszValue) const
{
int lFontSize = GetInteger(pszValue);
switch( lFontSize ) {
case 1: return 15; // 7.5
case 2: return 20; // 10
case 3: return 24; // 12
case 4: return 27; // 13.5
case 5: return 36; // 18
case 6: return 48; // 24
case 7: return 72; // 36
default: return 24;
}
}
int GetFontSize(int lFontSize) const
{
// Ok, RTF is in half-points, so this is obviously an x2 algorithm.
// But I'll leave it here if you need to customize...
if( lFontSize>=36 ) return 72;
if( lFontSize>=24 ) return 48;
if( lFontSize>=18 ) return 36;
if( lFontSize>=16 ) return 32;
if( lFontSize>=14 ) return 28;
if( lFontSize>=12 ) return 24;
if( lFontSize>=10 ) return 20;
if( lFontSize>=8 ) return 18;
return 24; // default
}
int GetInteger(LPCTSTR pszValue) const
{
return _ttol(pszValue);
}
};
/////////////////////////////////////////////////////////////////////////////
// CSimpleHtmlCtrl - a subclassed RichEdit control
template< class T, class TBase = CRichEditCtrl, class TWinTraits = CControlWinTraits >
class CSimpleHtmlImpl : public CWindowImpl< T, TBase, TWinTraits >,
public CRichEditFindReplaceImpl<T, CFindReplaceDialogWithMessageFilter>
{
protected:
typedef T thisClass;
typedef CRichEditFindReplaceImpl<T, CFindReplaceDialogWithMessageFilter> findReplaceClass;
public:
DECLARE_WND_SUPERCLASS(NULL, TBase::GetWndClassName())
typedef struct RtfStream
{
LPCSTR pstr;
DWORD pos;
}RtfStream;
CHtmlToRtf convert;
COLORREF m_clrText;
COLORREF m_clrBack;
BOOL PreTranslateMessage(MSG* pMsg)
{
// In non Multi-thread SDI cases, CFindReplaceDialogWithMessageFilter will add itself to the
// global message filters list. In our case, we'll call it directly.
if(m_pFindReplaceDialog != NULL)
{
if(m_pFindReplaceDialog->PreTranslateMessage(pMsg))
return TRUE;
}
return FALSE;
}
// Operations
BOOL SubclassWindow(HWND hWnd)
{
ATLASSERT(m_hWnd == NULL);
ATLASSERT(::IsWindow(hWnd));
#ifdef _DEBUG
TCHAR szBuffer[20];
if( ::GetClassName(hWnd, szBuffer, (sizeof(szBuffer)/sizeof(TCHAR))-1) ) {
ATLASSERT(::lstrcmpi(szBuffer, TBase::GetWndClassName()) == 0);
}
#endif
BOOL bRet = CWindowImpl< T, TBase, TWinTraits >::SubclassWindow(hWnd);
if(bRet) _Init();
return bRet;
}
BOOL Load(LPCTSTR pszHTML)
{
ATLASSERT(!::IsBadStringPtr(pszHTML,-1));
// Extract current font, text color and background color...
HFONT hFont = GetFont();
if( hFont==NULL ) hFont = (HFONT) ::GetStockObject(ANSI_VAR_FONT);
LOGFONT lf = { 0 };
::GetObject(hFont, sizeof(LOGFONT), &lf);
CWindowDC dc(m_hWnd);
m_clrText = dc.GetTextColor();
m_clrBack = dc.GetBkColor();
// Convert HTML to RTF
LPTSTR pstrText = (LPTSTR) convert.Convert(pszHTML, lf, m_clrText, m_clrBack);
if( pstrText==NULL ) return FALSE;
// Change the background color
SetBackgroundColor(m_clrBack);
// Stream RTF into control
USES_CONVERSION;
RtfStream st = { T2CA(pstrText), 0 }; // TODO: Don't use inline conversion for large texts
EDITSTREAM es = { 0 };
es.dwCookie = (DWORD_PTR) &st;
es.dwError = 0;
es.pfnCallback = _StreamReadCallback;
// NOTE: If execption handling is enabled for the app, the little ATLTRY macro
// might catch catastrophic errors (GPFs) from the RichEdit control
// when streaming in malformed RTF.
ATLTRY( StreamIn(SF_RTF, es) );
// All done...
free( pstrText );
if(es.dwError != 0)
{
CString msg;
msg.Format(_T("Load html error:%#x"), es.dwError);
MessageBox(msg);
}
_CreateLinks(convert);
return TRUE;
}
BOOL ExtractLink(CHARRANGE chrng, LPTSTR szUrl, UINT cchMax)
{
szUrl[0] = _T('\0');
CHtmlToRtf::LINK link = { 0 };
for( int i = 0; convert.GetLink(i, link); i++ ) {
if( chrng.cpMin >= link.nStart && chrng.cpMax <= link.nEnd ) {
_tcsncpy( szUrl, link.szURL, cchMax);
return TRUE;
}
}
return FALSE;
}
// Implementation
void _Init()
{
// Forgot to load RTF library?
ATLASSERT(::GetModuleHandle(CRichEditCtrl::GetLibraryName())!=NULL);
// Some style that should be set...
//ATLASSERT(GetStyle() & (ES_MULTILINE|ES_AUTOVSCROLL)==(ES_MULTILINE|ES_AUTOVSCROLL));
// Default background color
m_clrBack = ::GetSysColor(COLOR_WINDOW);
// Turn on word-wrapping...
ModifyStyle(ES_AUTOHSCROLL, 0);
SetTargetDevice(NULL, 0);
// We want to have nice URL behaviour
SetEventMask(ENM_SELCHANGE | ENM_LINK);
}
void _CreateLinks(CHtmlToRtf& conv)
{
conv;
#if _RICHEDIT_VER >= 0x0200
// Traverse the collection of links to assign the new display
// state. Links seems to be handled internally in the RichEdit
// control and not by some proprietary RTF tag (must be a first for
// Microsoft...) so we need to manually assign the CFE_LINK attribute.
CHtmlToRtf::LINK link = { 0 };
for( int i = 0; conv.GetLink(i, link); i++ ) {
SetSel(link.nStart, link.nEnd);
CHARFORMAT2 cf;
cf.cbSize = sizeof(cf);
cf.dwMask = CFM_STYLE | CFM_UNDERLINETYPE | CFM_LINK | CFM_UNDERLINE;
cf.dwEffects = CFE_LINK | CFE_UNDERLINE;
cf.bUnderlineType = CFU_UNDERLINE;
SetSelectionCharFormat(cf);
}
SetSel(0,0);
#endif
}
static DWORD CALLBACK _StreamReadCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG FAR *pcb)
{
RtfStream *pS = reinterpret_cast<RtfStream *>(dwCookie);
ATLASSERT(pS);
LPCSTR pstr = pS->pstr + pS->pos;
ATLASSERT(!::IsBadStringPtrA(pstr, -1));
LONG len = ::lstrlenA(pstr);
if( cb>len ) cb = len;
::CopyMemory(pbBuff, pstr, cb);
pS->pos += cb;
*pcb = cb;
return 0;
}
// Overrides from CEditFindReplaceImpl
CFindReplaceDialogWithMessageFilter* CreateFindReplaceDialog(BOOL bFindOnly, // TRUE for Find, FALSE for FindReplace
LPCTSTR lpszFindWhat,
LPCTSTR lpszReplaceWith = NULL,
DWORD dwFlags = FR_DOWN,
HWND hWndParent = NULL)
{
// In non Multi-Threaded SDI cases, we'd pass in the message loop to CFindReplaceDialogWithMessageFilter.
// In our case, we'll call PreTranslateMessage directly from this class.
//CFindReplaceDialogWithMessageFilter* findReplaceDialog =
// new CFindReplaceDialogWithMessageFilter(_Module.GetMessageLoop());
CFindReplaceDialogWithMessageFilter* findReplaceDialog =
new CFindReplaceDialogWithMessageFilter(NULL);
if(findReplaceDialog == NULL)
{
::MessageBeep(MB_ICONHAND);
}
else
{
HWND hWndFindReplace = findReplaceDialog->Create(bFindOnly,
lpszFindWhat, lpszReplaceWith, dwFlags, hWndParent);
if(hWndFindReplace == NULL)
{
delete findReplaceDialog;
findReplaceDialog = NULL;
}
else
{
findReplaceDialog->SetActiveWindow();
findReplaceDialog->ShowWindow(SW_SHOW);
}
}
return findReplaceDialog;
}
DWORD GetFindReplaceDialogFlags() const
{
DWORD dwFlags = FR_HIDEWHOLEWORD;
if(m_bFindDown)
dwFlags |= FR_DOWN;
if(m_bMatchCase)
dwFlags |= FR_MATCHCASE;
return dwFlags;
}
// Message map and handlers
BEGIN_MSG_MAP(CSimpleHtmlCtrl)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
CHAIN_MSG_MAP_ALT(findReplaceClass, 1)
END_MSG_MAP()
LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
{
// First let original control initialize everything
LRESULT lRet = DefWindowProc(uMsg, wParam, lParam);
_Init();
return lRet;
}
};
class CSimpleHtmlCtrl : public CSimpleHtmlImpl<CSimpleHtmlCtrl>
{
public:
DECLARE_WND_SUPERCLASS(_T("WTL_SimpleHtmlCtrl"), GetWndClassName())
};
#endif // !defined(AFX_SIMPLEHTMLCTRL_H__20020223_765E_434E_641B_0080AD509054__INCLUDED_)