1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxHtmlParser class (generic parser)
4 // Author: Vaclav Slavik
6 // Copyright: (c) 1999 Vaclav Slavik
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
11 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
12 #pragma implementation "htmlpars.h"
15 #include "wx/wxprec.h"
18 #if wxUSE_HTML && wxUSE_STREAMS
29 #include "wx/tokenzr.h"
30 #include "wx/wfstream.h"
32 #include "wx/fontmap.h"
33 #include "wx/html/htmldefs.h"
34 #include "wx/html/htmlpars.h"
35 #include "wx/dynarray.h"
36 #include "wx/arrimpl.cpp"
39 #include "wx/msw/wince/missing.h" // for bsearch()
42 // DLL options compatibility check:
44 WX_CHECK_BUILD_OPTIONS("wxHTML")
46 const wxChar
*wxTRACE_HTML_DEBUG
= _T("htmldebug");
48 //-----------------------------------------------------------------------------
49 // wxHtmlParser helpers
50 //-----------------------------------------------------------------------------
55 wxHtmlTextPiece(int pos
, int lng
) : m_pos(pos
), m_lng(lng
) {}
59 WX_DECLARE_OBJARRAY(wxHtmlTextPiece
, wxHtmlTextPieces
);
60 WX_DEFINE_OBJARRAY(wxHtmlTextPieces
);
62 class wxHtmlParserState
67 wxHtmlTextPieces
*m_textPieces
;
70 wxHtmlParserState
*m_nextState
;
73 //-----------------------------------------------------------------------------
75 //-----------------------------------------------------------------------------
77 IMPLEMENT_ABSTRACT_CLASS(wxHtmlParser
,wxObject
)
79 wxHtmlParser::wxHtmlParser()
80 : wxObject(), m_HandlersHash(wxKEY_STRING
),
81 m_FS(NULL
), m_HandlersStack(NULL
)
83 m_entitiesParser
= new wxHtmlEntitiesParser
;
91 wxHtmlParser::~wxHtmlParser()
93 while (RestoreState()) {}
98 wxList
& tmp
= *m_HandlersStack
;
99 wxList::iterator it
, en
;
100 for( it
= tmp
.begin(), en
= tmp
.end(); it
!= en
; ++it
)
101 delete (wxHashTable
*)*it
;
104 delete m_HandlersStack
;
105 m_HandlersHash
.Clear();
106 WX_CLEAR_LIST(wxList
, m_HandlersList
);
107 delete m_entitiesParser
;
110 wxObject
* wxHtmlParser::Parse(const wxString
& source
)
114 wxObject
*result
= GetProduct();
119 void wxHtmlParser::InitParser(const wxString
& source
)
122 m_stopParsing
= FALSE
;
125 void wxHtmlParser::DoneParser()
130 void wxHtmlParser::SetSource(const wxString
& src
)
139 void wxHtmlParser::CreateDOMTree()
141 wxHtmlTagsCache
cache(m_Source
);
142 m_TextPieces
= new wxHtmlTextPieces
;
143 CreateDOMSubTree(NULL
, 0, m_Source
.Length(), &cache
);
147 extern bool wxIsCDATAElement(const wxChar
*tag
);
149 void wxHtmlParser::CreateDOMSubTree(wxHtmlTag
*cur
,
150 int begin_pos
, int end_pos
,
151 wxHtmlTagsCache
*cache
)
153 if (end_pos
<= begin_pos
) return;
157 int textBeginning
= begin_pos
;
159 // If the tag contains CDATA text, we include the text between beginning
160 // and ending tag verbosely. Setting i=end_pos will skip to the very
161 // end of this function where text piece is added, bypassing any child
162 // tags parsing (CDATA element can't have child elements by definition):
163 if (cur
!= NULL
&& wxIsCDATAElement(cur
->GetName().c_str()))
170 c
= m_Source
.GetChar(i
);
174 // add text to m_TextPieces:
175 if (i
- textBeginning
> 0)
177 wxHtmlTextPiece(textBeginning
, i
- textBeginning
));
179 // if it is a comment, skip it:
180 if (i
< end_pos
-6 && m_Source
.GetChar(i
+1) == wxT('!') &&
181 m_Source
.GetChar(i
+2) == wxT('-') &&
182 m_Source
.GetChar(i
+3) == wxT('-'))
184 // Comments begin with "<!--" and end with "--[ \t\r\n]*>"
185 // according to HTML 4.0
190 c
= m_Source
.GetChar(i
++);
191 if ((c
== wxT(' ') || c
== wxT('\n') ||
192 c
== wxT('\r') || c
== wxT('\t')) && dashes
>= 2) {}
193 else if (c
== wxT('>') && dashes
>= 2)
198 else if (c
== wxT('-'))
205 // add another tag to the tree:
206 else if (i
< end_pos
-1 && m_Source
.GetChar(i
+1) != wxT('/'))
210 chd
= new wxHtmlTag(cur
, m_Source
,
211 i
, end_pos
, cache
, m_entitiesParser
);
214 chd
= new wxHtmlTag(NULL
, m_Source
,
215 i
, end_pos
, cache
, m_entitiesParser
);
218 // if this is the first tag to be created make the root
219 // m_Tags point to it:
224 // if there is already a root tag add this tag as
226 chd
->m_Prev
= m_Tags
->GetLastSibling();
227 chd
->m_Prev
->m_Next
= chd
;
231 if (chd
->HasEnding())
233 CreateDOMSubTree(chd
,
234 chd
->GetBeginPos(), chd
->GetEndPos1(),
236 i
= chd
->GetEndPos2();
239 i
= chd
->GetBeginPos();
244 // ... or skip ending tag:
247 while (i
< end_pos
&& m_Source
.GetChar(i
) != wxT('>')) i
++;
254 // add remaining text to m_TextPieces:
255 if (end_pos
- textBeginning
> 0)
257 wxHtmlTextPiece(textBeginning
, end_pos
- textBeginning
));
260 void wxHtmlParser::DestroyDOMTree()
266 t2
= t1
->GetNextSibling();
270 m_Tags
= m_CurTag
= NULL
;
276 void wxHtmlParser::DoParsing()
280 DoParsing(0, m_Source
.Length());
283 void wxHtmlParser::DoParsing(int begin_pos
, int end_pos
)
285 if (end_pos
<= begin_pos
) return;
287 wxHtmlTextPieces
& pieces
= *m_TextPieces
;
288 size_t piecesCnt
= pieces
.GetCount();
290 while (begin_pos
< end_pos
)
292 while (m_CurTag
&& m_CurTag
->GetBeginPos() < begin_pos
)
293 m_CurTag
= m_CurTag
->GetNextTag();
294 while (m_CurTextPiece
< piecesCnt
&&
295 pieces
[m_CurTextPiece
].m_pos
< begin_pos
)
298 if (m_CurTextPiece
< piecesCnt
&&
300 pieces
[m_CurTextPiece
].m_pos
< m_CurTag
->GetBeginPos()))
303 AddText(GetEntitiesParser()->Parse(
304 m_Source
.Mid(pieces
[m_CurTextPiece
].m_pos
,
305 pieces
[m_CurTextPiece
].m_lng
)));
306 begin_pos
= pieces
[m_CurTextPiece
].m_pos
+
307 pieces
[m_CurTextPiece
].m_lng
;
315 if (m_CurTag
->HasEnding())
316 begin_pos
= m_CurTag
->GetEndPos2();
318 begin_pos
= m_CurTag
->GetBeginPos();
320 wxHtmlTag
*t
= m_CurTag
;
321 m_CurTag
= m_CurTag
->GetNextTag();
330 void wxHtmlParser::AddTag(const wxHtmlTag
& tag
)
335 h
= (wxHtmlTagHandler
*) m_HandlersHash
.Get(tag
.GetName());
338 inner
= h
->HandleTag(tag
);
345 DoParsing(tag
.GetBeginPos(), tag
.GetEndPos1());
349 void wxHtmlParser::AddTagHandler(wxHtmlTagHandler
*handler
)
351 wxString
s(handler
->GetSupportedTags());
352 wxStringTokenizer
tokenizer(s
, wxT(", "));
354 while (tokenizer
.HasMoreTokens())
355 m_HandlersHash
.Put(tokenizer
.GetNextToken(), handler
);
357 if (m_HandlersList
.IndexOf(handler
) == wxNOT_FOUND
)
358 m_HandlersList
.Append(handler
);
360 handler
->SetParser(this);
363 void wxHtmlParser::PushTagHandler(wxHtmlTagHandler
*handler
, wxString tags
)
365 wxStringTokenizer
tokenizer(tags
, wxT(", "));
368 if (m_HandlersStack
== NULL
)
370 m_HandlersStack
= new wxList
;
373 m_HandlersStack
->Insert((wxObject
*)new wxHashTable(m_HandlersHash
));
375 while (tokenizer
.HasMoreTokens())
377 key
= tokenizer
.GetNextToken();
378 m_HandlersHash
.Delete(key
);
379 m_HandlersHash
.Put(key
, handler
);
383 void wxHtmlParser::PopTagHandler()
385 wxList::compatibility_iterator first
;
387 if ( !m_HandlersStack
||
389 !(first
= m_HandlersStack
->GetFirst())
391 ((first
= m_HandlersStack
->GetFirst()) == NULL
)
392 #endif // wxUSE_STL/!wxUSE_STL
395 wxLogWarning(_("Warning: attempt to remove HTML tag handler from empty stack."));
398 m_HandlersHash
= *((wxHashTable
*) first
->GetData());
399 delete (wxHashTable
*) first
->GetData();
400 m_HandlersStack
->Erase(first
);
403 void wxHtmlParser::SetSourceAndSaveState(const wxString
& src
)
405 wxHtmlParserState
*s
= new wxHtmlParserState
;
407 s
->m_curTag
= m_CurTag
;
409 s
->m_textPieces
= m_TextPieces
;
410 s
->m_curTextPiece
= m_CurTextPiece
;
411 s
->m_source
= m_Source
;
413 s
->m_nextState
= m_SavedStates
;
420 m_Source
= wxEmptyString
;
425 bool wxHtmlParser::RestoreState()
427 if (!m_SavedStates
) return FALSE
;
431 wxHtmlParserState
*s
= m_SavedStates
;
432 m_SavedStates
= s
->m_nextState
;
434 m_CurTag
= s
->m_curTag
;
436 m_TextPieces
= s
->m_textPieces
;
437 m_CurTextPiece
= s
->m_curTextPiece
;
438 m_Source
= s
->m_source
;
444 //-----------------------------------------------------------------------------
446 //-----------------------------------------------------------------------------
448 IMPLEMENT_ABSTRACT_CLASS(wxHtmlTagHandler
,wxObject
)
451 //-----------------------------------------------------------------------------
452 // wxHtmlEntitiesParser
453 //-----------------------------------------------------------------------------
455 IMPLEMENT_DYNAMIC_CLASS(wxHtmlEntitiesParser
,wxObject
)
457 wxHtmlEntitiesParser::wxHtmlEntitiesParser()
458 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
459 : m_conv(NULL
), m_encoding(wxFONTENCODING_SYSTEM
)
464 wxHtmlEntitiesParser::~wxHtmlEntitiesParser()
466 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
471 void wxHtmlEntitiesParser::SetEncoding(wxFontEncoding encoding
)
473 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
474 if (encoding
== m_encoding
)
479 m_encoding
= encoding
;
480 if (m_encoding
== wxFONTENCODING_SYSTEM
)
483 m_conv
= new wxCSConv(wxFontMapper::GetEncodingName(m_encoding
));
489 wxString
wxHtmlEntitiesParser::Parse(const wxString
& input
)
491 const wxChar
*c
, *last
;
492 const wxChar
*in_str
= input
.c_str();
495 output
.reserve(input
.length());
497 for (c
= in_str
, last
= in_str
; *c
!= wxT('\0'); c
++)
502 output
.append(last
, c
- last
);
503 if (++c
== wxT('\0')) break;
506 const wxChar
*ent_s
= c
;
509 for (; (*c
>= wxT('a') && *c
<= wxT('z')) ||
510 (*c
>= wxT('A') && *c
<= wxT('Z')) ||
511 (*c
>= wxT('0') && *c
<= wxT('9')) ||
512 *c
== wxT('_') || *c
== wxT('#'); c
++) {}
513 entity
.append(ent_s
, c
- ent_s
);
514 if (*c
!= wxT(';')) c
--;
516 entity_char
= GetEntityChar(entity
);
518 output
<< entity_char
;
521 output
.append(ent_s
-1, c
-ent_s
+2);
522 wxLogTrace(wxTRACE_HTML_DEBUG
,
523 wxT("Unrecognized HTML entity: '%s'"),
528 if (*last
!= wxT('\0'))
533 struct wxHtmlEntityInfo
539 extern "C" int LINKAGEMODE
wxHtmlEntityCompare(const void *key
, const void *item
)
541 return wxStrcmp((wxChar
*)key
, ((wxHtmlEntityInfo
*)item
)->name
);
545 wxChar
wxHtmlEntitiesParser::GetCharForCode(unsigned code
)
550 wbuf
[0] = (wchar_t)code
;
552 wxMBConv
*conv
= m_conv
? m_conv
: &wxConvLocal
;
553 if (conv
->WC2MB(buf
, wbuf
, 2) == (size_t)-1)
557 return (code
< 256) ? (wxChar
)code
: '?';
562 wxChar
wxHtmlEntitiesParser::GetEntityChar(const wxString
& entity
)
566 if (entity
[0] == wxT('#'))
568 const wxChar
*ent_s
= entity
.c_str();
569 const wxChar
*format
;
571 if (ent_s
[1] == wxT('x') || ent_s
[1] == wxT('X'))
580 if (wxSscanf(ent_s
, format
, &code
) != 1)
585 static wxHtmlEntityInfo substitutions
[] = {
586 { wxT("AElig"),198 },
587 { wxT("Aacute"),193 },
588 { wxT("Acirc"),194 },
589 { wxT("Agrave"),192 },
590 { wxT("Alpha"),913 },
591 { wxT("Aring"),197 },
592 { wxT("Atilde"),195 },
595 { wxT("Ccedil"),199 },
597 { wxT("Dagger"),8225 },
598 { wxT("Delta"),916 },
600 { wxT("Eacute"),201 },
601 { wxT("Ecirc"),202 },
602 { wxT("Egrave"),200 },
603 { wxT("Epsilon"),917 },
606 { wxT("Gamma"),915 },
607 { wxT("Iacute"),205 },
608 { wxT("Icirc"),206 },
609 { wxT("Igrave"),204 },
612 { wxT("Kappa"),922 },
613 { wxT("Lambda"),923 },
615 { wxT("Ntilde"),209 },
617 { wxT("OElig"),338 },
618 { wxT("Oacute"),211 },
619 { wxT("Ocirc"),212 },
620 { wxT("Ograve"),210 },
621 { wxT("Omega"),937 },
622 { wxT("Omicron"),927 },
623 { wxT("Oslash"),216 },
624 { wxT("Otilde"),213 },
628 { wxT("Prime"),8243 },
631 { wxT("Scaron"),352 },
632 { wxT("Sigma"),931 },
633 { wxT("THORN"),222 },
635 { wxT("Theta"),920 },
636 { wxT("Uacute"),218 },
637 { wxT("Ucirc"),219 },
638 { wxT("Ugrave"),217 },
639 { wxT("Upsilon"),933 },
642 { wxT("Yacute"),221 },
645 { wxT("aacute"),225 },
646 { wxT("acirc"),226 },
647 { wxT("acute"),180 },
648 { wxT("aelig"),230 },
649 { wxT("agrave"),224 },
650 { wxT("alefsym"),8501 },
651 { wxT("alpha"),945 },
655 { wxT("aring"),229 },
656 { wxT("asymp"),8776 },
657 { wxT("atilde"),227 },
659 { wxT("bdquo"),8222 },
661 { wxT("brvbar"),166 },
662 { wxT("bull"),8226 },
664 { wxT("ccedil"),231 },
665 { wxT("cedil"),184 },
669 { wxT("clubs"),9827 },
670 { wxT("cong"),8773 },
672 { wxT("crarr"),8629 },
674 { wxT("curren"),164 },
675 { wxT("dArr"),8659 },
676 { wxT("dagger"),8224 },
677 { wxT("darr"),8595 },
679 { wxT("delta"),948 },
680 { wxT("diams"),9830 },
681 { wxT("divide"),247 },
682 { wxT("eacute"),233 },
683 { wxT("ecirc"),234 },
684 { wxT("egrave"),232 },
685 { wxT("empty"),8709 },
686 { wxT("emsp"),8195 },
687 { wxT("ensp"),8194 },
688 { wxT("epsilon"),949 },
689 { wxT("equiv"),8801 },
693 { wxT("euro"),8364 },
694 { wxT("exist"),8707 },
696 { wxT("forall"),8704 },
697 { wxT("frac12"),189 },
698 { wxT("frac14"),188 },
699 { wxT("frac34"),190 },
700 { wxT("frasl"),8260 },
701 { wxT("gamma"),947 },
704 { wxT("hArr"),8660 },
705 { wxT("harr"),8596 },
706 { wxT("hearts"),9829 },
707 { wxT("hellip"),8230 },
708 { wxT("iacute"),237 },
709 { wxT("icirc"),238 },
710 { wxT("iexcl"),161 },
711 { wxT("igrave"),236 },
712 { wxT("image"),8465 },
713 { wxT("infin"),8734 },
716 { wxT("iquest"),191 },
717 { wxT("isin"),8712 },
719 { wxT("kappa"),954 },
720 { wxT("lArr"),8656 },
721 { wxT("lambda"),955 },
722 { wxT("lang"),9001 },
723 { wxT("laquo"),171 },
724 { wxT("larr"),8592 },
725 { wxT("lceil"),8968 },
726 { wxT("ldquo"),8220 },
728 { wxT("lfloor"),8970 },
729 { wxT("lowast"),8727 },
732 { wxT("lsaquo"),8249 },
733 { wxT("lsquo"),8216 },
736 { wxT("mdash"),8212 },
737 { wxT("micro"),181 },
738 { wxT("middot"),183 },
739 { wxT("minus"),8722 },
741 { wxT("nabla"),8711 },
743 { wxT("ndash"),8211 },
747 { wxT("notin"),8713 },
748 { wxT("nsub"),8836 },
749 { wxT("ntilde"),241 },
751 { wxT("oacute"),243 },
752 { wxT("ocirc"),244 },
753 { wxT("oelig"),339 },
754 { wxT("ograve"),242 },
755 { wxT("oline"),8254 },
756 { wxT("omega"),969 },
757 { wxT("omicron"),959 },
758 { wxT("oplus"),8853 },
762 { wxT("oslash"),248 },
763 { wxT("otilde"),245 },
764 { wxT("otimes"),8855 },
767 { wxT("part"),8706 },
768 { wxT("permil"),8240 },
769 { wxT("perp"),8869 },
773 { wxT("plusmn"),177 },
774 { wxT("pound"),163 },
775 { wxT("prime"),8242 },
776 { wxT("prod"),8719 },
777 { wxT("prop"),8733 },
780 { wxT("rArr"),8658 },
781 { wxT("radic"),8730 },
782 { wxT("rang"),9002 },
783 { wxT("raquo"),187 },
784 { wxT("rarr"),8594 },
785 { wxT("rceil"),8969 },
786 { wxT("rdquo"),8221 },
787 { wxT("real"),8476 },
789 { wxT("rfloor"),8971 },
792 { wxT("rsaquo"),8250 },
793 { wxT("rsquo"),8217 },
794 { wxT("sbquo"),8218 },
795 { wxT("scaron"),353 },
796 { wxT("sdot"),8901 },
799 { wxT("sigma"),963 },
800 { wxT("sigmaf"),962 },
802 { wxT("spades"),9824 },
804 { wxT("sube"),8838 },
810 { wxT("supe"),8839 },
811 { wxT("szlig"),223 },
813 { wxT("there4"),8756 },
814 { wxT("theta"),952 },
815 { wxT("thetasym"),977 },
816 { wxT("thinsp"),8201 },
817 { wxT("thorn"),254 },
818 { wxT("tilde"),732 },
819 { wxT("times"),215 },
820 { wxT("trade"),8482 },
821 { wxT("uArr"),8657 },
822 { wxT("uacute"),250 },
823 { wxT("uarr"),8593 },
824 { wxT("ucirc"),251 },
825 { wxT("ugrave"),249 },
827 { wxT("upsih"),978 },
828 { wxT("upsilon"),965 },
830 { wxT("weierp"),8472 },
832 { wxT("yacute"),253 },
837 { wxT("zwnj"),8204 },
839 static size_t substitutions_cnt
= 0;
841 if (substitutions_cnt
== 0)
842 while (substitutions
[substitutions_cnt
].code
!= 0)
845 wxHtmlEntityInfo
*info
;
846 info
= (wxHtmlEntityInfo
*) bsearch(entity
.c_str(), substitutions
,
848 sizeof(wxHtmlEntityInfo
),
849 wxHtmlEntityCompare
);
857 return GetCharForCode(code
);
860 wxFSFile
*wxHtmlParser::OpenURL(wxHtmlURLType
WXUNUSED(type
),
861 const wxString
& url
) const
863 return m_FS
? m_FS
->OpenFile(url
) : NULL
;
868 //-----------------------------------------------------------------------------
869 // wxHtmlParser::ExtractCharsetInformation
870 //-----------------------------------------------------------------------------
872 class wxMetaTagParser
: public wxHtmlParser
875 wxMetaTagParser() { }
877 wxObject
* GetProduct() { return NULL
; }
880 virtual void AddText(const wxChar
* WXUNUSED(txt
)) {}
882 DECLARE_NO_COPY_CLASS(wxMetaTagParser
)
885 class wxMetaTagHandler
: public wxHtmlTagHandler
888 wxMetaTagHandler(wxString
*retval
) : wxHtmlTagHandler(), m_retval(retval
) {}
889 wxString
GetSupportedTags() { return wxT("META,BODY"); }
890 bool HandleTag(const wxHtmlTag
& tag
);
895 DECLARE_NO_COPY_CLASS(wxMetaTagHandler
)
898 bool wxMetaTagHandler::HandleTag(const wxHtmlTag
& tag
)
900 if (tag
.GetName() == _T("BODY"))
902 m_Parser
->StopParsing();
906 if (tag
.HasParam(_T("HTTP-EQUIV")) &&
907 tag
.GetParam(_T("HTTP-EQUIV")).IsSameAs(_T("Content-Type"), false) &&
908 tag
.HasParam(_T("CONTENT")))
910 wxString content
= tag
.GetParam(_T("CONTENT")).Lower();
911 if (content
.Left(19) == _T("text/html; charset="))
913 *m_retval
= content
.Mid(19);
914 m_Parser
->StopParsing();
922 wxString
wxHtmlParser::ExtractCharsetInformation(const wxString
& markup
)
925 wxMetaTagParser parser
;
926 parser
.AddTagHandler(new wxMetaTagHandler(&charset
));
927 parser
.Parse(markup
);