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()) {}
88 wxList
& tmp
= *m_HandlersStack
;
89 wxList::iterator it
, en
;
90 for( it
= tmp
.begin(), en
= tmp
.end(); it
!= en
; ++it
)
91 delete (wxHashTable
*)*it
;
94 delete m_HandlersStack
;
95 m_HandlersHash
.Clear();
96 WX_CLEAR_LIST(wxList
, m_HandlersList
);
97 delete m_entitiesParser
;
100 wxObject
* wxHtmlParser::Parse(const wxString
& source
)
104 wxObject
*result
= GetProduct();
109 void wxHtmlParser::InitParser(const wxString
& source
)
112 m_stopParsing
= FALSE
;
115 void wxHtmlParser::DoneParser()
120 void wxHtmlParser::SetSource(const wxString
& src
)
129 void wxHtmlParser::CreateDOMTree()
131 wxHtmlTagsCache
cache(m_Source
);
132 m_TextPieces
= new wxHtmlTextPieces
;
133 CreateDOMSubTree(NULL
, 0, m_Source
.Length(), &cache
);
137 extern bool wxIsCDATAElement(const wxChar
*tag
);
139 void wxHtmlParser::CreateDOMSubTree(wxHtmlTag
*cur
,
140 int begin_pos
, int end_pos
,
141 wxHtmlTagsCache
*cache
)
143 if (end_pos
<= begin_pos
) return;
147 int textBeginning
= begin_pos
;
149 // If the tag contains CDATA text, we include the text between beginning
150 // and ending tag verbosely. Setting i=end_pos will skip to the very
151 // end of this function where text piece is added, bypassing any child
152 // tags parsing (CDATA element can't have child elements by definition):
153 if (cur
!= NULL
&& wxIsCDATAElement(cur
->GetName().c_str()))
160 c
= m_Source
.GetChar(i
);
164 // add text to m_TextPieces:
165 if (i
- textBeginning
> 0)
167 wxHtmlTextPiece(textBeginning
, i
- textBeginning
));
169 // if it is a comment, skip it:
170 if (i
< end_pos
-6 && m_Source
.GetChar(i
+1) == wxT('!') &&
171 m_Source
.GetChar(i
+2) == wxT('-') &&
172 m_Source
.GetChar(i
+3) == wxT('-'))
174 // Comments begin with "<!--" and end with "--[ \t\r\n]*>"
175 // according to HTML 4.0
180 c
= m_Source
.GetChar(i
++);
181 if ((c
== wxT(' ') || c
== wxT('\n') ||
182 c
== wxT('\r') || c
== wxT('\t')) && dashes
>= 2) {}
183 else if (c
== wxT('>') && dashes
>= 2)
188 else if (c
== wxT('-'))
195 // add another tag to the tree:
196 else if (i
< end_pos
-1 && m_Source
.GetChar(i
+1) != wxT('/'))
200 chd
= new wxHtmlTag(cur
, m_Source
,
201 i
, end_pos
, cache
, m_entitiesParser
);
204 chd
= new wxHtmlTag(NULL
, m_Source
,
205 i
, end_pos
, cache
, m_entitiesParser
);
208 // if this is the first tag to be created make the root
209 // m_Tags point to it:
214 // if there is already a root tag add this tag as
216 chd
->m_Prev
= m_Tags
->GetLastSibling();
217 chd
->m_Prev
->m_Next
= chd
;
221 if (chd
->HasEnding())
223 CreateDOMSubTree(chd
,
224 chd
->GetBeginPos(), chd
->GetEndPos1(),
226 i
= chd
->GetEndPos2();
229 i
= chd
->GetBeginPos();
234 // ... or skip ending tag:
237 while (i
< end_pos
&& m_Source
.GetChar(i
) != wxT('>')) i
++;
244 // add remaining text to m_TextPieces:
245 if (end_pos
- textBeginning
> 0)
247 wxHtmlTextPiece(textBeginning
, end_pos
- textBeginning
));
250 void wxHtmlParser::DestroyDOMTree()
256 t2
= t1
->GetNextSibling();
260 m_Tags
= m_CurTag
= NULL
;
266 void wxHtmlParser::DoParsing()
270 DoParsing(0, m_Source
.Length());
273 void wxHtmlParser::DoParsing(int begin_pos
, int end_pos
)
275 if (end_pos
<= begin_pos
) return;
277 wxHtmlTextPieces
& pieces
= *m_TextPieces
;
278 size_t piecesCnt
= pieces
.GetCount();
280 while (begin_pos
< end_pos
)
282 while (m_CurTag
&& m_CurTag
->GetBeginPos() < begin_pos
)
283 m_CurTag
= m_CurTag
->GetNextTag();
284 while (m_CurTextPiece
< piecesCnt
&&
285 pieces
[m_CurTextPiece
].m_pos
< begin_pos
)
288 if (m_CurTextPiece
< piecesCnt
&&
290 pieces
[m_CurTextPiece
].m_pos
< m_CurTag
->GetBeginPos()))
293 AddText(GetEntitiesParser()->Parse(
294 m_Source
.Mid(pieces
[m_CurTextPiece
].m_pos
,
295 pieces
[m_CurTextPiece
].m_lng
)));
296 begin_pos
= pieces
[m_CurTextPiece
].m_pos
+
297 pieces
[m_CurTextPiece
].m_lng
;
305 if (m_CurTag
->HasEnding())
306 begin_pos
= m_CurTag
->GetEndPos2();
308 begin_pos
= m_CurTag
->GetBeginPos();
310 wxHtmlTag
*t
= m_CurTag
;
311 m_CurTag
= m_CurTag
->GetNextTag();
320 void wxHtmlParser::AddTag(const wxHtmlTag
& tag
)
325 h
= (wxHtmlTagHandler
*) m_HandlersHash
.Get(tag
.GetName());
328 inner
= h
->HandleTag(tag
);
335 DoParsing(tag
.GetBeginPos(), tag
.GetEndPos1());
339 void wxHtmlParser::AddTagHandler(wxHtmlTagHandler
*handler
)
341 wxString
s(handler
->GetSupportedTags());
342 wxStringTokenizer
tokenizer(s
, wxT(", "));
344 while (tokenizer
.HasMoreTokens())
345 m_HandlersHash
.Put(tokenizer
.GetNextToken(), handler
);
347 if (m_HandlersList
.IndexOf(handler
) == wxNOT_FOUND
)
348 m_HandlersList
.Append(handler
);
350 handler
->SetParser(this);
353 void wxHtmlParser::PushTagHandler(wxHtmlTagHandler
*handler
, wxString tags
)
355 wxStringTokenizer
tokenizer(tags
, wxT(", "));
358 if (m_HandlersStack
== NULL
)
360 m_HandlersStack
= new wxList
;
363 m_HandlersStack
->Insert((wxObject
*)new wxHashTable(m_HandlersHash
));
365 while (tokenizer
.HasMoreTokens())
367 key
= tokenizer
.GetNextToken();
368 m_HandlersHash
.Delete(key
);
369 m_HandlersHash
.Put(key
, handler
);
373 void wxHtmlParser::PopTagHandler()
375 wxList::compatibility_iterator first
;
377 if ( !m_HandlersStack
||
379 !(first
= m_HandlersStack
->GetFirst())
381 ((first
= m_HandlersStack
->GetFirst()) == NULL
)
382 #endif // wxUSE_STL/!wxUSE_STL
385 wxLogWarning(_("Warning: attempt to remove HTML tag handler from empty stack."));
388 m_HandlersHash
= *((wxHashTable
*) first
->GetData());
389 delete (wxHashTable
*) first
->GetData();
390 m_HandlersStack
->Erase(first
);
393 void wxHtmlParser::SetSourceAndSaveState(const wxString
& src
)
395 wxHtmlParserState
*s
= new wxHtmlParserState
;
397 s
->m_curTag
= m_CurTag
;
399 s
->m_textPieces
= m_TextPieces
;
400 s
->m_curTextPiece
= m_CurTextPiece
;
401 s
->m_source
= m_Source
;
403 s
->m_nextState
= m_SavedStates
;
410 m_Source
= wxEmptyString
;
415 bool wxHtmlParser::RestoreState()
417 if (!m_SavedStates
) return FALSE
;
421 wxHtmlParserState
*s
= m_SavedStates
;
422 m_SavedStates
= s
->m_nextState
;
424 m_CurTag
= s
->m_curTag
;
426 m_TextPieces
= s
->m_textPieces
;
427 m_CurTextPiece
= s
->m_curTextPiece
;
428 m_Source
= s
->m_source
;
434 //-----------------------------------------------------------------------------
436 //-----------------------------------------------------------------------------
438 IMPLEMENT_ABSTRACT_CLASS(wxHtmlTagHandler
,wxObject
)
441 //-----------------------------------------------------------------------------
442 // wxHtmlEntitiesParser
443 //-----------------------------------------------------------------------------
445 IMPLEMENT_DYNAMIC_CLASS(wxHtmlEntitiesParser
,wxObject
)
447 wxHtmlEntitiesParser::wxHtmlEntitiesParser()
448 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
449 : m_conv(NULL
), m_encoding(wxFONTENCODING_SYSTEM
)
454 wxHtmlEntitiesParser::~wxHtmlEntitiesParser()
456 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
461 void wxHtmlEntitiesParser::SetEncoding(wxFontEncoding encoding
)
463 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
464 if (encoding
== m_encoding
)
469 m_encoding
= encoding
;
470 if (m_encoding
== wxFONTENCODING_SYSTEM
)
473 m_conv
= new wxCSConv(wxFontMapper::GetEncodingName(m_encoding
));
479 wxString
wxHtmlEntitiesParser::Parse(const wxString
& input
)
481 const wxChar
*c
, *last
;
482 const wxChar
*in_str
= input
.c_str();
485 output
.reserve(input
.length());
487 for (c
= in_str
, last
= in_str
; *c
!= wxT('\0'); c
++)
492 output
.append(last
, c
- last
);
493 if (++c
== wxT('\0')) break;
496 const wxChar
*ent_s
= c
;
499 for (; (*c
>= wxT('a') && *c
<= wxT('z')) ||
500 (*c
>= wxT('A') && *c
<= wxT('Z')) ||
501 (*c
>= wxT('0') && *c
<= wxT('9')) ||
502 *c
== wxT('_') || *c
== wxT('#'); c
++) {}
503 entity
.append(ent_s
, c
- ent_s
);
504 if (*c
!= wxT(';')) c
--;
506 entity_char
= GetEntityChar(entity
);
508 output
<< entity_char
;
511 output
.append(ent_s
-1, c
-ent_s
+2);
512 wxLogDebug(wxT("Unrecognized HTML entity: '%s'"), entity
.c_str());
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
;
834 info
= (wxHtmlEntityInfo
*) bsearch(entity
.c_str(), substitutions
,
836 sizeof(wxHtmlEntityInfo
),
837 wxHtmlEntityCompare
);
845 return GetCharForCode(code
);
848 wxFSFile
*wxHtmlParser::OpenURL(wxHtmlURLType
WXUNUSED(type
),
849 const wxString
& url
) const
851 return GetFS()->OpenFile(url
);
855 //-----------------------------------------------------------------------------
856 // wxHtmlParser::ExtractCharsetInformation
857 //-----------------------------------------------------------------------------
859 class wxMetaTagParser
: public wxHtmlParser
862 wxMetaTagParser() { }
864 wxObject
* GetProduct() { return NULL
; }
867 virtual void AddText(const wxChar
* WXUNUSED(txt
)) {}
869 DECLARE_NO_COPY_CLASS(wxMetaTagParser
)
872 class wxMetaTagHandler
: public wxHtmlTagHandler
875 wxMetaTagHandler(wxString
*retval
) : wxHtmlTagHandler(), m_retval(retval
) {}
876 wxString
GetSupportedTags() { return wxT("META,BODY"); }
877 bool HandleTag(const wxHtmlTag
& tag
);
882 DECLARE_NO_COPY_CLASS(wxMetaTagHandler
)
885 bool wxMetaTagHandler::HandleTag(const wxHtmlTag
& tag
)
887 if (tag
.GetName() == _T("BODY"))
889 m_Parser
->StopParsing();
893 if (tag
.HasParam(_T("HTTP-EQUIV")) &&
894 tag
.GetParam(_T("HTTP-EQUIV")).IsSameAs(_T("Content-Type"), false) &&
895 tag
.HasParam(_T("CONTENT")))
897 wxString content
= tag
.GetParam(_T("CONTENT"));
898 if (content
.Left(19) == _T("text/html; charset="))
900 *m_retval
= content
.Mid(19);
901 m_Parser
->StopParsing();
909 wxString
wxHtmlParser::ExtractCharsetInformation(const wxString
& markup
)
912 wxMetaTagParser parser
;
913 parser
.AddTagHandler(new wxMetaTagHandler(&charset
));
914 parser
.Parse(markup
);