1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxHtmlParser class (generic parser)
4 // Author: Vaclav Slavik
6 // Copyright: (c) 1999 Vaclav Slavik
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 #include "wx/wxprec.h"
13 #if wxUSE_HTML && wxUSE_STREAMS
24 #include "wx/tokenzr.h"
25 #include "wx/wfstream.h"
27 #include "wx/fontmap.h"
28 #include "wx/html/htmldefs.h"
29 #include "wx/html/htmlpars.h"
30 #include "wx/dynarray.h"
31 #include "wx/arrimpl.cpp"
34 #include "wx/msw/wince/missing.h" // for bsearch()
37 // DLL options compatibility check:
39 WX_CHECK_BUILD_OPTIONS("wxHTML")
41 const wxChar
*wxTRACE_HTML_DEBUG
= _T("htmldebug");
43 //-----------------------------------------------------------------------------
44 // wxHtmlParser helpers
45 //-----------------------------------------------------------------------------
50 wxHtmlTextPiece(int pos
, int lng
) : m_pos(pos
), m_lng(lng
) {}
54 WX_DECLARE_OBJARRAY(wxHtmlTextPiece
, wxHtmlTextPieces
);
55 WX_DEFINE_OBJARRAY(wxHtmlTextPieces
)
57 class wxHtmlParserState
62 wxHtmlTextPieces
*m_textPieces
;
65 wxHtmlParserState
*m_nextState
;
68 //-----------------------------------------------------------------------------
70 //-----------------------------------------------------------------------------
72 IMPLEMENT_ABSTRACT_CLASS(wxHtmlParser
,wxObject
)
74 wxHtmlParser::wxHtmlParser()
75 : wxObject(), m_HandlersHash(wxKEY_STRING
),
76 m_FS(NULL
), m_HandlersStack(NULL
)
78 m_entitiesParser
= new wxHtmlEntitiesParser
;
86 wxHtmlParser::~wxHtmlParser()
88 while (RestoreState()) {}
93 wxList
& tmp
= *m_HandlersStack
;
94 wxList::iterator it
, en
;
95 for( it
= tmp
.begin(), en
= tmp
.end(); it
!= en
; ++it
)
96 delete (wxHashTable
*)*it
;
99 delete m_HandlersStack
;
100 m_HandlersHash
.Clear();
101 WX_CLEAR_LIST(wxList
, m_HandlersList
);
102 delete m_entitiesParser
;
105 wxObject
* wxHtmlParser::Parse(const wxString
& source
)
109 wxObject
*result
= GetProduct();
114 void wxHtmlParser::InitParser(const wxString
& source
)
117 m_stopParsing
= false;
120 void wxHtmlParser::DoneParser()
125 void wxHtmlParser::SetSource(const wxString
& src
)
134 void wxHtmlParser::CreateDOMTree()
136 wxHtmlTagsCache
cache(m_Source
);
137 m_TextPieces
= new wxHtmlTextPieces
;
138 CreateDOMSubTree(NULL
, 0, m_Source
.Length(), &cache
);
142 extern bool wxIsCDATAElement(const wxChar
*tag
);
144 void wxHtmlParser::CreateDOMSubTree(wxHtmlTag
*cur
,
145 int begin_pos
, int end_pos
,
146 wxHtmlTagsCache
*cache
)
148 if (end_pos
<= begin_pos
) return;
152 int textBeginning
= begin_pos
;
154 // If the tag contains CDATA text, we include the text between beginning
155 // and ending tag verbosely. Setting i=end_pos will skip to the very
156 // end of this function where text piece is added, bypassing any child
157 // tags parsing (CDATA element can't have child elements by definition):
158 if (cur
!= NULL
&& wxIsCDATAElement(cur
->GetName().c_str()))
165 c
= m_Source
.GetChar(i
);
169 // add text to m_TextPieces:
170 if (i
- textBeginning
> 0)
172 wxHtmlTextPiece(textBeginning
, i
- textBeginning
));
174 // if it is a comment, skip it:
175 if (i
< end_pos
-6 && m_Source
.GetChar(i
+1) == wxT('!') &&
176 m_Source
.GetChar(i
+2) == wxT('-') &&
177 m_Source
.GetChar(i
+3) == wxT('-'))
179 // Comments begin with "<!--" and end with "--[ \t\r\n]*>"
180 // according to HTML 4.0
185 c
= m_Source
.GetChar(i
++);
186 if ((c
== wxT(' ') || c
== wxT('\n') ||
187 c
== wxT('\r') || c
== wxT('\t')) && dashes
>= 2) {}
188 else if (c
== wxT('>') && dashes
>= 2)
193 else if (c
== wxT('-'))
200 // add another tag to the tree:
201 else if (i
< end_pos
-1 && m_Source
.GetChar(i
+1) != wxT('/'))
205 chd
= new wxHtmlTag(cur
, m_Source
,
206 i
, end_pos
, cache
, m_entitiesParser
);
209 chd
= new wxHtmlTag(NULL
, m_Source
,
210 i
, end_pos
, cache
, m_entitiesParser
);
213 // if this is the first tag to be created make the root
214 // m_Tags point to it:
219 // if there is already a root tag add this tag as
221 chd
->m_Prev
= m_Tags
->GetLastSibling();
222 chd
->m_Prev
->m_Next
= chd
;
226 if (chd
->HasEnding())
228 CreateDOMSubTree(chd
,
229 chd
->GetBeginPos(), chd
->GetEndPos1(),
231 i
= chd
->GetEndPos2();
234 i
= chd
->GetBeginPos();
239 // ... or skip ending tag:
242 while (i
< end_pos
&& m_Source
.GetChar(i
) != wxT('>')) i
++;
249 // add remaining text to m_TextPieces:
250 if (end_pos
- textBeginning
> 0)
252 wxHtmlTextPiece(textBeginning
, end_pos
- textBeginning
));
255 void wxHtmlParser::DestroyDOMTree()
261 t2
= t1
->GetNextSibling();
265 m_Tags
= m_CurTag
= NULL
;
271 void wxHtmlParser::DoParsing()
275 DoParsing(0, m_Source
.Length());
278 void wxHtmlParser::DoParsing(int begin_pos
, int end_pos
)
280 if (end_pos
<= begin_pos
) return;
282 wxHtmlTextPieces
& pieces
= *m_TextPieces
;
283 size_t piecesCnt
= pieces
.GetCount();
285 while (begin_pos
< end_pos
)
287 while (m_CurTag
&& m_CurTag
->GetBeginPos() < begin_pos
)
288 m_CurTag
= m_CurTag
->GetNextTag();
289 while (m_CurTextPiece
< piecesCnt
&&
290 pieces
[m_CurTextPiece
].m_pos
< begin_pos
)
293 if (m_CurTextPiece
< piecesCnt
&&
295 pieces
[m_CurTextPiece
].m_pos
< m_CurTag
->GetBeginPos()))
298 AddText(GetEntitiesParser()->Parse(
299 m_Source
.Mid(pieces
[m_CurTextPiece
].m_pos
,
300 pieces
[m_CurTextPiece
].m_lng
)));
301 begin_pos
= pieces
[m_CurTextPiece
].m_pos
+
302 pieces
[m_CurTextPiece
].m_lng
;
307 if (m_CurTag
->HasEnding())
308 begin_pos
= m_CurTag
->GetEndPos2();
310 begin_pos
= m_CurTag
->GetBeginPos();
311 wxHtmlTag
*t
= m_CurTag
;
312 m_CurTag
= m_CurTag
->GetNextTag();
321 void wxHtmlParser::AddTag(const wxHtmlTag
& tag
)
326 h
= (wxHtmlTagHandler
*) m_HandlersHash
.Get(tag
.GetName());
329 inner
= h
->HandleTag(tag
);
336 DoParsing(tag
.GetBeginPos(), tag
.GetEndPos1());
340 void wxHtmlParser::AddTagHandler(wxHtmlTagHandler
*handler
)
342 wxString
s(handler
->GetSupportedTags());
343 wxStringTokenizer
tokenizer(s
, wxT(", "));
345 while (tokenizer
.HasMoreTokens())
346 m_HandlersHash
.Put(tokenizer
.GetNextToken(), handler
);
348 if (m_HandlersList
.IndexOf(handler
) == wxNOT_FOUND
)
349 m_HandlersList
.Append(handler
);
351 handler
->SetParser(this);
354 void wxHtmlParser::PushTagHandler(wxHtmlTagHandler
*handler
, const wxString
& tags
)
356 wxStringTokenizer
tokenizer(tags
, wxT(", "));
359 if (m_HandlersStack
== NULL
)
361 m_HandlersStack
= new wxList
;
364 m_HandlersStack
->Insert((wxObject
*)new wxHashTable(m_HandlersHash
));
366 while (tokenizer
.HasMoreTokens())
368 key
= tokenizer
.GetNextToken();
369 m_HandlersHash
.Delete(key
);
370 m_HandlersHash
.Put(key
, handler
);
374 void wxHtmlParser::PopTagHandler()
376 wxList::compatibility_iterator first
;
378 if ( !m_HandlersStack
||
380 !(first
= m_HandlersStack
->GetFirst())
382 ((first
= m_HandlersStack
->GetFirst()) == NULL
)
383 #endif // wxUSE_STL/!wxUSE_STL
386 wxLogWarning(_("Warning: attempt to remove HTML tag handler from empty stack."));
389 m_HandlersHash
= *((wxHashTable
*) first
->GetData());
390 delete (wxHashTable
*) first
->GetData();
391 m_HandlersStack
->Erase(first
);
394 void wxHtmlParser::SetSourceAndSaveState(const wxString
& src
)
396 wxHtmlParserState
*s
= new wxHtmlParserState
;
398 s
->m_curTag
= m_CurTag
;
400 s
->m_textPieces
= m_TextPieces
;
401 s
->m_curTextPiece
= m_CurTextPiece
;
402 s
->m_source
= m_Source
;
404 s
->m_nextState
= m_SavedStates
;
411 m_Source
= wxEmptyString
;
416 bool wxHtmlParser::RestoreState()
418 if (!m_SavedStates
) return false;
422 wxHtmlParserState
*s
= m_SavedStates
;
423 m_SavedStates
= s
->m_nextState
;
425 m_CurTag
= s
->m_curTag
;
427 m_TextPieces
= s
->m_textPieces
;
428 m_CurTextPiece
= s
->m_curTextPiece
;
429 m_Source
= s
->m_source
;
435 wxString
wxHtmlParser::GetInnerSource(const wxHtmlTag
& tag
)
437 return GetSource()->Mid(tag
.GetBeginPos(),
438 tag
.GetEndPos1() - tag
.GetBeginPos());
441 //-----------------------------------------------------------------------------
443 //-----------------------------------------------------------------------------
445 IMPLEMENT_ABSTRACT_CLASS(wxHtmlTagHandler
,wxObject
)
447 void wxHtmlTagHandler::ParseInnerSource(const wxString
& source
)
449 // It is safe to temporarily change the source being parsed,
450 // provided we restore the state back after parsing
451 m_Parser
->SetSourceAndSaveState(source
);
452 m_Parser
->DoParsing();
453 m_Parser
->RestoreState();
457 //-----------------------------------------------------------------------------
458 // wxHtmlEntitiesParser
459 //-----------------------------------------------------------------------------
461 IMPLEMENT_DYNAMIC_CLASS(wxHtmlEntitiesParser
,wxObject
)
463 wxHtmlEntitiesParser::wxHtmlEntitiesParser()
464 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
465 : m_conv(NULL
), m_encoding(wxFONTENCODING_SYSTEM
)
470 wxHtmlEntitiesParser::~wxHtmlEntitiesParser()
472 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
477 void wxHtmlEntitiesParser::SetEncoding(wxFontEncoding encoding
)
479 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
480 if (encoding
== m_encoding
)
485 m_encoding
= encoding
;
486 if (m_encoding
== wxFONTENCODING_SYSTEM
)
489 m_conv
= new wxCSConv(wxFontMapper::GetEncodingName(m_encoding
));
495 wxString
wxHtmlEntitiesParser::Parse(const wxString
& input
)
497 const wxChar
*c
, *last
;
498 const wxChar
*in_str
= input
.c_str();
501 output
.reserve(input
.length());
503 for (c
= in_str
, last
= in_str
; *c
!= wxT('\0'); c
++)
508 output
.append(last
, c
- last
);
509 if ( *++c
== wxT('\0') )
513 const wxChar
*ent_s
= c
;
516 for (; (*c
>= wxT('a') && *c
<= wxT('z')) ||
517 (*c
>= wxT('A') && *c
<= wxT('Z')) ||
518 (*c
>= wxT('0') && *c
<= wxT('9')) ||
519 *c
== wxT('_') || *c
== wxT('#'); c
++) {}
520 entity
.append(ent_s
, c
- ent_s
);
521 if (*c
!= wxT(';')) c
--;
523 entity_char
= GetEntityChar(entity
);
525 output
<< entity_char
;
528 output
.append(ent_s
-1, c
-ent_s
+2);
529 wxLogTrace(wxTRACE_HTML_DEBUG
,
530 wxT("Unrecognized HTML entity: '%s'"),
535 if (*last
!= wxT('\0'))
540 struct wxHtmlEntityInfo
546 extern "C" int LINKAGEMODE
wxHtmlEntityCompare(const void *key
, const void *item
)
548 return wxStrcmp((wxChar
*)key
, ((wxHtmlEntityInfo
*)item
)->name
);
552 wxChar
wxHtmlEntitiesParser::GetCharForCode(unsigned code
)
557 wbuf
[0] = (wchar_t)code
;
559 wxMBConv
*conv
= m_conv
? m_conv
: &wxConvLocal
;
560 if (conv
->WC2MB(buf
, wbuf
, 2) == (size_t)-1)
564 return (code
< 256) ? (wxChar
)code
: '?';
569 wxChar
wxHtmlEntitiesParser::GetEntityChar(const wxString
& entity
)
573 if (entity
[0] == wxT('#'))
575 const wxChar
*ent_s
= entity
.c_str();
576 const wxChar
*format
;
578 if (ent_s
[1] == wxT('x') || ent_s
[1] == wxT('X'))
587 if (wxSscanf(ent_s
, format
, &code
) != 1)
592 static wxHtmlEntityInfo substitutions
[] = {
593 { wxT("AElig"),198 },
594 { wxT("Aacute"),193 },
595 { wxT("Acirc"),194 },
596 { wxT("Agrave"),192 },
597 { wxT("Alpha"),913 },
598 { wxT("Aring"),197 },
599 { wxT("Atilde"),195 },
602 { wxT("Ccedil"),199 },
604 { wxT("Dagger"),8225 },
605 { wxT("Delta"),916 },
607 { wxT("Eacute"),201 },
608 { wxT("Ecirc"),202 },
609 { wxT("Egrave"),200 },
610 { wxT("Epsilon"),917 },
613 { wxT("Gamma"),915 },
614 { wxT("Iacute"),205 },
615 { wxT("Icirc"),206 },
616 { wxT("Igrave"),204 },
619 { wxT("Kappa"),922 },
620 { wxT("Lambda"),923 },
622 { wxT("Ntilde"),209 },
624 { wxT("OElig"),338 },
625 { wxT("Oacute"),211 },
626 { wxT("Ocirc"),212 },
627 { wxT("Ograve"),210 },
628 { wxT("Omega"),937 },
629 { wxT("Omicron"),927 },
630 { wxT("Oslash"),216 },
631 { wxT("Otilde"),213 },
635 { wxT("Prime"),8243 },
638 { wxT("Scaron"),352 },
639 { wxT("Sigma"),931 },
640 { wxT("THORN"),222 },
642 { wxT("Theta"),920 },
643 { wxT("Uacute"),218 },
644 { wxT("Ucirc"),219 },
645 { wxT("Ugrave"),217 },
646 { wxT("Upsilon"),933 },
649 { wxT("Yacute"),221 },
652 { wxT("aacute"),225 },
653 { wxT("acirc"),226 },
654 { wxT("acute"),180 },
655 { wxT("aelig"),230 },
656 { wxT("agrave"),224 },
657 { wxT("alefsym"),8501 },
658 { wxT("alpha"),945 },
662 { wxT("aring"),229 },
663 { wxT("asymp"),8776 },
664 { wxT("atilde"),227 },
666 { wxT("bdquo"),8222 },
668 { wxT("brvbar"),166 },
669 { wxT("bull"),8226 },
671 { wxT("ccedil"),231 },
672 { wxT("cedil"),184 },
676 { wxT("clubs"),9827 },
677 { wxT("cong"),8773 },
679 { wxT("crarr"),8629 },
681 { wxT("curren"),164 },
682 { wxT("dArr"),8659 },
683 { wxT("dagger"),8224 },
684 { wxT("darr"),8595 },
686 { wxT("delta"),948 },
687 { wxT("diams"),9830 },
688 { wxT("divide"),247 },
689 { wxT("eacute"),233 },
690 { wxT("ecirc"),234 },
691 { wxT("egrave"),232 },
692 { wxT("empty"),8709 },
693 { wxT("emsp"),8195 },
694 { wxT("ensp"),8194 },
695 { wxT("epsilon"),949 },
696 { wxT("equiv"),8801 },
700 { wxT("euro"),8364 },
701 { wxT("exist"),8707 },
703 { wxT("forall"),8704 },
704 { wxT("frac12"),189 },
705 { wxT("frac14"),188 },
706 { wxT("frac34"),190 },
707 { wxT("frasl"),8260 },
708 { wxT("gamma"),947 },
711 { wxT("hArr"),8660 },
712 { wxT("harr"),8596 },
713 { wxT("hearts"),9829 },
714 { wxT("hellip"),8230 },
715 { wxT("iacute"),237 },
716 { wxT("icirc"),238 },
717 { wxT("iexcl"),161 },
718 { wxT("igrave"),236 },
719 { wxT("image"),8465 },
720 { wxT("infin"),8734 },
723 { wxT("iquest"),191 },
724 { wxT("isin"),8712 },
726 { wxT("kappa"),954 },
727 { wxT("lArr"),8656 },
728 { wxT("lambda"),955 },
729 { wxT("lang"),9001 },
730 { wxT("laquo"),171 },
731 { wxT("larr"),8592 },
732 { wxT("lceil"),8968 },
733 { wxT("ldquo"),8220 },
735 { wxT("lfloor"),8970 },
736 { wxT("lowast"),8727 },
739 { wxT("lsaquo"),8249 },
740 { wxT("lsquo"),8216 },
743 { wxT("mdash"),8212 },
744 { wxT("micro"),181 },
745 { wxT("middot"),183 },
746 { wxT("minus"),8722 },
748 { wxT("nabla"),8711 },
750 { wxT("ndash"),8211 },
754 { wxT("notin"),8713 },
755 { wxT("nsub"),8836 },
756 { wxT("ntilde"),241 },
758 { wxT("oacute"),243 },
759 { wxT("ocirc"),244 },
760 { wxT("oelig"),339 },
761 { wxT("ograve"),242 },
762 { wxT("oline"),8254 },
763 { wxT("omega"),969 },
764 { wxT("omicron"),959 },
765 { wxT("oplus"),8853 },
769 { wxT("oslash"),248 },
770 { wxT("otilde"),245 },
771 { wxT("otimes"),8855 },
774 { wxT("part"),8706 },
775 { wxT("permil"),8240 },
776 { wxT("perp"),8869 },
780 { wxT("plusmn"),177 },
781 { wxT("pound"),163 },
782 { wxT("prime"),8242 },
783 { wxT("prod"),8719 },
784 { wxT("prop"),8733 },
787 { wxT("rArr"),8658 },
788 { wxT("radic"),8730 },
789 { wxT("rang"),9002 },
790 { wxT("raquo"),187 },
791 { wxT("rarr"),8594 },
792 { wxT("rceil"),8969 },
793 { wxT("rdquo"),8221 },
794 { wxT("real"),8476 },
796 { wxT("rfloor"),8971 },
799 { wxT("rsaquo"),8250 },
800 { wxT("rsquo"),8217 },
801 { wxT("sbquo"),8218 },
802 { wxT("scaron"),353 },
803 { wxT("sdot"),8901 },
806 { wxT("sigma"),963 },
807 { wxT("sigmaf"),962 },
809 { wxT("spades"),9824 },
811 { wxT("sube"),8838 },
817 { wxT("supe"),8839 },
818 { wxT("szlig"),223 },
820 { wxT("there4"),8756 },
821 { wxT("theta"),952 },
822 { wxT("thetasym"),977 },
823 { wxT("thinsp"),8201 },
824 { wxT("thorn"),254 },
825 { wxT("tilde"),732 },
826 { wxT("times"),215 },
827 { wxT("trade"),8482 },
828 { wxT("uArr"),8657 },
829 { wxT("uacute"),250 },
830 { wxT("uarr"),8593 },
831 { wxT("ucirc"),251 },
832 { wxT("ugrave"),249 },
834 { wxT("upsih"),978 },
835 { wxT("upsilon"),965 },
837 { wxT("weierp"),8472 },
839 { wxT("yacute"),253 },
844 { wxT("zwnj"),8204 },
846 static size_t substitutions_cnt
= 0;
848 if (substitutions_cnt
== 0)
849 while (substitutions
[substitutions_cnt
].code
!= 0)
852 wxHtmlEntityInfo
*info
= NULL
;
854 // bsearch crashes under WinCE for some reason
856 for (i
= 0; i
< substitutions_cnt
; i
++)
858 if (entity
== substitutions
[i
].name
)
860 info
= & substitutions
[i
];
865 info
= (wxHtmlEntityInfo
*) bsearch(entity
.c_str(), substitutions
,
867 sizeof(wxHtmlEntityInfo
),
868 wxHtmlEntityCompare
);
877 return GetCharForCode(code
);
880 wxFSFile
*wxHtmlParser::OpenURL(wxHtmlURLType
WXUNUSED(type
),
881 const wxString
& url
) const
883 return m_FS
? m_FS
->OpenFile(url
) : NULL
;
888 //-----------------------------------------------------------------------------
889 // wxHtmlParser::ExtractCharsetInformation
890 //-----------------------------------------------------------------------------
892 class wxMetaTagParser
: public wxHtmlParser
895 wxMetaTagParser() { }
897 wxObject
* GetProduct() { return NULL
; }
900 virtual void AddText(const wxChar
* WXUNUSED(txt
)) {}
902 DECLARE_NO_COPY_CLASS(wxMetaTagParser
)
905 class wxMetaTagHandler
: public wxHtmlTagHandler
908 wxMetaTagHandler(wxString
*retval
) : wxHtmlTagHandler(), m_retval(retval
) {}
909 wxString
GetSupportedTags() { return wxT("META,BODY"); }
910 bool HandleTag(const wxHtmlTag
& tag
);
915 DECLARE_NO_COPY_CLASS(wxMetaTagHandler
)
918 bool wxMetaTagHandler::HandleTag(const wxHtmlTag
& tag
)
920 if (tag
.GetName() == _T("BODY"))
922 m_Parser
->StopParsing();
926 if (tag
.HasParam(_T("HTTP-EQUIV")) &&
927 tag
.GetParam(_T("HTTP-EQUIV")).IsSameAs(_T("Content-Type"), false) &&
928 tag
.HasParam(_T("CONTENT")))
930 wxString content
= tag
.GetParam(_T("CONTENT")).Lower();
931 if (content
.Left(19) == _T("text/html; charset="))
933 *m_retval
= content
.Mid(19);
934 m_Parser
->StopParsing();
942 wxString
wxHtmlParser::ExtractCharsetInformation(const wxString
& markup
)
945 wxMetaTagParser
*parser
= new wxMetaTagParser();
948 parser
->AddTagHandler(new wxMetaTagHandler(&charset
));
949 parser
->Parse(markup
);