1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxHtmlParser class (generic parser)
4 // Author: Vaclav Slavik
6 // Copyright: (c) 1999 Vaclav Slavik
7 // Licence: wxWindows Licence
8 /////////////////////////////////////////////////////////////////////////////
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"
38 //-----------------------------------------------------------------------------
39 // wxHtmlParser helpers
40 //-----------------------------------------------------------------------------
45 wxHtmlTextPiece(int pos
, int lng
) : m_pos(pos
), m_lng(lng
) {}
49 WX_DECLARE_OBJARRAY(wxHtmlTextPiece
, wxHtmlTextPieces
);
50 WX_DEFINE_OBJARRAY(wxHtmlTextPieces
);
52 class wxHtmlParserState
57 wxHtmlTextPieces
*m_textPieces
;
60 wxHtmlParserState
*m_nextState
;
63 //-----------------------------------------------------------------------------
65 //-----------------------------------------------------------------------------
67 IMPLEMENT_ABSTRACT_CLASS(wxHtmlParser
,wxObject
)
69 wxHtmlParser::wxHtmlParser()
70 : wxObject(), m_HandlersHash(wxKEY_STRING
),
71 m_FS(NULL
), m_HandlersStack(NULL
)
73 m_entitiesParser
= new wxHtmlEntitiesParser
;
81 wxHtmlParser::~wxHtmlParser()
83 while (RestoreState()) {}
86 delete m_HandlersStack
;
87 m_HandlersHash
.Clear();
88 m_HandlersList
.DeleteContents(TRUE
);
89 m_HandlersList
.Clear();
90 delete m_entitiesParser
;
93 wxObject
* wxHtmlParser::Parse(const wxString
& source
)
97 wxObject
*result
= GetProduct();
102 void wxHtmlParser::InitParser(const wxString
& source
)
105 m_stopParsing
= FALSE
;
108 void wxHtmlParser::DoneParser()
113 void wxHtmlParser::SetSource(const wxString
& src
)
122 void wxHtmlParser::CreateDOMTree()
124 wxHtmlTagsCache
cache(m_Source
);
125 m_TextPieces
= new wxHtmlTextPieces
;
126 CreateDOMSubTree(NULL
, 0, m_Source
.Length(), &cache
);
130 extern bool wxIsCDATAElement(const wxChar
*tag
);
132 void wxHtmlParser::CreateDOMSubTree(wxHtmlTag
*cur
,
133 int begin_pos
, int end_pos
,
134 wxHtmlTagsCache
*cache
)
136 if (end_pos
<= begin_pos
) return;
140 int textBeginning
= begin_pos
;
142 // If the tag contains CDATA text, we include the text between beginning
143 // and ending tag verbosely. Setting i=end_pos will skip to the very
144 // end of this function where text piece is added, bypassing any child
145 // tags parsing (CDATA element can't have child elements by definition):
146 if (cur
!= NULL
&& wxIsCDATAElement(cur
->GetName().c_str()))
153 c
= m_Source
.GetChar(i
);
157 // add text to m_TextPieces:
158 if (i
- textBeginning
> 0)
160 wxHtmlTextPiece(textBeginning
, i
- textBeginning
));
162 // if it is a comment, skip it:
163 if (i
< end_pos
-6 && m_Source
.GetChar(i
+1) == wxT('!') &&
164 m_Source
.GetChar(i
+2) == wxT('-') &&
165 m_Source
.GetChar(i
+3) == wxT('-'))
167 // Comments begin with "<!--" and end with "--[ \t\r\n]*>"
168 // according to HTML 4.0
173 c
= m_Source
.GetChar(i
++);
174 if ((c
== wxT(' ') || c
== wxT('\n') ||
175 c
== wxT('\r') || c
== wxT('\t')) && dashes
>= 2) {}
176 else if (c
== wxT('>') && dashes
>= 2)
181 else if (c
== wxT('-'))
188 // add another tag to the tree:
189 else if (i
< end_pos
-1 && m_Source
.GetChar(i
+1) != wxT('/'))
193 chd
= new wxHtmlTag(cur
, m_Source
,
194 i
, end_pos
, cache
, m_entitiesParser
);
197 chd
= new wxHtmlTag(NULL
, m_Source
,
198 i
, end_pos
, cache
, m_entitiesParser
);
201 // if this is the first tag to be created make the root
202 // m_Tags point to it:
207 // if there is already a root tag add this tag as
209 chd
->m_Prev
= m_Tags
->GetLastSibling();
210 chd
->m_Prev
->m_Next
= chd
;
214 if (chd
->HasEnding())
216 CreateDOMSubTree(chd
,
217 chd
->GetBeginPos(), chd
->GetEndPos1(),
219 i
= chd
->GetEndPos2();
222 i
= chd
->GetBeginPos();
227 // ... or skip ending tag:
230 while (i
< end_pos
&& m_Source
.GetChar(i
) != wxT('>')) i
++;
237 // add remaining text to m_TextPieces:
238 if (end_pos
- textBeginning
> 0)
240 wxHtmlTextPiece(textBeginning
, end_pos
- textBeginning
));
243 void wxHtmlParser::DestroyDOMTree()
249 t2
= t1
->GetNextSibling();
253 m_Tags
= m_CurTag
= NULL
;
259 void wxHtmlParser::DoParsing()
263 DoParsing(0, m_Source
.Length());
266 void wxHtmlParser::DoParsing(int begin_pos
, int end_pos
)
268 if (end_pos
<= begin_pos
) return;
270 wxHtmlTextPieces
& pieces
= *m_TextPieces
;
271 size_t piecesCnt
= pieces
.GetCount();
273 while (begin_pos
< end_pos
)
275 while (m_CurTag
&& m_CurTag
->GetBeginPos() < begin_pos
)
276 m_CurTag
= m_CurTag
->GetNextTag();
277 while (m_CurTextPiece
< piecesCnt
&&
278 pieces
[m_CurTextPiece
].m_pos
< begin_pos
)
281 if (m_CurTextPiece
< piecesCnt
&&
283 pieces
[m_CurTextPiece
].m_pos
< m_CurTag
->GetBeginPos()))
286 AddText(GetEntitiesParser()->Parse(
287 m_Source
.Mid(pieces
[m_CurTextPiece
].m_pos
,
288 pieces
[m_CurTextPiece
].m_lng
)));
289 begin_pos
= pieces
[m_CurTextPiece
].m_pos
+
290 pieces
[m_CurTextPiece
].m_lng
;
298 if (m_CurTag
->HasEnding())
299 begin_pos
= m_CurTag
->GetEndPos2();
301 begin_pos
= m_CurTag
->GetBeginPos();
303 wxHtmlTag
*t
= m_CurTag
;
304 m_CurTag
= m_CurTag
->GetNextTag();
313 void wxHtmlParser::AddTag(const wxHtmlTag
& tag
)
318 h
= (wxHtmlTagHandler
*) m_HandlersHash
.Get(tag
.GetName());
321 inner
= h
->HandleTag(tag
);
328 DoParsing(tag
.GetBeginPos(), tag
.GetEndPos1());
332 void wxHtmlParser::AddTagHandler(wxHtmlTagHandler
*handler
)
334 wxString
s(handler
->GetSupportedTags());
335 wxStringTokenizer
tokenizer(s
, wxT(", "));
337 while (tokenizer
.HasMoreTokens())
338 m_HandlersHash
.Put(tokenizer
.GetNextToken(), handler
);
340 if (m_HandlersList
.IndexOf(handler
) == wxNOT_FOUND
)
341 m_HandlersList
.Append(handler
);
343 handler
->SetParser(this);
346 void wxHtmlParser::PushTagHandler(wxHtmlTagHandler
*handler
, wxString tags
)
348 wxStringTokenizer
tokenizer(tags
, wxT(", "));
351 if (m_HandlersStack
== NULL
)
353 m_HandlersStack
= new wxList
;
354 m_HandlersStack
->DeleteContents(TRUE
);
357 m_HandlersStack
->Insert(new wxHashTable(m_HandlersHash
));
359 while (tokenizer
.HasMoreTokens())
361 key
= tokenizer
.GetNextToken();
362 m_HandlersHash
.Delete(key
);
363 m_HandlersHash
.Put(key
, handler
);
367 void wxHtmlParser::PopTagHandler()
371 if (m_HandlersStack
== NULL
||
372 (first
= m_HandlersStack
->GetFirst()) == NULL
)
374 wxLogWarning(_("Warning: attempt to remove HTML tag handler from empty stack."));
377 m_HandlersHash
= *((wxHashTable
*) first
->GetData());
378 m_HandlersStack
->DeleteNode(first
);
381 void wxHtmlParser::SetSourceAndSaveState(const wxString
& src
)
383 wxHtmlParserState
*s
= new wxHtmlParserState
;
385 s
->m_curTag
= m_CurTag
;
387 s
->m_textPieces
= m_TextPieces
;
388 s
->m_curTextPiece
= m_CurTextPiece
;
389 s
->m_source
= m_Source
;
391 s
->m_nextState
= m_SavedStates
;
398 m_Source
= wxEmptyString
;
403 bool wxHtmlParser::RestoreState()
405 if (!m_SavedStates
) return FALSE
;
409 wxHtmlParserState
*s
= m_SavedStates
;
410 m_SavedStates
= s
->m_nextState
;
412 m_CurTag
= s
->m_curTag
;
414 m_TextPieces
= s
->m_textPieces
;
415 m_CurTextPiece
= s
->m_curTextPiece
;
416 m_Source
= s
->m_source
;
422 //-----------------------------------------------------------------------------
424 //-----------------------------------------------------------------------------
426 IMPLEMENT_ABSTRACT_CLASS(wxHtmlTagHandler
,wxObject
)
429 //-----------------------------------------------------------------------------
430 // wxHtmlEntitiesParser
431 //-----------------------------------------------------------------------------
433 IMPLEMENT_DYNAMIC_CLASS(wxHtmlEntitiesParser
,wxObject
)
435 wxHtmlEntitiesParser::wxHtmlEntitiesParser()
436 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
437 : m_conv(NULL
), m_encoding(wxFONTENCODING_SYSTEM
)
442 wxHtmlEntitiesParser::~wxHtmlEntitiesParser()
444 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
449 void wxHtmlEntitiesParser::SetEncoding(wxFontEncoding encoding
)
451 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
452 if (encoding
== m_encoding
)
457 m_encoding
= encoding
;
458 if (m_encoding
== wxFONTENCODING_SYSTEM
)
461 m_conv
= new wxCSConv(wxFontMapper::GetEncodingName(m_encoding
));
467 wxString
wxHtmlEntitiesParser::Parse(const wxString
& input
)
469 const wxChar
*c
, *last
;
470 const wxChar
*in_str
= input
.c_str();
473 output
.reserve(input
.length());
475 for (c
= in_str
, last
= in_str
; *c
!= wxT('\0'); c
++)
480 output
.append(last
, c
- last
);
481 if (++c
== wxT('\0')) break;
484 const wxChar
*ent_s
= c
;
487 for (; (*c
>= wxT('a') && *c
<= wxT('z')) ||
488 (*c
>= wxT('A') && *c
<= wxT('Z')) ||
489 (*c
>= wxT('0') && *c
<= wxT('9')) ||
490 *c
== wxT('_') || *c
== wxT('#'); c
++) {}
491 entity
.append(ent_s
, c
- ent_s
);
492 if (*c
!= wxT(';')) c
--;
494 entity_char
= GetEntityChar(entity
);
496 output
<< entity_char
;
499 output
.append(ent_s
-1, c
-ent_s
+2);
500 wxLogDebug(wxT("Unrecognized HTML entity: '%s'"), entity
.c_str());
504 if (*last
!= wxT('\0'))
509 struct wxHtmlEntityInfo
515 extern "C" int LINKAGEMODE
wxHtmlEntityCompare(const void *key
, const void *item
)
517 return wxStrcmp((wxChar
*)key
, ((wxHtmlEntityInfo
*)item
)->name
);
521 wxChar
wxHtmlEntitiesParser::GetCharForCode(unsigned code
)
526 wbuf
[0] = (wchar_t)code
;
528 wxMBConv
*conv
= m_conv
? m_conv
: &wxConvLocal
;
529 if (conv
->WC2MB(buf
, wbuf
, 2) == (size_t)-1)
533 return (code
< 256) ? (wxChar
)code
: '?';
538 wxChar
wxHtmlEntitiesParser::GetEntityChar(const wxString
& entity
)
542 if (entity
[0] == wxT('#'))
544 const wxChar
*ent_s
= entity
.c_str();
545 const wxChar
*format
;
547 if (ent_s
[1] == wxT('x') || ent_s
[1] == wxT('X'))
556 if (wxSscanf(ent_s
, format
, &code
) != 1)
561 static wxHtmlEntityInfo substitutions
[] = {
562 { wxT("AElig"),198 },
563 { wxT("Aacute"),193 },
564 { wxT("Acirc"),194 },
565 { wxT("Agrave"),192 },
566 { wxT("Alpha"),913 },
567 { wxT("Aring"),197 },
568 { wxT("Atilde"),195 },
571 { wxT("Ccedil"),199 },
573 { wxT("Dagger"),8225 },
574 { wxT("Delta"),916 },
576 { wxT("Eacute"),201 },
577 { wxT("Ecirc"),202 },
578 { wxT("Egrave"),200 },
579 { wxT("Epsilon"),917 },
582 { wxT("Gamma"),915 },
583 { wxT("Iacute"),205 },
584 { wxT("Icirc"),206 },
585 { wxT("Igrave"),204 },
588 { wxT("Kappa"),922 },
589 { wxT("Lambda"),923 },
591 { wxT("Ntilde"),209 },
593 { wxT("OElig"),338 },
594 { wxT("Oacute"),211 },
595 { wxT("Ocirc"),212 },
596 { wxT("Ograve"),210 },
597 { wxT("Omega"),937 },
598 { wxT("Omicron"),927 },
599 { wxT("Oslash"),216 },
600 { wxT("Otilde"),213 },
604 { wxT("Prime"),8243 },
607 { wxT("Scaron"),352 },
608 { wxT("Sigma"),931 },
609 { wxT("THORN"),222 },
611 { wxT("Theta"),920 },
612 { wxT("Uacute"),218 },
613 { wxT("Ucirc"),219 },
614 { wxT("Ugrave"),217 },
615 { wxT("Upsilon"),933 },
618 { wxT("Yacute"),221 },
621 { wxT("aacute"),225 },
622 { wxT("acirc"),226 },
623 { wxT("acute"),180 },
624 { wxT("aelig"),230 },
625 { wxT("agrave"),224 },
626 { wxT("alefsym"),8501 },
627 { wxT("alpha"),945 },
631 { wxT("aring"),229 },
632 { wxT("asymp"),8776 },
633 { wxT("atilde"),227 },
635 { wxT("bdquo"),8222 },
637 { wxT("brvbar"),166 },
638 { wxT("bull"),8226 },
640 { wxT("ccedil"),231 },
641 { wxT("cedil"),184 },
645 { wxT("clubs"),9827 },
646 { wxT("cong"),8773 },
648 { wxT("crarr"),8629 },
650 { wxT("curren"),164 },
651 { wxT("dArr"),8659 },
652 { wxT("dagger"),8224 },
653 { wxT("darr"),8595 },
655 { wxT("delta"),948 },
656 { wxT("diams"),9830 },
657 { wxT("divide"),247 },
658 { wxT("eacute"),233 },
659 { wxT("ecirc"),234 },
660 { wxT("egrave"),232 },
661 { wxT("empty"),8709 },
662 { wxT("emsp"),8195 },
663 { wxT("ensp"),8194 },
664 { wxT("epsilon"),949 },
665 { wxT("equiv"),8801 },
669 { wxT("euro"),8364 },
670 { wxT("exist"),8707 },
672 { wxT("forall"),8704 },
673 { wxT("frac12"),189 },
674 { wxT("frac14"),188 },
675 { wxT("frac34"),190 },
676 { wxT("frasl"),8260 },
677 { wxT("gamma"),947 },
680 { wxT("hArr"),8660 },
681 { wxT("harr"),8596 },
682 { wxT("hearts"),9829 },
683 { wxT("hellip"),8230 },
684 { wxT("iacute"),237 },
685 { wxT("icirc"),238 },
686 { wxT("iexcl"),161 },
687 { wxT("igrave"),236 },
688 { wxT("image"),8465 },
689 { wxT("infin"),8734 },
692 { wxT("iquest"),191 },
693 { wxT("isin"),8712 },
695 { wxT("kappa"),954 },
696 { wxT("lArr"),8656 },
697 { wxT("lambda"),955 },
698 { wxT("lang"),9001 },
699 { wxT("laquo"),171 },
700 { wxT("larr"),8592 },
701 { wxT("lceil"),8968 },
702 { wxT("ldquo"),8220 },
704 { wxT("lfloor"),8970 },
705 { wxT("lowast"),8727 },
708 { wxT("lsaquo"),8249 },
709 { wxT("lsquo"),8216 },
712 { wxT("mdash"),8212 },
713 { wxT("micro"),181 },
714 { wxT("middot"),183 },
715 { wxT("minus"),8722 },
717 { wxT("nabla"),8711 },
719 { wxT("ndash"),8211 },
723 { wxT("notin"),8713 },
724 { wxT("nsub"),8836 },
725 { wxT("ntilde"),241 },
727 { wxT("oacute"),243 },
728 { wxT("ocirc"),244 },
729 { wxT("oelig"),339 },
730 { wxT("ograve"),242 },
731 { wxT("oline"),8254 },
732 { wxT("omega"),969 },
733 { wxT("omicron"),959 },
734 { wxT("oplus"),8853 },
738 { wxT("oslash"),248 },
739 { wxT("otilde"),245 },
740 { wxT("otimes"),8855 },
743 { wxT("part"),8706 },
744 { wxT("permil"),8240 },
745 { wxT("perp"),8869 },
749 { wxT("plusmn"),177 },
750 { wxT("pound"),163 },
751 { wxT("prime"),8242 },
752 { wxT("prod"),8719 },
753 { wxT("prop"),8733 },
756 { wxT("rArr"),8658 },
757 { wxT("radic"),8730 },
758 { wxT("rang"),9002 },
759 { wxT("raquo"),187 },
760 { wxT("rarr"),8594 },
761 { wxT("rceil"),8969 },
762 { wxT("rdquo"),8221 },
763 { wxT("real"),8476 },
765 { wxT("rfloor"),8971 },
768 { wxT("rsaquo"),8250 },
769 { wxT("rsquo"),8217 },
770 { wxT("sbquo"),8218 },
771 { wxT("scaron"),353 },
772 { wxT("sdot"),8901 },
775 { wxT("sigma"),963 },
776 { wxT("sigmaf"),962 },
778 { wxT("spades"),9824 },
780 { wxT("sube"),8838 },
786 { wxT("supe"),8839 },
787 { wxT("szlig"),223 },
789 { wxT("there4"),8756 },
790 { wxT("theta"),952 },
791 { wxT("thetasym"),977 },
792 { wxT("thinsp"),8201 },
793 { wxT("thorn"),254 },
794 { wxT("tilde"),732 },
795 { wxT("times"),215 },
796 { wxT("trade"),8482 },
797 { wxT("uArr"),8657 },
798 { wxT("uacute"),250 },
799 { wxT("uarr"),8593 },
800 { wxT("ucirc"),251 },
801 { wxT("ugrave"),249 },
803 { wxT("upsih"),978 },
804 { wxT("upsilon"),965 },
806 { wxT("weierp"),8472 },
808 { wxT("yacute"),253 },
813 { wxT("zwnj"),8204 },
815 static size_t substitutions_cnt
= 0;
817 if (substitutions_cnt
== 0)
818 while (substitutions
[substitutions_cnt
].code
!= 0)
821 wxHtmlEntityInfo
*info
;
822 info
= (wxHtmlEntityInfo
*) bsearch(entity
.c_str(), substitutions
,
824 sizeof(wxHtmlEntityInfo
),
825 wxHtmlEntityCompare
);
833 return GetCharForCode(code
);
836 wxFSFile
*wxHtmlParser::OpenURL(wxHtmlURLType
WXUNUSED(type
),
837 const wxString
& url
) const
839 return GetFS()->OpenFile(url
);
843 //-----------------------------------------------------------------------------
844 // wxHtmlParser::ExtractCharsetInformation
845 //-----------------------------------------------------------------------------
847 class wxMetaTagParser
: public wxHtmlParser
850 wxObject
* GetProduct() { return NULL
; }
852 virtual void AddText(const wxChar
* WXUNUSED(txt
)) {}
855 class wxMetaTagHandler
: public wxHtmlTagHandler
858 wxMetaTagHandler(wxString
*retval
) : wxHtmlTagHandler(), m_retval(retval
) {}
859 wxString
GetSupportedTags() { return wxT("META,BODY"); }
860 bool HandleTag(const wxHtmlTag
& tag
);
866 bool wxMetaTagHandler::HandleTag(const wxHtmlTag
& tag
)
868 if (tag
.GetName() == _T("BODY"))
870 m_Parser
->StopParsing();
874 if (tag
.HasParam(_T("HTTP-EQUIV")) &&
875 tag
.GetParam(_T("HTTP-EQUIV")) == _T("Content-Type") &&
876 tag
.HasParam(_T("CONTENT")))
878 wxString content
= tag
.GetParam(_T("CONTENT"));
879 if (content
.Left(19) == _T("text/html; charset="))
881 *m_retval
= content
.Mid(19);
882 m_Parser
->StopParsing();
890 wxString
wxHtmlParser::ExtractCharsetInformation(const wxString
& markup
)
893 wxMetaTagParser parser
;
894 parser
.AddTagHandler(new wxMetaTagHandler(&charset
));
895 parser
.Parse(markup
);