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 // DLL options compatibility check:
41 WX_CHECK_BUILD_OPTIONS("wxHTML")
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
;
310 if (m_CurTag
->HasEnding())
311 begin_pos
= m_CurTag
->GetEndPos2();
313 begin_pos
= m_CurTag
->GetBeginPos();
315 wxHtmlTag
*t
= m_CurTag
;
316 m_CurTag
= m_CurTag
->GetNextTag();
325 void wxHtmlParser::AddTag(const wxHtmlTag
& tag
)
330 h
= (wxHtmlTagHandler
*) m_HandlersHash
.Get(tag
.GetName());
333 inner
= h
->HandleTag(tag
);
340 DoParsing(tag
.GetBeginPos(), tag
.GetEndPos1());
344 void wxHtmlParser::AddTagHandler(wxHtmlTagHandler
*handler
)
346 wxString
s(handler
->GetSupportedTags());
347 wxStringTokenizer
tokenizer(s
, wxT(", "));
349 while (tokenizer
.HasMoreTokens())
350 m_HandlersHash
.Put(tokenizer
.GetNextToken(), handler
);
352 if (m_HandlersList
.IndexOf(handler
) == wxNOT_FOUND
)
353 m_HandlersList
.Append(handler
);
355 handler
->SetParser(this);
358 void wxHtmlParser::PushTagHandler(wxHtmlTagHandler
*handler
, wxString tags
)
360 wxStringTokenizer
tokenizer(tags
, wxT(", "));
363 if (m_HandlersStack
== NULL
)
365 m_HandlersStack
= new wxList
;
368 m_HandlersStack
->Insert((wxObject
*)new wxHashTable(m_HandlersHash
));
370 while (tokenizer
.HasMoreTokens())
372 key
= tokenizer
.GetNextToken();
373 m_HandlersHash
.Delete(key
);
374 m_HandlersHash
.Put(key
, handler
);
378 void wxHtmlParser::PopTagHandler()
380 wxList::compatibility_iterator first
;
382 if ( !m_HandlersStack
||
384 !(first
= m_HandlersStack
->GetFirst())
386 ((first
= m_HandlersStack
->GetFirst()) == NULL
)
387 #endif // wxUSE_STL/!wxUSE_STL
390 wxLogWarning(_("Warning: attempt to remove HTML tag handler from empty stack."));
393 m_HandlersHash
= *((wxHashTable
*) first
->GetData());
394 delete (wxHashTable
*) first
->GetData();
395 m_HandlersStack
->Erase(first
);
398 void wxHtmlParser::SetSourceAndSaveState(const wxString
& src
)
400 wxHtmlParserState
*s
= new wxHtmlParserState
;
402 s
->m_curTag
= m_CurTag
;
404 s
->m_textPieces
= m_TextPieces
;
405 s
->m_curTextPiece
= m_CurTextPiece
;
406 s
->m_source
= m_Source
;
408 s
->m_nextState
= m_SavedStates
;
415 m_Source
= wxEmptyString
;
420 bool wxHtmlParser::RestoreState()
422 if (!m_SavedStates
) return FALSE
;
426 wxHtmlParserState
*s
= m_SavedStates
;
427 m_SavedStates
= s
->m_nextState
;
429 m_CurTag
= s
->m_curTag
;
431 m_TextPieces
= s
->m_textPieces
;
432 m_CurTextPiece
= s
->m_curTextPiece
;
433 m_Source
= s
->m_source
;
439 //-----------------------------------------------------------------------------
441 //-----------------------------------------------------------------------------
443 IMPLEMENT_ABSTRACT_CLASS(wxHtmlTagHandler
,wxObject
)
446 //-----------------------------------------------------------------------------
447 // wxHtmlEntitiesParser
448 //-----------------------------------------------------------------------------
450 IMPLEMENT_DYNAMIC_CLASS(wxHtmlEntitiesParser
,wxObject
)
452 wxHtmlEntitiesParser::wxHtmlEntitiesParser()
453 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
454 : m_conv(NULL
), m_encoding(wxFONTENCODING_SYSTEM
)
459 wxHtmlEntitiesParser::~wxHtmlEntitiesParser()
461 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
466 void wxHtmlEntitiesParser::SetEncoding(wxFontEncoding encoding
)
468 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
469 if (encoding
== m_encoding
)
474 m_encoding
= encoding
;
475 if (m_encoding
== wxFONTENCODING_SYSTEM
)
478 m_conv
= new wxCSConv(wxFontMapper::GetEncodingName(m_encoding
));
484 wxString
wxHtmlEntitiesParser::Parse(const wxString
& input
)
486 const wxChar
*c
, *last
;
487 const wxChar
*in_str
= input
.c_str();
490 output
.reserve(input
.length());
492 for (c
= in_str
, last
= in_str
; *c
!= wxT('\0'); c
++)
497 output
.append(last
, c
- last
);
498 if (++c
== wxT('\0')) break;
501 const wxChar
*ent_s
= c
;
504 for (; (*c
>= wxT('a') && *c
<= wxT('z')) ||
505 (*c
>= wxT('A') && *c
<= wxT('Z')) ||
506 (*c
>= wxT('0') && *c
<= wxT('9')) ||
507 *c
== wxT('_') || *c
== wxT('#'); c
++) {}
508 entity
.append(ent_s
, c
- ent_s
);
509 if (*c
!= wxT(';')) c
--;
511 entity_char
= GetEntityChar(entity
);
513 output
<< entity_char
;
516 output
.append(ent_s
-1, c
-ent_s
+2);
517 wxLogDebug(wxT("Unrecognized HTML entity: '%s'"), entity
.c_str());
521 if (*last
!= wxT('\0'))
526 struct wxHtmlEntityInfo
532 extern "C" int LINKAGEMODE
wxHtmlEntityCompare(const void *key
, const void *item
)
534 return wxStrcmp((wxChar
*)key
, ((wxHtmlEntityInfo
*)item
)->name
);
538 wxChar
wxHtmlEntitiesParser::GetCharForCode(unsigned code
)
543 wbuf
[0] = (wchar_t)code
;
545 wxMBConv
*conv
= m_conv
? m_conv
: &wxConvLocal
;
546 if (conv
->WC2MB(buf
, wbuf
, 2) == (size_t)-1)
550 return (code
< 256) ? (wxChar
)code
: '?';
555 wxChar
wxHtmlEntitiesParser::GetEntityChar(const wxString
& entity
)
559 if (entity
[0] == wxT('#'))
561 const wxChar
*ent_s
= entity
.c_str();
562 const wxChar
*format
;
564 if (ent_s
[1] == wxT('x') || ent_s
[1] == wxT('X'))
573 if (wxSscanf(ent_s
, format
, &code
) != 1)
578 static wxHtmlEntityInfo substitutions
[] = {
579 { wxT("AElig"),198 },
580 { wxT("Aacute"),193 },
581 { wxT("Acirc"),194 },
582 { wxT("Agrave"),192 },
583 { wxT("Alpha"),913 },
584 { wxT("Aring"),197 },
585 { wxT("Atilde"),195 },
588 { wxT("Ccedil"),199 },
590 { wxT("Dagger"),8225 },
591 { wxT("Delta"),916 },
593 { wxT("Eacute"),201 },
594 { wxT("Ecirc"),202 },
595 { wxT("Egrave"),200 },
596 { wxT("Epsilon"),917 },
599 { wxT("Gamma"),915 },
600 { wxT("Iacute"),205 },
601 { wxT("Icirc"),206 },
602 { wxT("Igrave"),204 },
605 { wxT("Kappa"),922 },
606 { wxT("Lambda"),923 },
608 { wxT("Ntilde"),209 },
610 { wxT("OElig"),338 },
611 { wxT("Oacute"),211 },
612 { wxT("Ocirc"),212 },
613 { wxT("Ograve"),210 },
614 { wxT("Omega"),937 },
615 { wxT("Omicron"),927 },
616 { wxT("Oslash"),216 },
617 { wxT("Otilde"),213 },
621 { wxT("Prime"),8243 },
624 { wxT("Scaron"),352 },
625 { wxT("Sigma"),931 },
626 { wxT("THORN"),222 },
628 { wxT("Theta"),920 },
629 { wxT("Uacute"),218 },
630 { wxT("Ucirc"),219 },
631 { wxT("Ugrave"),217 },
632 { wxT("Upsilon"),933 },
635 { wxT("Yacute"),221 },
638 { wxT("aacute"),225 },
639 { wxT("acirc"),226 },
640 { wxT("acute"),180 },
641 { wxT("aelig"),230 },
642 { wxT("agrave"),224 },
643 { wxT("alefsym"),8501 },
644 { wxT("alpha"),945 },
648 { wxT("aring"),229 },
649 { wxT("asymp"),8776 },
650 { wxT("atilde"),227 },
652 { wxT("bdquo"),8222 },
654 { wxT("brvbar"),166 },
655 { wxT("bull"),8226 },
657 { wxT("ccedil"),231 },
658 { wxT("cedil"),184 },
662 { wxT("clubs"),9827 },
663 { wxT("cong"),8773 },
665 { wxT("crarr"),8629 },
667 { wxT("curren"),164 },
668 { wxT("dArr"),8659 },
669 { wxT("dagger"),8224 },
670 { wxT("darr"),8595 },
672 { wxT("delta"),948 },
673 { wxT("diams"),9830 },
674 { wxT("divide"),247 },
675 { wxT("eacute"),233 },
676 { wxT("ecirc"),234 },
677 { wxT("egrave"),232 },
678 { wxT("empty"),8709 },
679 { wxT("emsp"),8195 },
680 { wxT("ensp"),8194 },
681 { wxT("epsilon"),949 },
682 { wxT("equiv"),8801 },
686 { wxT("euro"),8364 },
687 { wxT("exist"),8707 },
689 { wxT("forall"),8704 },
690 { wxT("frac12"),189 },
691 { wxT("frac14"),188 },
692 { wxT("frac34"),190 },
693 { wxT("frasl"),8260 },
694 { wxT("gamma"),947 },
697 { wxT("hArr"),8660 },
698 { wxT("harr"),8596 },
699 { wxT("hearts"),9829 },
700 { wxT("hellip"),8230 },
701 { wxT("iacute"),237 },
702 { wxT("icirc"),238 },
703 { wxT("iexcl"),161 },
704 { wxT("igrave"),236 },
705 { wxT("image"),8465 },
706 { wxT("infin"),8734 },
709 { wxT("iquest"),191 },
710 { wxT("isin"),8712 },
712 { wxT("kappa"),954 },
713 { wxT("lArr"),8656 },
714 { wxT("lambda"),955 },
715 { wxT("lang"),9001 },
716 { wxT("laquo"),171 },
717 { wxT("larr"),8592 },
718 { wxT("lceil"),8968 },
719 { wxT("ldquo"),8220 },
721 { wxT("lfloor"),8970 },
722 { wxT("lowast"),8727 },
725 { wxT("lsaquo"),8249 },
726 { wxT("lsquo"),8216 },
729 { wxT("mdash"),8212 },
730 { wxT("micro"),181 },
731 { wxT("middot"),183 },
732 { wxT("minus"),8722 },
734 { wxT("nabla"),8711 },
736 { wxT("ndash"),8211 },
740 { wxT("notin"),8713 },
741 { wxT("nsub"),8836 },
742 { wxT("ntilde"),241 },
744 { wxT("oacute"),243 },
745 { wxT("ocirc"),244 },
746 { wxT("oelig"),339 },
747 { wxT("ograve"),242 },
748 { wxT("oline"),8254 },
749 { wxT("omega"),969 },
750 { wxT("omicron"),959 },
751 { wxT("oplus"),8853 },
755 { wxT("oslash"),248 },
756 { wxT("otilde"),245 },
757 { wxT("otimes"),8855 },
760 { wxT("part"),8706 },
761 { wxT("permil"),8240 },
762 { wxT("perp"),8869 },
766 { wxT("plusmn"),177 },
767 { wxT("pound"),163 },
768 { wxT("prime"),8242 },
769 { wxT("prod"),8719 },
770 { wxT("prop"),8733 },
773 { wxT("rArr"),8658 },
774 { wxT("radic"),8730 },
775 { wxT("rang"),9002 },
776 { wxT("raquo"),187 },
777 { wxT("rarr"),8594 },
778 { wxT("rceil"),8969 },
779 { wxT("rdquo"),8221 },
780 { wxT("real"),8476 },
782 { wxT("rfloor"),8971 },
785 { wxT("rsaquo"),8250 },
786 { wxT("rsquo"),8217 },
787 { wxT("sbquo"),8218 },
788 { wxT("scaron"),353 },
789 { wxT("sdot"),8901 },
792 { wxT("sigma"),963 },
793 { wxT("sigmaf"),962 },
795 { wxT("spades"),9824 },
797 { wxT("sube"),8838 },
803 { wxT("supe"),8839 },
804 { wxT("szlig"),223 },
806 { wxT("there4"),8756 },
807 { wxT("theta"),952 },
808 { wxT("thetasym"),977 },
809 { wxT("thinsp"),8201 },
810 { wxT("thorn"),254 },
811 { wxT("tilde"),732 },
812 { wxT("times"),215 },
813 { wxT("trade"),8482 },
814 { wxT("uArr"),8657 },
815 { wxT("uacute"),250 },
816 { wxT("uarr"),8593 },
817 { wxT("ucirc"),251 },
818 { wxT("ugrave"),249 },
820 { wxT("upsih"),978 },
821 { wxT("upsilon"),965 },
823 { wxT("weierp"),8472 },
825 { wxT("yacute"),253 },
830 { wxT("zwnj"),8204 },
832 static size_t substitutions_cnt
= 0;
834 if (substitutions_cnt
== 0)
835 while (substitutions
[substitutions_cnt
].code
!= 0)
838 wxHtmlEntityInfo
*info
;
839 info
= (wxHtmlEntityInfo
*) bsearch(entity
.c_str(), substitutions
,
841 sizeof(wxHtmlEntityInfo
),
842 wxHtmlEntityCompare
);
850 return GetCharForCode(code
);
853 wxFSFile
*wxHtmlParser::OpenURL(wxHtmlURLType
WXUNUSED(type
),
854 const wxString
& url
) const
856 return GetFS()->OpenFile(url
);
860 //-----------------------------------------------------------------------------
861 // wxHtmlParser::ExtractCharsetInformation
862 //-----------------------------------------------------------------------------
864 class wxMetaTagParser
: public wxHtmlParser
867 wxMetaTagParser() { }
869 wxObject
* GetProduct() { return NULL
; }
872 virtual void AddText(const wxChar
* WXUNUSED(txt
)) {}
874 DECLARE_NO_COPY_CLASS(wxMetaTagParser
)
877 class wxMetaTagHandler
: public wxHtmlTagHandler
880 wxMetaTagHandler(wxString
*retval
) : wxHtmlTagHandler(), m_retval(retval
) {}
881 wxString
GetSupportedTags() { return wxT("META,BODY"); }
882 bool HandleTag(const wxHtmlTag
& tag
);
887 DECLARE_NO_COPY_CLASS(wxMetaTagHandler
)
890 bool wxMetaTagHandler::HandleTag(const wxHtmlTag
& tag
)
892 if (tag
.GetName() == _T("BODY"))
894 m_Parser
->StopParsing();
898 if (tag
.HasParam(_T("HTTP-EQUIV")) &&
899 tag
.GetParam(_T("HTTP-EQUIV")).IsSameAs(_T("Content-Type"), false) &&
900 tag
.HasParam(_T("CONTENT")))
902 wxString content
= tag
.GetParam(_T("CONTENT")).Lower();
903 if (content
.Left(19) == _T("text/html; charset="))
905 *m_retval
= content
.Mid(19);
906 m_Parser
->StopParsing();
914 wxString
wxHtmlParser::ExtractCharsetInformation(const wxString
& markup
)
917 wxMetaTagParser parser
;
918 parser
.AddTagHandler(new wxMetaTagHandler(&charset
));
919 parser
.Parse(markup
);