1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/html/htmlpars.cpp
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"
16 #if wxUSE_HTML && wxUSE_STREAMS
19 #include "wx/dynarray.h"
25 #include "wx/tokenzr.h"
26 #include "wx/wfstream.h"
28 #include "wx/fontmap.h"
29 #include "wx/html/htmldefs.h"
30 #include "wx/html/htmlpars.h"
31 #include "wx/arrimpl.cpp"
34 #include "wx/msw/wince/missing.h" // for bsearch()
37 // DLL options compatibility check:
38 WX_CHECK_BUILD_OPTIONS("wxHTML")
40 const wxChar
*wxTRACE_HTML_DEBUG
= _T("htmldebug");
42 //-----------------------------------------------------------------------------
43 // wxHtmlParser helpers
44 //-----------------------------------------------------------------------------
49 wxHtmlTextPiece(int pos
, int lng
) : m_pos(pos
), m_lng(lng
) {}
53 WX_DECLARE_OBJARRAY(wxHtmlTextPiece
, wxHtmlTextPieces
);
54 WX_DEFINE_OBJARRAY(wxHtmlTextPieces
)
56 class wxHtmlParserState
61 wxHtmlTextPieces
*m_textPieces
;
64 wxHtmlParserState
*m_nextState
;
67 //-----------------------------------------------------------------------------
69 //-----------------------------------------------------------------------------
71 IMPLEMENT_ABSTRACT_CLASS(wxHtmlParser
,wxObject
)
73 wxHtmlParser::wxHtmlParser()
74 : wxObject(), m_HandlersHash(wxKEY_STRING
),
75 m_FS(NULL
), m_HandlersStack(NULL
)
77 m_entitiesParser
= new wxHtmlEntitiesParser
;
85 wxHtmlParser::~wxHtmlParser()
87 while (RestoreState()) {}
92 wxList
& tmp
= *m_HandlersStack
;
93 wxList::iterator it
, en
;
94 for( it
= tmp
.begin(), en
= tmp
.end(); it
!= en
; ++it
)
95 delete (wxHashTable
*)*it
;
98 delete m_HandlersStack
;
99 m_HandlersHash
.Clear();
100 WX_CLEAR_LIST(wxList
, m_HandlersList
);
101 delete m_entitiesParser
;
104 wxObject
* wxHtmlParser::Parse(const wxString
& source
)
108 wxObject
*result
= GetProduct();
113 void wxHtmlParser::InitParser(const wxString
& source
)
116 m_stopParsing
= false;
119 void wxHtmlParser::DoneParser()
124 void wxHtmlParser::SetSource(const wxString
& src
)
133 void wxHtmlParser::CreateDOMTree()
135 wxHtmlTagsCache
cache(m_Source
);
136 m_TextPieces
= new wxHtmlTextPieces
;
137 CreateDOMSubTree(NULL
, 0, m_Source
.length(), &cache
);
141 extern bool wxIsCDATAElement(const wxChar
*tag
);
143 void wxHtmlParser::CreateDOMSubTree(wxHtmlTag
*cur
,
144 int begin_pos
, int end_pos
,
145 wxHtmlTagsCache
*cache
)
147 if (end_pos
<= begin_pos
) return;
151 int textBeginning
= begin_pos
;
153 // If the tag contains CDATA text, we include the text between beginning
154 // and ending tag verbosely. Setting i=end_pos will skip to the very
155 // end of this function where text piece is added, bypassing any child
156 // tags parsing (CDATA element can't have child elements by definition):
157 if (cur
!= NULL
&& wxIsCDATAElement(cur
->GetName().c_str()))
164 c
= m_Source
.GetChar(i
);
168 // add text to m_TextPieces:
169 if (i
- textBeginning
> 0)
171 wxHtmlTextPiece(textBeginning
, i
- textBeginning
));
173 // if it is a comment, skip it:
174 wxString::const_iterator iter
= m_Source
.begin() + i
;
175 if ( SkipCommentTag(iter
, m_Source
.end()) )
178 i
= iter
- m_Source
.begin() + 1; // skip closing '>' too
181 // add another tag to the tree:
182 else if (i
< end_pos
-1 && m_Source
.GetChar(i
+1) != wxT('/'))
186 chd
= new wxHtmlTag(cur
, m_Source
,
187 i
, end_pos
, cache
, m_entitiesParser
);
190 chd
= new wxHtmlTag(NULL
, m_Source
,
191 i
, end_pos
, cache
, m_entitiesParser
);
194 // if this is the first tag to be created make the root
195 // m_Tags point to it:
200 // if there is already a root tag add this tag as
202 chd
->m_Prev
= m_Tags
->GetLastSibling();
203 chd
->m_Prev
->m_Next
= chd
;
207 if (chd
->HasEnding())
209 CreateDOMSubTree(chd
,
210 chd
->GetBeginPos(), chd
->GetEndPos1(),
212 i
= chd
->GetEndPos2();
215 i
= chd
->GetBeginPos();
220 // ... or skip ending tag:
223 while (i
< end_pos
&& m_Source
.GetChar(i
) != wxT('>')) i
++;
230 // add remaining text to m_TextPieces:
231 if (end_pos
- textBeginning
> 0)
233 wxHtmlTextPiece(textBeginning
, end_pos
- textBeginning
));
236 void wxHtmlParser::DestroyDOMTree()
242 t2
= t1
->GetNextSibling();
246 m_Tags
= m_CurTag
= NULL
;
252 void wxHtmlParser::DoParsing()
256 DoParsing(0, m_Source
.length());
259 void wxHtmlParser::DoParsing(int begin_pos
, int end_pos
)
261 if (end_pos
<= begin_pos
) return;
263 wxHtmlTextPieces
& pieces
= *m_TextPieces
;
264 size_t piecesCnt
= pieces
.GetCount();
266 while (begin_pos
< end_pos
)
268 while (m_CurTag
&& m_CurTag
->GetBeginPos() < begin_pos
)
269 m_CurTag
= m_CurTag
->GetNextTag();
270 while (m_CurTextPiece
< piecesCnt
&&
271 pieces
[m_CurTextPiece
].m_pos
< begin_pos
)
274 if (m_CurTextPiece
< piecesCnt
&&
276 pieces
[m_CurTextPiece
].m_pos
< m_CurTag
->GetBeginPos()))
279 AddText(GetEntitiesParser()->Parse(
280 m_Source
.Mid(pieces
[m_CurTextPiece
].m_pos
,
281 pieces
[m_CurTextPiece
].m_lng
)));
282 begin_pos
= pieces
[m_CurTextPiece
].m_pos
+
283 pieces
[m_CurTextPiece
].m_lng
;
288 if (m_CurTag
->HasEnding())
289 begin_pos
= m_CurTag
->GetEndPos2();
291 begin_pos
= m_CurTag
->GetBeginPos();
292 wxHtmlTag
*t
= m_CurTag
;
293 m_CurTag
= m_CurTag
->GetNextTag();
302 void wxHtmlParser::AddTag(const wxHtmlTag
& tag
)
307 h
= (wxHtmlTagHandler
*) m_HandlersHash
.Get(tag
.GetName());
310 inner
= h
->HandleTag(tag
);
317 DoParsing(tag
.GetBeginPos(), tag
.GetEndPos1());
321 void wxHtmlParser::AddTagHandler(wxHtmlTagHandler
*handler
)
323 wxString
s(handler
->GetSupportedTags());
324 wxStringTokenizer
tokenizer(s
, wxT(", "));
326 while (tokenizer
.HasMoreTokens())
327 m_HandlersHash
.Put(tokenizer
.GetNextToken(), handler
);
329 if (m_HandlersList
.IndexOf(handler
) == wxNOT_FOUND
)
330 m_HandlersList
.Append(handler
);
332 handler
->SetParser(this);
335 void wxHtmlParser::PushTagHandler(wxHtmlTagHandler
*handler
, const wxString
& tags
)
337 wxStringTokenizer
tokenizer(tags
, wxT(", "));
340 if (m_HandlersStack
== NULL
)
342 m_HandlersStack
= new wxList
;
345 m_HandlersStack
->Insert((wxObject
*)new wxHashTable(m_HandlersHash
));
347 while (tokenizer
.HasMoreTokens())
349 key
= tokenizer
.GetNextToken();
350 m_HandlersHash
.Delete(key
);
351 m_HandlersHash
.Put(key
, handler
);
355 void wxHtmlParser::PopTagHandler()
357 wxList::compatibility_iterator first
;
359 if ( !m_HandlersStack
||
361 !(first
= m_HandlersStack
->GetFirst())
363 ((first
= m_HandlersStack
->GetFirst()) == NULL
)
364 #endif // wxUSE_STL/!wxUSE_STL
367 wxLogWarning(_("Warning: attempt to remove HTML tag handler from empty stack."));
370 m_HandlersHash
= *((wxHashTable
*) first
->GetData());
371 delete (wxHashTable
*) first
->GetData();
372 m_HandlersStack
->Erase(first
);
375 void wxHtmlParser::SetSourceAndSaveState(const wxString
& src
)
377 wxHtmlParserState
*s
= new wxHtmlParserState
;
379 s
->m_curTag
= m_CurTag
;
381 s
->m_textPieces
= m_TextPieces
;
382 s
->m_curTextPiece
= m_CurTextPiece
;
383 s
->m_source
= m_Source
;
385 s
->m_nextState
= m_SavedStates
;
392 m_Source
= wxEmptyString
;
397 bool wxHtmlParser::RestoreState()
399 if (!m_SavedStates
) return false;
403 wxHtmlParserState
*s
= m_SavedStates
;
404 m_SavedStates
= s
->m_nextState
;
406 m_CurTag
= s
->m_curTag
;
408 m_TextPieces
= s
->m_textPieces
;
409 m_CurTextPiece
= s
->m_curTextPiece
;
410 m_Source
= s
->m_source
;
416 wxString
wxHtmlParser::GetInnerSource(const wxHtmlTag
& tag
)
418 return GetSource()->Mid(tag
.GetBeginPos(),
419 tag
.GetEndPos1() - tag
.GetBeginPos());
422 //-----------------------------------------------------------------------------
424 //-----------------------------------------------------------------------------
426 IMPLEMENT_ABSTRACT_CLASS(wxHtmlTagHandler
,wxObject
)
428 void wxHtmlTagHandler::ParseInnerSource(const wxString
& source
)
430 // It is safe to temporarily change the source being parsed,
431 // provided we restore the state back after parsing
432 m_Parser
->SetSourceAndSaveState(source
);
433 m_Parser
->DoParsing();
434 m_Parser
->RestoreState();
438 //-----------------------------------------------------------------------------
439 // wxHtmlEntitiesParser
440 //-----------------------------------------------------------------------------
442 IMPLEMENT_DYNAMIC_CLASS(wxHtmlEntitiesParser
,wxObject
)
444 wxHtmlEntitiesParser::wxHtmlEntitiesParser()
445 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
446 : m_conv(NULL
), m_encoding(wxFONTENCODING_SYSTEM
)
451 wxHtmlEntitiesParser::~wxHtmlEntitiesParser()
453 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
458 void wxHtmlEntitiesParser::SetEncoding(wxFontEncoding encoding
)
460 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
461 if (encoding
== m_encoding
)
466 m_encoding
= encoding
;
467 if (m_encoding
== wxFONTENCODING_SYSTEM
)
470 m_conv
= new wxCSConv(wxFontMapper::GetEncodingName(m_encoding
));
476 wxString
wxHtmlEntitiesParser::Parse(const wxString
& input
)
478 const wxChar
*c
, *last
;
479 const wxChar
*in_str
= input
.c_str();
482 output
.reserve(input
.length());
484 for (c
= in_str
, last
= in_str
; *c
!= wxT('\0'); c
++)
489 output
.append(last
, c
- last
);
490 if ( *++c
== wxT('\0') )
494 const wxChar
*ent_s
= c
;
497 for (; (*c
>= wxT('a') && *c
<= wxT('z')) ||
498 (*c
>= wxT('A') && *c
<= wxT('Z')) ||
499 (*c
>= wxT('0') && *c
<= wxT('9')) ||
500 *c
== wxT('_') || *c
== wxT('#'); c
++) {}
501 entity
.append(ent_s
, c
- ent_s
);
502 if (*c
!= wxT(';')) c
--;
504 entity_char
= GetEntityChar(entity
);
506 output
<< entity_char
;
509 output
.append(ent_s
-1, c
-ent_s
+2);
510 wxLogTrace(wxTRACE_HTML_DEBUG
,
511 wxT("Unrecognized HTML entity: '%s'"),
516 if (*last
!= wxT('\0'))
521 struct wxHtmlEntityInfo
527 extern "C" int LINKAGEMODE
wxHtmlEntityCompare(const void *key
, const void *item
)
529 return wxStrcmp((wxChar
*)key
, ((wxHtmlEntityInfo
*)item
)->name
);
533 wxChar
wxHtmlEntitiesParser::GetCharForCode(unsigned code
)
538 wbuf
[0] = (wchar_t)code
;
540 wxMBConv
*conv
= m_conv
? m_conv
: &wxConvLocal
;
541 if (conv
->WC2MB(buf
, wbuf
, 2) == (size_t)-1)
545 return (code
< 256) ? (wxChar
)code
: '?';
550 wxChar
wxHtmlEntitiesParser::GetEntityChar(const wxString
& entity
)
554 if (entity
[0] == wxT('#'))
556 const wxChar
*ent_s
= entity
.c_str();
557 const wxChar
*format
;
559 if (ent_s
[1] == wxT('x') || ent_s
[1] == wxT('X'))
568 if (wxSscanf(ent_s
, format
, &code
) != 1)
573 static wxHtmlEntityInfo substitutions
[] = {
574 { wxT("AElig"),198 },
575 { wxT("Aacute"),193 },
576 { wxT("Acirc"),194 },
577 { wxT("Agrave"),192 },
578 { wxT("Alpha"),913 },
579 { wxT("Aring"),197 },
580 { wxT("Atilde"),195 },
583 { wxT("Ccedil"),199 },
585 { wxT("Dagger"),8225 },
586 { wxT("Delta"),916 },
588 { wxT("Eacute"),201 },
589 { wxT("Ecirc"),202 },
590 { wxT("Egrave"),200 },
591 { wxT("Epsilon"),917 },
594 { wxT("Gamma"),915 },
595 { wxT("Iacute"),205 },
596 { wxT("Icirc"),206 },
597 { wxT("Igrave"),204 },
600 { wxT("Kappa"),922 },
601 { wxT("Lambda"),923 },
603 { wxT("Ntilde"),209 },
605 { wxT("OElig"),338 },
606 { wxT("Oacute"),211 },
607 { wxT("Ocirc"),212 },
608 { wxT("Ograve"),210 },
609 { wxT("Omega"),937 },
610 { wxT("Omicron"),927 },
611 { wxT("Oslash"),216 },
612 { wxT("Otilde"),213 },
616 { wxT("Prime"),8243 },
619 { wxT("Scaron"),352 },
620 { wxT("Sigma"),931 },
621 { wxT("THORN"),222 },
623 { wxT("Theta"),920 },
624 { wxT("Uacute"),218 },
625 { wxT("Ucirc"),219 },
626 { wxT("Ugrave"),217 },
627 { wxT("Upsilon"),933 },
630 { wxT("Yacute"),221 },
633 { wxT("aacute"),225 },
634 { wxT("acirc"),226 },
635 { wxT("acute"),180 },
636 { wxT("aelig"),230 },
637 { wxT("agrave"),224 },
638 { wxT("alefsym"),8501 },
639 { wxT("alpha"),945 },
643 { wxT("aring"),229 },
644 { wxT("asymp"),8776 },
645 { wxT("atilde"),227 },
647 { wxT("bdquo"),8222 },
649 { wxT("brvbar"),166 },
650 { wxT("bull"),8226 },
652 { wxT("ccedil"),231 },
653 { wxT("cedil"),184 },
657 { wxT("clubs"),9827 },
658 { wxT("cong"),8773 },
660 { wxT("crarr"),8629 },
662 { wxT("curren"),164 },
663 { wxT("dArr"),8659 },
664 { wxT("dagger"),8224 },
665 { wxT("darr"),8595 },
667 { wxT("delta"),948 },
668 { wxT("diams"),9830 },
669 { wxT("divide"),247 },
670 { wxT("eacute"),233 },
671 { wxT("ecirc"),234 },
672 { wxT("egrave"),232 },
673 { wxT("empty"),8709 },
674 { wxT("emsp"),8195 },
675 { wxT("ensp"),8194 },
676 { wxT("epsilon"),949 },
677 { wxT("equiv"),8801 },
681 { wxT("euro"),8364 },
682 { wxT("exist"),8707 },
684 { wxT("forall"),8704 },
685 { wxT("frac12"),189 },
686 { wxT("frac14"),188 },
687 { wxT("frac34"),190 },
688 { wxT("frasl"),8260 },
689 { wxT("gamma"),947 },
692 { wxT("hArr"),8660 },
693 { wxT("harr"),8596 },
694 { wxT("hearts"),9829 },
695 { wxT("hellip"),8230 },
696 { wxT("iacute"),237 },
697 { wxT("icirc"),238 },
698 { wxT("iexcl"),161 },
699 { wxT("igrave"),236 },
700 { wxT("image"),8465 },
701 { wxT("infin"),8734 },
704 { wxT("iquest"),191 },
705 { wxT("isin"),8712 },
707 { wxT("kappa"),954 },
708 { wxT("lArr"),8656 },
709 { wxT("lambda"),955 },
710 { wxT("lang"),9001 },
711 { wxT("laquo"),171 },
712 { wxT("larr"),8592 },
713 { wxT("lceil"),8968 },
714 { wxT("ldquo"),8220 },
716 { wxT("lfloor"),8970 },
717 { wxT("lowast"),8727 },
720 { wxT("lsaquo"),8249 },
721 { wxT("lsquo"),8216 },
724 { wxT("mdash"),8212 },
725 { wxT("micro"),181 },
726 { wxT("middot"),183 },
727 { wxT("minus"),8722 },
729 { wxT("nabla"),8711 },
731 { wxT("ndash"),8211 },
735 { wxT("notin"),8713 },
736 { wxT("nsub"),8836 },
737 { wxT("ntilde"),241 },
739 { wxT("oacute"),243 },
740 { wxT("ocirc"),244 },
741 { wxT("oelig"),339 },
742 { wxT("ograve"),242 },
743 { wxT("oline"),8254 },
744 { wxT("omega"),969 },
745 { wxT("omicron"),959 },
746 { wxT("oplus"),8853 },
750 { wxT("oslash"),248 },
751 { wxT("otilde"),245 },
752 { wxT("otimes"),8855 },
755 { wxT("part"),8706 },
756 { wxT("permil"),8240 },
757 { wxT("perp"),8869 },
761 { wxT("plusmn"),177 },
762 { wxT("pound"),163 },
763 { wxT("prime"),8242 },
764 { wxT("prod"),8719 },
765 { wxT("prop"),8733 },
768 { wxT("rArr"),8658 },
769 { wxT("radic"),8730 },
770 { wxT("rang"),9002 },
771 { wxT("raquo"),187 },
772 { wxT("rarr"),8594 },
773 { wxT("rceil"),8969 },
774 { wxT("rdquo"),8221 },
775 { wxT("real"),8476 },
777 { wxT("rfloor"),8971 },
780 { wxT("rsaquo"),8250 },
781 { wxT("rsquo"),8217 },
782 { wxT("sbquo"),8218 },
783 { wxT("scaron"),353 },
784 { wxT("sdot"),8901 },
787 { wxT("sigma"),963 },
788 { wxT("sigmaf"),962 },
790 { wxT("spades"),9824 },
792 { wxT("sube"),8838 },
798 { wxT("supe"),8839 },
799 { wxT("szlig"),223 },
801 { wxT("there4"),8756 },
802 { wxT("theta"),952 },
803 { wxT("thetasym"),977 },
804 { wxT("thinsp"),8201 },
805 { wxT("thorn"),254 },
806 { wxT("tilde"),732 },
807 { wxT("times"),215 },
808 { wxT("trade"),8482 },
809 { wxT("uArr"),8657 },
810 { wxT("uacute"),250 },
811 { wxT("uarr"),8593 },
812 { wxT("ucirc"),251 },
813 { wxT("ugrave"),249 },
815 { wxT("upsih"),978 },
816 { wxT("upsilon"),965 },
818 { wxT("weierp"),8472 },
820 { wxT("yacute"),253 },
825 { wxT("zwnj"),8204 },
827 static size_t substitutions_cnt
= 0;
829 if (substitutions_cnt
== 0)
830 while (substitutions
[substitutions_cnt
].code
!= 0)
833 wxHtmlEntityInfo
*info
= NULL
;
835 // bsearch crashes under WinCE for some reason
837 for (i
= 0; i
< substitutions_cnt
; i
++)
839 if (entity
== substitutions
[i
].name
)
841 info
= & substitutions
[i
];
846 info
= (wxHtmlEntityInfo
*) bsearch(entity
.c_str(), substitutions
,
848 sizeof(wxHtmlEntityInfo
),
849 wxHtmlEntityCompare
);
858 return GetCharForCode(code
);
861 wxFSFile
*wxHtmlParser::OpenURL(wxHtmlURLType
WXUNUSED(type
),
862 const wxString
& url
) const
864 return m_FS
? m_FS
->OpenFile(url
) : NULL
;
869 //-----------------------------------------------------------------------------
870 // wxHtmlParser::ExtractCharsetInformation
871 //-----------------------------------------------------------------------------
873 class wxMetaTagParser
: public wxHtmlParser
876 wxMetaTagParser() { }
878 wxObject
* GetProduct() { return NULL
; }
881 virtual void AddText(const wxChar
* WXUNUSED(txt
)) {}
883 DECLARE_NO_COPY_CLASS(wxMetaTagParser
)
886 class wxMetaTagHandler
: public wxHtmlTagHandler
889 wxMetaTagHandler(wxString
*retval
) : wxHtmlTagHandler(), m_retval(retval
) {}
890 wxString
GetSupportedTags() { return wxT("META,BODY"); }
891 bool HandleTag(const wxHtmlTag
& tag
);
896 DECLARE_NO_COPY_CLASS(wxMetaTagHandler
)
899 bool wxMetaTagHandler::HandleTag(const wxHtmlTag
& tag
)
901 if (tag
.GetName() == _T("BODY"))
903 m_Parser
->StopParsing();
907 if (tag
.HasParam(_T("HTTP-EQUIV")) &&
908 tag
.GetParam(_T("HTTP-EQUIV")).IsSameAs(_T("Content-Type"), false) &&
909 tag
.HasParam(_T("CONTENT")))
911 wxString content
= tag
.GetParam(_T("CONTENT")).Lower();
912 if (content
.Left(19) == _T("text/html; charset="))
914 *m_retval
= content
.Mid(19);
915 m_Parser
->StopParsing();
923 wxString
wxHtmlParser::ExtractCharsetInformation(const wxString
& markup
)
926 wxMetaTagParser
*parser
= new wxMetaTagParser();
929 parser
->AddTagHandler(new wxMetaTagHandler(&charset
));
930 parser
->Parse(markup
);
938 wxHtmlParser::SkipCommentTag(wxString::const_iterator
& start
,
939 wxString::const_iterator end
)
941 wxASSERT_MSG( *start
== '<', _T("should be called on the tag start") );
943 wxString::const_iterator p
= start
;
945 // comments begin with "<!--" in HTML 4.0
946 if ( end
- p
< 3 || *++p
!= '!' || *++p
!= '-' || *++p
!= '-' )
948 // not a comment at all
952 // skip the start of the comment tag in any case, if we don't find the
953 // closing tag we should ignore broken markup
956 // comments end with "--[ \t\r\n]*>", i.e. white space is allowed between
957 // comment delimiter and the closing tag character (section 3.2.4 of
958 // http://www.w3.org/TR/html401/)
964 if ( (c
== wxT(' ') || c
== wxT('\n') ||
965 c
== wxT('\r') || c
== wxT('\t')) && dashes
>= 2 )
967 // ignore white space before potential tag end
971 if ( c
== wxT('>') && dashes
>= 2 )
973 // found end of comment