1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/html/htmlpars.cpp
3 // Purpose: wx28HtmlParser class (generic parser)
4 // Author: Vaclav Slavik
6 // Copyright: (c) 1999 Vaclav Slavik
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 #include "wx/wxprec.h"
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/arrimpl.cpp"
33 #include "wx/msw/wince/missing.h" // for bsearch()
36 // DLL options compatibility check:
37 WX_CHECK_BUILD_OPTIONS("wxHTML")
39 const wxChar
*wxTRACE_HTML_DEBUG
= wxT("htmldebug");
41 //-----------------------------------------------------------------------------
42 // wx28HtmlParser helpers
43 //-----------------------------------------------------------------------------
45 class wx28HtmlTextPiece
48 wx28HtmlTextPiece(int pos
, int lng
) : m_pos(pos
), m_lng(lng
) {}
52 WX_DECLARE_OBJARRAY(wx28HtmlTextPiece
, wx28HtmlTextPieces
);
53 WX_DEFINE_OBJARRAY(wx28HtmlTextPieces
)
55 class wx28HtmlParserState
58 wx28HtmlTag
*m_curTag
;
60 wx28HtmlTextPieces
*m_textPieces
;
63 wx28HtmlParserState
*m_nextState
;
66 //-----------------------------------------------------------------------------
68 //-----------------------------------------------------------------------------
70 IMPLEMENT_ABSTRACT_CLASS(wx28HtmlParser
,wxObject
)
72 wx28HtmlParser::wx28HtmlParser()
73 : wxObject(), m_HandlersHash(wxKEY_STRING
),
74 m_FS(NULL
), m_HandlersStack(NULL
)
76 m_entitiesParser
= new wx28HtmlEntitiesParser
;
84 wx28HtmlParser::~wx28HtmlParser()
86 while (RestoreState()) {}
91 wxList
& tmp
= *m_HandlersStack
;
92 wxList::iterator it
, en
;
93 for( it
= tmp
.begin(), en
= tmp
.end(); it
!= en
; ++it
)
94 delete (wxHashTable
*)*it
;
97 delete m_HandlersStack
;
98 m_HandlersHash
.Clear();
99 WX_CLEAR_LIST(wxList
, m_HandlersList
);
100 delete m_entitiesParser
;
103 wxObject
* wx28HtmlParser::Parse(const wxString
& source
)
107 wxObject
*result
= GetProduct();
112 void wx28HtmlParser::InitParser(const wxString
& source
)
115 m_stopParsing
= false;
118 void wx28HtmlParser::DoneParser()
123 void wx28HtmlParser::SetSource(const wxString
& src
)
132 void wx28HtmlParser::CreateDOMTree()
134 wx28HtmlTagsCache
cache(m_Source
);
135 m_TextPieces
= new wx28HtmlTextPieces
;
136 CreateDOMSubTree(NULL
, 0, m_Source
.length(), &cache
);
140 extern bool wxIsCDATAElement(const wxChar
*tag
);
142 void wx28HtmlParser::CreateDOMSubTree(wx28HtmlTag
*cur
,
143 int begin_pos
, int end_pos
,
144 wx28HtmlTagsCache
*cache
)
146 if (end_pos
<= begin_pos
) return;
150 int textBeginning
= begin_pos
;
152 // If the tag contains CDATA text, we include the text between beginning
153 // and ending tag verbosely. Setting i=end_pos will skip to the very
154 // end of this function where text piece is added, bypassing any child
155 // tags parsing (CDATA element can't have child elements by definition):
156 if (cur
!= NULL
&& wxIsCDATAElement(cur
->GetName().c_str()))
163 c
= m_Source
.GetChar(i
);
167 // add text to m_TextPieces:
168 if (i
- textBeginning
> 0)
170 wx28HtmlTextPiece(textBeginning
, i
- textBeginning
));
172 // if it is a comment, skip it:
173 if (i
< end_pos
-6 && m_Source
.GetChar(i
+1) == wxT('!') &&
174 m_Source
.GetChar(i
+2) == wxT('-') &&
175 m_Source
.GetChar(i
+3) == wxT('-'))
177 // Comments begin with "<!--" and end with "--[ \t\r\n]*>"
178 // according to HTML 4.0
183 c
= m_Source
.GetChar(i
++);
184 if ((c
== wxT(' ') || c
== wxT('\n') ||
185 c
== wxT('\r') || c
== wxT('\t')) && dashes
>= 2) {}
186 else if (c
== wxT('>') && dashes
>= 2)
191 else if (c
== wxT('-'))
198 // add another tag to the tree:
199 else if (i
< end_pos
-1 && m_Source
.GetChar(i
+1) != wxT('/'))
203 chd
= new wx28HtmlTag(cur
, m_Source
,
204 i
, end_pos
, cache
, m_entitiesParser
);
207 chd
= new wx28HtmlTag(NULL
, m_Source
,
208 i
, end_pos
, cache
, m_entitiesParser
);
211 // if this is the first tag to be created make the root
212 // m_Tags point to it:
217 // if there is already a root tag add this tag as
219 chd
->m_Prev
= m_Tags
->GetLastSibling();
220 chd
->m_Prev
->m_Next
= chd
;
224 if (chd
->HasEnding())
226 CreateDOMSubTree(chd
,
227 chd
->GetBeginPos(), chd
->GetEndPos1(),
229 i
= chd
->GetEndPos2();
232 i
= chd
->GetBeginPos();
237 // ... or skip ending tag:
240 while (i
< end_pos
&& m_Source
.GetChar(i
) != wxT('>')) i
++;
247 // add remaining text to m_TextPieces:
248 if (end_pos
- textBeginning
> 0)
250 wx28HtmlTextPiece(textBeginning
, end_pos
- textBeginning
));
253 void wx28HtmlParser::DestroyDOMTree()
255 wx28HtmlTag
*t1
, *t2
;
259 t2
= t1
->GetNextSibling();
263 m_Tags
= m_CurTag
= NULL
;
269 void wx28HtmlParser::DoParsing()
273 DoParsing(0, m_Source
.length());
276 void wx28HtmlParser::DoParsing(int begin_pos
, int end_pos
)
278 if (end_pos
<= begin_pos
) return;
280 wx28HtmlTextPieces
& pieces
= *m_TextPieces
;
281 size_t piecesCnt
= pieces
.GetCount();
283 while (begin_pos
< end_pos
)
285 while (m_CurTag
&& m_CurTag
->GetBeginPos() < begin_pos
)
286 m_CurTag
= m_CurTag
->GetNextTag();
287 while (m_CurTextPiece
< piecesCnt
&&
288 pieces
[m_CurTextPiece
].m_pos
< begin_pos
)
291 if (m_CurTextPiece
< piecesCnt
&&
293 pieces
[m_CurTextPiece
].m_pos
< m_CurTag
->GetBeginPos()))
296 AddText(GetEntitiesParser()->Parse(
297 m_Source
.Mid(pieces
[m_CurTextPiece
].m_pos
,
298 pieces
[m_CurTextPiece
].m_lng
)));
299 begin_pos
= pieces
[m_CurTextPiece
].m_pos
+
300 pieces
[m_CurTextPiece
].m_lng
;
305 if (m_CurTag
->HasEnding())
306 begin_pos
= m_CurTag
->GetEndPos2();
308 begin_pos
= m_CurTag
->GetBeginPos();
309 wx28HtmlTag
*t
= m_CurTag
;
310 m_CurTag
= m_CurTag
->GetNextTag();
319 void wx28HtmlParser::AddTag(const wx28HtmlTag
& tag
)
321 wx28HtmlTagHandler
*h
;
324 h
= (wx28HtmlTagHandler
*) m_HandlersHash
.Get(tag
.GetName());
327 inner
= h
->HandleTag(tag
);
334 DoParsing(tag
.GetBeginPos(), tag
.GetEndPos1());
338 void wx28HtmlParser::AddTagHandler(wx28HtmlTagHandler
*handler
)
340 wxString
s(handler
->GetSupportedTags());
341 wxStringTokenizer
tokenizer(s
, wxT(", "));
343 while (tokenizer
.HasMoreTokens())
344 m_HandlersHash
.Put(tokenizer
.GetNextToken(), handler
);
346 if (m_HandlersList
.IndexOf(handler
) == wxNOT_FOUND
)
347 m_HandlersList
.Append(handler
);
349 handler
->SetParser(this);
352 void wx28HtmlParser::PushTagHandler(wx28HtmlTagHandler
*handler
, const wxString
& tags
)
354 wxStringTokenizer
tokenizer(tags
, wxT(", "));
357 if (m_HandlersStack
== NULL
)
359 m_HandlersStack
= new wxList
;
362 m_HandlersStack
->Insert((wxObject
*)new wxHashTable(m_HandlersHash
));
364 while (tokenizer
.HasMoreTokens())
366 key
= tokenizer
.GetNextToken();
367 m_HandlersHash
.Delete(key
);
368 m_HandlersHash
.Put(key
, handler
);
372 void wx28HtmlParser::PopTagHandler()
374 wxList::compatibility_iterator first
;
376 if ( !m_HandlersStack
||
378 !(first
= m_HandlersStack
->GetFirst())
380 ((first
= m_HandlersStack
->GetFirst()) == NULL
)
381 #endif // wxUSE_STL/!wxUSE_STL
384 wxLogWarning(_("Warning: attempt to remove HTML tag handler from empty stack."));
387 m_HandlersHash
= *((wxHashTable
*) first
->GetData());
388 delete (wxHashTable
*) first
->GetData();
389 m_HandlersStack
->Erase(first
);
392 void wx28HtmlParser::SetSourceAndSaveState(const wxString
& src
)
394 wx28HtmlParserState
*s
= new wx28HtmlParserState
;
396 s
->m_curTag
= m_CurTag
;
398 s
->m_textPieces
= m_TextPieces
;
399 s
->m_curTextPiece
= m_CurTextPiece
;
400 s
->m_source
= m_Source
;
402 s
->m_nextState
= m_SavedStates
;
409 m_Source
= wxEmptyString
;
414 bool wx28HtmlParser::RestoreState()
416 if (!m_SavedStates
) return false;
420 wx28HtmlParserState
*s
= m_SavedStates
;
421 m_SavedStates
= s
->m_nextState
;
423 m_CurTag
= s
->m_curTag
;
425 m_TextPieces
= s
->m_textPieces
;
426 m_CurTextPiece
= s
->m_curTextPiece
;
427 m_Source
= s
->m_source
;
433 wxString
wx28HtmlParser::GetInnerSource(const wx28HtmlTag
& tag
)
435 return GetSource()->Mid(tag
.GetBeginPos(),
436 tag
.GetEndPos1() - tag
.GetBeginPos());
439 //-----------------------------------------------------------------------------
440 // wx28HtmlTagHandler
441 //-----------------------------------------------------------------------------
443 IMPLEMENT_ABSTRACT_CLASS(wx28HtmlTagHandler
,wxObject
)
445 void wx28HtmlTagHandler::ParseInnerSource(const wxString
& source
)
447 // It is safe to temporarily change the source being parsed,
448 // provided we restore the state back after parsing
449 m_Parser
->SetSourceAndSaveState(source
);
450 m_Parser
->DoParsing();
451 m_Parser
->RestoreState();
455 //-----------------------------------------------------------------------------
456 // wx28HtmlEntitiesParser
457 //-----------------------------------------------------------------------------
459 IMPLEMENT_DYNAMIC_CLASS(wx28HtmlEntitiesParser
,wxObject
)
461 wx28HtmlEntitiesParser::wx28HtmlEntitiesParser()
463 : m_conv(NULL
), m_encoding(wxFONTENCODING_SYSTEM
)
468 wx28HtmlEntitiesParser::~wx28HtmlEntitiesParser()
475 void wx28HtmlEntitiesParser::SetEncoding(wxFontEncoding encoding
)
478 if (encoding
== m_encoding
)
483 m_encoding
= encoding
;
484 if (m_encoding
== wxFONTENCODING_SYSTEM
)
487 m_conv
= new wxCSConv(wxFontMapper::GetEncodingName(m_encoding
));
493 wxString
wx28HtmlEntitiesParser::Parse(const wxString
& input
)
495 const wxChar
*c
, *last
;
496 const wxChar
*in_str
= input
.c_str();
499 for (c
= in_str
, last
= in_str
; *c
!= wxT('\0'); c
++)
503 if ( output
.empty() )
504 output
.reserve(input
.length());
507 output
.append(last
, c
- last
);
508 if ( *++c
== wxT('\0') )
512 const wxChar
*ent_s
= c
;
515 for (; (*c
>= wxT('a') && *c
<= wxT('z')) ||
516 (*c
>= wxT('A') && *c
<= wxT('Z')) ||
517 (*c
>= wxT('0') && *c
<= wxT('9')) ||
518 *c
== wxT('_') || *c
== wxT('#'); c
++) {}
519 entity
.append(ent_s
, c
- ent_s
);
520 if (*c
!= wxT(';')) c
--;
522 entity_char
= GetEntityChar(entity
);
524 output
<< entity_char
;
527 output
.append(ent_s
-1, c
-ent_s
+2);
528 wxLogTrace(wxTRACE_HTML_DEBUG
,
529 wxT("Unrecognized HTML entity: '%s'"),
534 if (last
== in_str
) // common case: no entity
536 if (*last
!= wxT('\0'))
541 struct wx28HtmlEntityInfo
547 extern "C" int LINKAGEMODE
wx28HtmlEntityCompare(const void *key
, const void *item
)
549 return wxStrcmp((wxChar
*)key
, ((wx28HtmlEntityInfo
*)item
)->name
);
553 wxChar
wx28HtmlEntitiesParser::GetCharForCode(unsigned code
)
557 wbuf
[0] = (wchar_t)code
;
559 wxMBConv
*conv
= m_conv
? m_conv
: &wxConvLocal
;
560 if (conv
->WC2MB(buf
, wbuf
, 2) == (size_t)-1)
566 wxChar
wx28HtmlEntitiesParser::GetEntityChar(const wxString
& entity
)
570 if (entity
[0] == wxT('#'))
572 const wxChar
*ent_s
= entity
.c_str();
573 const wxChar
*format
;
575 if (ent_s
[1] == wxT('x') || ent_s
[1] == wxT('X'))
584 if (wxSscanf(ent_s
, format
, &code
) != 1)
589 static wx28HtmlEntityInfo substitutions
[] = {
590 { wxT("AElig"),198 },
591 { wxT("Aacute"),193 },
592 { wxT("Acirc"),194 },
593 { wxT("Agrave"),192 },
594 { wxT("Alpha"),913 },
595 { wxT("Aring"),197 },
596 { wxT("Atilde"),195 },
599 { wxT("Ccedil"),199 },
601 { wxT("Dagger"),8225 },
602 { wxT("Delta"),916 },
604 { wxT("Eacute"),201 },
605 { wxT("Ecirc"),202 },
606 { wxT("Egrave"),200 },
607 { wxT("Epsilon"),917 },
610 { wxT("Gamma"),915 },
611 { wxT("Iacute"),205 },
612 { wxT("Icirc"),206 },
613 { wxT("Igrave"),204 },
616 { wxT("Kappa"),922 },
617 { wxT("Lambda"),923 },
619 { wxT("Ntilde"),209 },
621 { wxT("OElig"),338 },
622 { wxT("Oacute"),211 },
623 { wxT("Ocirc"),212 },
624 { wxT("Ograve"),210 },
625 { wxT("Omega"),937 },
626 { wxT("Omicron"),927 },
627 { wxT("Oslash"),216 },
628 { wxT("Otilde"),213 },
632 { wxT("Prime"),8243 },
635 { wxT("Scaron"),352 },
636 { wxT("Sigma"),931 },
637 { wxT("THORN"),222 },
639 { wxT("Theta"),920 },
640 { wxT("Uacute"),218 },
641 { wxT("Ucirc"),219 },
642 { wxT("Ugrave"),217 },
643 { wxT("Upsilon"),933 },
646 { wxT("Yacute"),221 },
649 { wxT("aacute"),225 },
650 { wxT("acirc"),226 },
651 { wxT("acute"),180 },
652 { wxT("aelig"),230 },
653 { wxT("agrave"),224 },
654 { wxT("alefsym"),8501 },
655 { wxT("alpha"),945 },
659 { wxT("aring"),229 },
660 { wxT("asymp"),8776 },
661 { wxT("atilde"),227 },
663 { wxT("bdquo"),8222 },
665 { wxT("brvbar"),166 },
666 { wxT("bull"),8226 },
668 { wxT("ccedil"),231 },
669 { wxT("cedil"),184 },
673 { wxT("clubs"),9827 },
674 { wxT("cong"),8773 },
676 { wxT("crarr"),8629 },
678 { wxT("curren"),164 },
679 { wxT("dArr"),8659 },
680 { wxT("dagger"),8224 },
681 { wxT("darr"),8595 },
683 { wxT("delta"),948 },
684 { wxT("diams"),9830 },
685 { wxT("divide"),247 },
686 { wxT("eacute"),233 },
687 { wxT("ecirc"),234 },
688 { wxT("egrave"),232 },
689 { wxT("empty"),8709 },
690 { wxT("emsp"),8195 },
691 { wxT("ensp"),8194 },
692 { wxT("epsilon"),949 },
693 { wxT("equiv"),8801 },
697 { wxT("euro"),8364 },
698 { wxT("exist"),8707 },
700 { wxT("forall"),8704 },
701 { wxT("frac12"),189 },
702 { wxT("frac14"),188 },
703 { wxT("frac34"),190 },
704 { wxT("frasl"),8260 },
705 { wxT("gamma"),947 },
708 { wxT("hArr"),8660 },
709 { wxT("harr"),8596 },
710 { wxT("hearts"),9829 },
711 { wxT("hellip"),8230 },
712 { wxT("iacute"),237 },
713 { wxT("icirc"),238 },
714 { wxT("iexcl"),161 },
715 { wxT("igrave"),236 },
716 { wxT("image"),8465 },
717 { wxT("infin"),8734 },
720 { wxT("iquest"),191 },
721 { wxT("isin"),8712 },
723 { wxT("kappa"),954 },
724 { wxT("lArr"),8656 },
725 { wxT("lambda"),955 },
726 { wxT("lang"),9001 },
727 { wxT("laquo"),171 },
728 { wxT("larr"),8592 },
729 { wxT("lceil"),8968 },
730 { wxT("ldquo"),8220 },
732 { wxT("lfloor"),8970 },
733 { wxT("lowast"),8727 },
736 { wxT("lsaquo"),8249 },
737 { wxT("lsquo"),8216 },
740 { wxT("mdash"),8212 },
741 { wxT("micro"),181 },
742 { wxT("middot"),183 },
743 { wxT("minus"),8722 },
745 { wxT("nabla"),8711 },
747 { wxT("ndash"),8211 },
751 { wxT("notin"),8713 },
752 { wxT("nsub"),8836 },
753 { wxT("ntilde"),241 },
755 { wxT("oacute"),243 },
756 { wxT("ocirc"),244 },
757 { wxT("oelig"),339 },
758 { wxT("ograve"),242 },
759 { wxT("oline"),8254 },
760 { wxT("omega"),969 },
761 { wxT("omicron"),959 },
762 { wxT("oplus"),8853 },
766 { wxT("oslash"),248 },
767 { wxT("otilde"),245 },
768 { wxT("otimes"),8855 },
771 { wxT("part"),8706 },
772 { wxT("permil"),8240 },
773 { wxT("perp"),8869 },
777 { wxT("plusmn"),177 },
778 { wxT("pound"),163 },
779 { wxT("prime"),8242 },
780 { wxT("prod"),8719 },
781 { wxT("prop"),8733 },
784 { wxT("rArr"),8658 },
785 { wxT("radic"),8730 },
786 { wxT("rang"),9002 },
787 { wxT("raquo"),187 },
788 { wxT("rarr"),8594 },
789 { wxT("rceil"),8969 },
790 { wxT("rdquo"),8221 },
791 { wxT("real"),8476 },
793 { wxT("rfloor"),8971 },
796 { wxT("rsaquo"),8250 },
797 { wxT("rsquo"),8217 },
798 { wxT("sbquo"),8218 },
799 { wxT("scaron"),353 },
800 { wxT("sdot"),8901 },
803 { wxT("sigma"),963 },
804 { wxT("sigmaf"),962 },
806 { wxT("spades"),9824 },
808 { wxT("sube"),8838 },
814 { wxT("supe"),8839 },
815 { wxT("szlig"),223 },
817 { wxT("there4"),8756 },
818 { wxT("theta"),952 },
819 { wxT("thetasym"),977 },
820 { wxT("thinsp"),8201 },
821 { wxT("thorn"),254 },
822 { wxT("tilde"),732 },
823 { wxT("times"),215 },
824 { wxT("trade"),8482 },
825 { wxT("uArr"),8657 },
826 { wxT("uacute"),250 },
827 { wxT("uarr"),8593 },
828 { wxT("ucirc"),251 },
829 { wxT("ugrave"),249 },
831 { wxT("upsih"),978 },
832 { wxT("upsilon"),965 },
834 { wxT("weierp"),8472 },
836 { wxT("yacute"),253 },
841 { wxT("zwnj"),8204 },
843 static size_t substitutions_cnt
= 0;
845 if (substitutions_cnt
== 0)
846 while (substitutions
[substitutions_cnt
].code
!= 0)
849 wx28HtmlEntityInfo
*info
= NULL
;
851 // bsearch crashes under WinCE for some reason
853 for (i
= 0; i
< substitutions_cnt
; i
++)
855 if (entity
== substitutions
[i
].name
)
857 info
= & substitutions
[i
];
862 info
= (wx28HtmlEntityInfo
*) bsearch(entity
.c_str(), substitutions
,
864 sizeof(wx28HtmlEntityInfo
),
865 wx28HtmlEntityCompare
);
874 return GetCharForCode(code
);
877 wxFSFile
*wx28HtmlParser::OpenURL(wx28HtmlURLType
WXUNUSED(type
),
878 const wxString
& url
) const
880 return m_FS
? m_FS
->OpenFile(url
) : NULL
;
885 //-----------------------------------------------------------------------------
886 // wx28HtmlParser::ExtractCharsetInformation
887 //-----------------------------------------------------------------------------
889 class wxMetaTagParser
: public wx28HtmlParser
892 wxMetaTagParser() { }
894 wxObject
* GetProduct() { return NULL
; }
897 virtual void AddText(const wxChar
* WXUNUSED(txt
)) {}
899 DECLARE_NO_COPY_CLASS(wxMetaTagParser
)
902 class wxMetaTagHandler
: public wx28HtmlTagHandler
905 wxMetaTagHandler(wxString
*retval
) : wx28HtmlTagHandler(), m_retval(retval
) {}
906 wxString
GetSupportedTags() { return wxT("META,BODY"); }
907 bool HandleTag(const wx28HtmlTag
& tag
);
912 DECLARE_NO_COPY_CLASS(wxMetaTagHandler
)
915 bool wxMetaTagHandler::HandleTag(const wx28HtmlTag
& tag
)
917 if (tag
.GetName() == wxT("BODY"))
919 m_Parser
->StopParsing();
923 if (tag
.HasParam(wxT("HTTP-EQUIV")) &&
924 tag
.GetParam(wxT("HTTP-EQUIV")).IsSameAs(wxT("Content-Type"), false) &&
925 tag
.HasParam(wxT("CONTENT")))
927 wxString content
= tag
.GetParam(wxT("CONTENT")).Lower();
928 if (content
.Left(19) == wxT("text/html; charset="))
930 *m_retval
= content
.Mid(19);
931 m_Parser
->StopParsing();
939 wxString
wx28HtmlParser::ExtractCharsetInformation(const wxString
& markup
)
942 wxMetaTagParser
*parser
= new wxMetaTagParser();
945 parser
->AddTagHandler(new wxMetaTagHandler(&charset
));
946 parser
->Parse(markup
);