1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/html/htmlpars.cpp
3 // Purpose: wx28HtmlParser class (generic parser)
4 // Author: Vaclav Slavik
5 // Copyright: (c) 1999 Vaclav Slavik
6 // Licence: wxWindows licence
7 /////////////////////////////////////////////////////////////////////////////
18 #include "wx/dynarray.h"
24 #include "wx/tokenzr.h"
25 #include "wx/wfstream.h"
27 #include "wx/fontmap.h"
28 #include "wx/html/htmldefs.h"
29 #include "wx/arrimpl.cpp"
32 #include "wx/msw/wince/missing.h" // for bsearch()
35 // DLL options compatibility check:
36 WX_CHECK_BUILD_OPTIONS("wxHTML")
38 const wxChar
*wxTRACE_HTML_DEBUG
= wxT("htmldebug");
40 //-----------------------------------------------------------------------------
41 // wx28HtmlParser helpers
42 //-----------------------------------------------------------------------------
44 class wx28HtmlTextPiece
47 wx28HtmlTextPiece(int pos
, int lng
) : m_pos(pos
), m_lng(lng
) {}
51 WX_DECLARE_OBJARRAY(wx28HtmlTextPiece
, wx28HtmlTextPieces
);
52 WX_DEFINE_OBJARRAY(wx28HtmlTextPieces
)
54 class wx28HtmlParserState
57 wx28HtmlTag
*m_curTag
;
59 wx28HtmlTextPieces
*m_textPieces
;
62 wx28HtmlParserState
*m_nextState
;
65 //-----------------------------------------------------------------------------
67 //-----------------------------------------------------------------------------
69 IMPLEMENT_ABSTRACT_CLASS(wx28HtmlParser
,wxObject
)
71 wx28HtmlParser::wx28HtmlParser()
72 : wxObject(), m_HandlersHash(wxKEY_STRING
),
73 m_FS(NULL
), m_HandlersStack(NULL
)
75 m_entitiesParser
= new wx28HtmlEntitiesParser
;
83 wx28HtmlParser::~wx28HtmlParser()
85 while (RestoreState()) {}
90 wxList
& tmp
= *m_HandlersStack
;
91 wxList::iterator it
, en
;
92 for( it
= tmp
.begin(), en
= tmp
.end(); it
!= en
; ++it
)
93 delete (wxHashTable
*)*it
;
96 delete m_HandlersStack
;
97 m_HandlersHash
.Clear();
98 WX_CLEAR_LIST(wxList
, m_HandlersList
);
99 delete m_entitiesParser
;
102 wxObject
* wx28HtmlParser::Parse(const wxString
& source
)
106 wxObject
*result
= GetProduct();
111 void wx28HtmlParser::InitParser(const wxString
& source
)
114 m_stopParsing
= false;
117 void wx28HtmlParser::DoneParser()
122 void wx28HtmlParser::SetSource(const wxString
& src
)
131 void wx28HtmlParser::CreateDOMTree()
133 wx28HtmlTagsCache
cache(m_Source
);
134 m_TextPieces
= new wx28HtmlTextPieces
;
135 CreateDOMSubTree(NULL
, 0, m_Source
.length(), &cache
);
139 extern bool wxIsCDATAElement(const wxChar
*tag
);
141 void wx28HtmlParser::CreateDOMSubTree(wx28HtmlTag
*cur
,
142 int begin_pos
, int end_pos
,
143 wx28HtmlTagsCache
*cache
)
145 if (end_pos
<= begin_pos
) return;
149 int textBeginning
= begin_pos
;
151 // If the tag contains CDATA text, we include the text between beginning
152 // and ending tag verbosely. Setting i=end_pos will skip to the very
153 // end of this function where text piece is added, bypassing any child
154 // tags parsing (CDATA element can't have child elements by definition):
155 if (cur
!= NULL
&& wxIsCDATAElement(cur
->GetName().c_str()))
162 c
= m_Source
.GetChar(i
);
166 // add text to m_TextPieces:
167 if (i
- textBeginning
> 0)
169 wx28HtmlTextPiece(textBeginning
, i
- textBeginning
));
171 // if it is a comment, skip it:
172 if (i
< end_pos
-6 && m_Source
.GetChar(i
+1) == wxT('!') &&
173 m_Source
.GetChar(i
+2) == wxT('-') &&
174 m_Source
.GetChar(i
+3) == wxT('-'))
176 // Comments begin with "<!--" and end with "--[ \t\r\n]*>"
177 // according to HTML 4.0
182 c
= m_Source
.GetChar(i
++);
183 if ((c
== wxT(' ') || c
== wxT('\n') ||
184 c
== wxT('\r') || c
== wxT('\t')) && dashes
>= 2) {}
185 else if (c
== wxT('>') && dashes
>= 2)
190 else if (c
== wxT('-'))
197 // add another tag to the tree:
198 else if (i
< end_pos
-1 && m_Source
.GetChar(i
+1) != wxT('/'))
202 chd
= new wx28HtmlTag(cur
, m_Source
,
203 i
, end_pos
, cache
, m_entitiesParser
);
206 chd
= new wx28HtmlTag(NULL
, m_Source
,
207 i
, end_pos
, cache
, m_entitiesParser
);
210 // if this is the first tag to be created make the root
211 // m_Tags point to it:
216 // if there is already a root tag add this tag as
218 chd
->m_Prev
= m_Tags
->GetLastSibling();
219 chd
->m_Prev
->m_Next
= chd
;
223 if (chd
->HasEnding())
225 CreateDOMSubTree(chd
,
226 chd
->GetBeginPos(), chd
->GetEndPos1(),
228 i
= chd
->GetEndPos2();
231 i
= chd
->GetBeginPos();
236 // ... or skip ending tag:
239 while (i
< end_pos
&& m_Source
.GetChar(i
) != wxT('>')) i
++;
246 // add remaining text to m_TextPieces:
247 if (end_pos
- textBeginning
> 0)
249 wx28HtmlTextPiece(textBeginning
, end_pos
- textBeginning
));
252 void wx28HtmlParser::DestroyDOMTree()
254 wx28HtmlTag
*t1
, *t2
;
258 t2
= t1
->GetNextSibling();
262 m_Tags
= m_CurTag
= NULL
;
268 void wx28HtmlParser::DoParsing()
272 DoParsing(0, m_Source
.length());
275 void wx28HtmlParser::DoParsing(int begin_pos
, int end_pos
)
277 if (end_pos
<= begin_pos
) return;
279 wx28HtmlTextPieces
& pieces
= *m_TextPieces
;
280 size_t piecesCnt
= pieces
.GetCount();
282 while (begin_pos
< end_pos
)
284 while (m_CurTag
&& m_CurTag
->GetBeginPos() < begin_pos
)
285 m_CurTag
= m_CurTag
->GetNextTag();
286 while (m_CurTextPiece
< piecesCnt
&&
287 pieces
[m_CurTextPiece
].m_pos
< begin_pos
)
290 if (m_CurTextPiece
< piecesCnt
&&
292 pieces
[m_CurTextPiece
].m_pos
< m_CurTag
->GetBeginPos()))
295 AddText(GetEntitiesParser()->Parse(
296 m_Source
.Mid(pieces
[m_CurTextPiece
].m_pos
,
297 pieces
[m_CurTextPiece
].m_lng
)).t_str());
298 begin_pos
= pieces
[m_CurTextPiece
].m_pos
+
299 pieces
[m_CurTextPiece
].m_lng
;
304 if (m_CurTag
->HasEnding())
305 begin_pos
= m_CurTag
->GetEndPos2();
307 begin_pos
= m_CurTag
->GetBeginPos();
308 wx28HtmlTag
*t
= m_CurTag
;
309 m_CurTag
= m_CurTag
->GetNextTag();
318 void wx28HtmlParser::AddTag(const wx28HtmlTag
& tag
)
320 wx28HtmlTagHandler
*h
;
323 h
= (wx28HtmlTagHandler
*) m_HandlersHash
.Get(tag
.GetName());
326 inner
= h
->HandleTag(tag
);
333 DoParsing(tag
.GetBeginPos(), tag
.GetEndPos1());
337 void wx28HtmlParser::AddTagHandler(wx28HtmlTagHandler
*handler
)
339 wxString
s(handler
->GetSupportedTags());
340 wxStringTokenizer
tokenizer(s
, wxT(", "));
342 while (tokenizer
.HasMoreTokens())
343 m_HandlersHash
.Put(tokenizer
.GetNextToken(), handler
);
345 if (m_HandlersList
.IndexOf(handler
) == wxNOT_FOUND
)
346 m_HandlersList
.Append(handler
);
348 handler
->SetParser(this);
351 void wx28HtmlParser::PushTagHandler(wx28HtmlTagHandler
*handler
, const wxString
& tags
)
353 wxStringTokenizer
tokenizer(tags
, wxT(", "));
356 if (m_HandlersStack
== NULL
)
358 m_HandlersStack
= new wxList
;
361 m_HandlersStack
->Insert((wxObject
*)new wxHashTable(m_HandlersHash
));
363 while (tokenizer
.HasMoreTokens())
365 key
= tokenizer
.GetNextToken();
366 m_HandlersHash
.Delete(key
);
367 m_HandlersHash
.Put(key
, handler
);
371 void wx28HtmlParser::PopTagHandler()
373 wxList::compatibility_iterator first
;
375 if ( !m_HandlersStack
||
377 !(first
= m_HandlersStack
->GetFirst())
379 ((first
= m_HandlersStack
->GetFirst()) == NULL
)
380 #endif // wxUSE_STL/!wxUSE_STL
383 wxLogWarning(_("Warning: attempt to remove HTML tag handler from empty stack."));
386 m_HandlersHash
= *((wxHashTable
*) first
->GetData());
387 delete (wxHashTable
*) first
->GetData();
388 m_HandlersStack
->Erase(first
);
391 void wx28HtmlParser::SetSourceAndSaveState(const wxString
& src
)
393 wx28HtmlParserState
*s
= new wx28HtmlParserState
;
395 s
->m_curTag
= m_CurTag
;
397 s
->m_textPieces
= m_TextPieces
;
398 s
->m_curTextPiece
= m_CurTextPiece
;
399 s
->m_source
= m_Source
;
401 s
->m_nextState
= m_SavedStates
;
408 m_Source
= wxEmptyString
;
413 bool wx28HtmlParser::RestoreState()
415 if (!m_SavedStates
) return false;
419 wx28HtmlParserState
*s
= m_SavedStates
;
420 m_SavedStates
= s
->m_nextState
;
422 m_CurTag
= s
->m_curTag
;
424 m_TextPieces
= s
->m_textPieces
;
425 m_CurTextPiece
= s
->m_curTextPiece
;
426 m_Source
= s
->m_source
;
432 wxString
wx28HtmlParser::GetInnerSource(const wx28HtmlTag
& tag
)
434 return GetSource()->Mid(tag
.GetBeginPos(),
435 tag
.GetEndPos1() - tag
.GetBeginPos());
438 //-----------------------------------------------------------------------------
439 // wx28HtmlTagHandler
440 //-----------------------------------------------------------------------------
442 IMPLEMENT_ABSTRACT_CLASS(wx28HtmlTagHandler
,wxObject
)
444 void wx28HtmlTagHandler::ParseInnerSource(const wxString
& source
)
446 // It is safe to temporarily change the source being parsed,
447 // provided we restore the state back after parsing
448 m_Parser
->SetSourceAndSaveState(source
);
449 m_Parser
->DoParsing();
450 m_Parser
->RestoreState();
454 //-----------------------------------------------------------------------------
455 // wx28HtmlEntitiesParser
456 //-----------------------------------------------------------------------------
458 IMPLEMENT_DYNAMIC_CLASS(wx28HtmlEntitiesParser
,wxObject
)
460 wx28HtmlEntitiesParser::wx28HtmlEntitiesParser()
462 : m_conv(NULL
), m_encoding(wxFONTENCODING_SYSTEM
)
467 wx28HtmlEntitiesParser::~wx28HtmlEntitiesParser()
474 void wx28HtmlEntitiesParser::SetEncoding(wxFontEncoding encoding
)
477 if (encoding
== m_encoding
)
482 m_encoding
= encoding
;
483 if (m_encoding
== wxFONTENCODING_SYSTEM
)
486 m_conv
= new wxCSConv(wxFontMapper::GetEncodingName(m_encoding
));
492 wxString
wx28HtmlEntitiesParser::Parse(const wxString
& input
)
494 const wxChar
*c
, *last
;
495 const wxChar
*in_str
= input
.c_str();
498 for (c
= in_str
, last
= in_str
; *c
!= wxT('\0'); c
++)
502 if ( output
.empty() )
503 output
.reserve(input
.length());
506 output
.append(last
, c
- last
);
507 if ( *++c
== wxT('\0') )
511 const wxChar
*ent_s
= c
;
514 for (; (*c
>= wxT('a') && *c
<= wxT('z')) ||
515 (*c
>= wxT('A') && *c
<= wxT('Z')) ||
516 (*c
>= wxT('0') && *c
<= wxT('9')) ||
517 *c
== wxT('_') || *c
== wxT('#'); c
++) {}
518 entity
.append(ent_s
, c
- ent_s
);
519 if (*c
!= wxT(';')) c
--;
521 entity_char
= GetEntityChar(entity
);
523 output
<< entity_char
;
526 output
.append(ent_s
-1, c
-ent_s
+2);
527 wxLogTrace(wxTRACE_HTML_DEBUG
,
528 wxT("Unrecognized HTML entity: '%s'"),
533 if (last
== in_str
) // common case: no entity
535 if (*last
!= wxT('\0'))
540 struct wx28HtmlEntityInfo
546 extern "C" int LINKAGEMODE
wx28HtmlEntityCompare(const void *key
, const void *item
)
548 return wxStrcmp((wxChar
*)key
, ((wx28HtmlEntityInfo
*)item
)->name
);
552 wxChar
wx28HtmlEntitiesParser::GetCharForCode(unsigned code
)
556 wbuf
[0] = (wchar_t)code
;
558 wxMBConv
*conv
= m_conv
? m_conv
: &wxConvLocal
;
559 if (conv
->WC2MB(buf
, wbuf
, 2) == (size_t)-1)
565 wxChar
wx28HtmlEntitiesParser::GetEntityChar(const wxString
& entity
)
569 if (entity
[0] == wxT('#'))
571 const wxChar
*ent_s
= entity
.c_str();
572 const wxChar
*format
;
574 if (ent_s
[1] == wxT('x') || ent_s
[1] == wxT('X'))
583 if (wxSscanf(ent_s
, format
, &code
) != 1)
588 static wx28HtmlEntityInfo substitutions
[] = {
589 { wxT("AElig"),198 },
590 { wxT("Aacute"),193 },
591 { wxT("Acirc"),194 },
592 { wxT("Agrave"),192 },
593 { wxT("Alpha"),913 },
594 { wxT("Aring"),197 },
595 { wxT("Atilde"),195 },
598 { wxT("Ccedil"),199 },
600 { wxT("Dagger"),8225 },
601 { wxT("Delta"),916 },
603 { wxT("Eacute"),201 },
604 { wxT("Ecirc"),202 },
605 { wxT("Egrave"),200 },
606 { wxT("Epsilon"),917 },
609 { wxT("Gamma"),915 },
610 { wxT("Iacute"),205 },
611 { wxT("Icirc"),206 },
612 { wxT("Igrave"),204 },
615 { wxT("Kappa"),922 },
616 { wxT("Lambda"),923 },
618 { wxT("Ntilde"),209 },
620 { wxT("OElig"),338 },
621 { wxT("Oacute"),211 },
622 { wxT("Ocirc"),212 },
623 { wxT("Ograve"),210 },
624 { wxT("Omega"),937 },
625 { wxT("Omicron"),927 },
626 { wxT("Oslash"),216 },
627 { wxT("Otilde"),213 },
631 { wxT("Prime"),8243 },
634 { wxT("Scaron"),352 },
635 { wxT("Sigma"),931 },
636 { wxT("THORN"),222 },
638 { wxT("Theta"),920 },
639 { wxT("Uacute"),218 },
640 { wxT("Ucirc"),219 },
641 { wxT("Ugrave"),217 },
642 { wxT("Upsilon"),933 },
645 { wxT("Yacute"),221 },
648 { wxT("aacute"),225 },
649 { wxT("acirc"),226 },
650 { wxT("acute"),180 },
651 { wxT("aelig"),230 },
652 { wxT("agrave"),224 },
653 { wxT("alefsym"),8501 },
654 { wxT("alpha"),945 },
658 { wxT("aring"),229 },
659 { wxT("asymp"),8776 },
660 { wxT("atilde"),227 },
662 { wxT("bdquo"),8222 },
664 { wxT("brvbar"),166 },
665 { wxT("bull"),8226 },
667 { wxT("ccedil"),231 },
668 { wxT("cedil"),184 },
672 { wxT("clubs"),9827 },
673 { wxT("cong"),8773 },
675 { wxT("crarr"),8629 },
677 { wxT("curren"),164 },
678 { wxT("dArr"),8659 },
679 { wxT("dagger"),8224 },
680 { wxT("darr"),8595 },
682 { wxT("delta"),948 },
683 { wxT("diams"),9830 },
684 { wxT("divide"),247 },
685 { wxT("eacute"),233 },
686 { wxT("ecirc"),234 },
687 { wxT("egrave"),232 },
688 { wxT("empty"),8709 },
689 { wxT("emsp"),8195 },
690 { wxT("ensp"),8194 },
691 { wxT("epsilon"),949 },
692 { wxT("equiv"),8801 },
696 { wxT("euro"),8364 },
697 { wxT("exist"),8707 },
699 { wxT("forall"),8704 },
700 { wxT("frac12"),189 },
701 { wxT("frac14"),188 },
702 { wxT("frac34"),190 },
703 { wxT("frasl"),8260 },
704 { wxT("gamma"),947 },
707 { wxT("hArr"),8660 },
708 { wxT("harr"),8596 },
709 { wxT("hearts"),9829 },
710 { wxT("hellip"),8230 },
711 { wxT("iacute"),237 },
712 { wxT("icirc"),238 },
713 { wxT("iexcl"),161 },
714 { wxT("igrave"),236 },
715 { wxT("image"),8465 },
716 { wxT("infin"),8734 },
719 { wxT("iquest"),191 },
720 { wxT("isin"),8712 },
722 { wxT("kappa"),954 },
723 { wxT("lArr"),8656 },
724 { wxT("lambda"),955 },
725 { wxT("lang"),9001 },
726 { wxT("laquo"),171 },
727 { wxT("larr"),8592 },
728 { wxT("lceil"),8968 },
729 { wxT("ldquo"),8220 },
731 { wxT("lfloor"),8970 },
732 { wxT("lowast"),8727 },
735 { wxT("lsaquo"),8249 },
736 { wxT("lsquo"),8216 },
739 { wxT("mdash"),8212 },
740 { wxT("micro"),181 },
741 { wxT("middot"),183 },
742 { wxT("minus"),8722 },
744 { wxT("nabla"),8711 },
746 { wxT("ndash"),8211 },
750 { wxT("notin"),8713 },
751 { wxT("nsub"),8836 },
752 { wxT("ntilde"),241 },
754 { wxT("oacute"),243 },
755 { wxT("ocirc"),244 },
756 { wxT("oelig"),339 },
757 { wxT("ograve"),242 },
758 { wxT("oline"),8254 },
759 { wxT("omega"),969 },
760 { wxT("omicron"),959 },
761 { wxT("oplus"),8853 },
765 { wxT("oslash"),248 },
766 { wxT("otilde"),245 },
767 { wxT("otimes"),8855 },
770 { wxT("part"),8706 },
771 { wxT("permil"),8240 },
772 { wxT("perp"),8869 },
776 { wxT("plusmn"),177 },
777 { wxT("pound"),163 },
778 { wxT("prime"),8242 },
779 { wxT("prod"),8719 },
780 { wxT("prop"),8733 },
783 { wxT("rArr"),8658 },
784 { wxT("radic"),8730 },
785 { wxT("rang"),9002 },
786 { wxT("raquo"),187 },
787 { wxT("rarr"),8594 },
788 { wxT("rceil"),8969 },
789 { wxT("rdquo"),8221 },
790 { wxT("real"),8476 },
792 { wxT("rfloor"),8971 },
795 { wxT("rsaquo"),8250 },
796 { wxT("rsquo"),8217 },
797 { wxT("sbquo"),8218 },
798 { wxT("scaron"),353 },
799 { wxT("sdot"),8901 },
802 { wxT("sigma"),963 },
803 { wxT("sigmaf"),962 },
805 { wxT("spades"),9824 },
807 { wxT("sube"),8838 },
813 { wxT("supe"),8839 },
814 { wxT("szlig"),223 },
816 { wxT("there4"),8756 },
817 { wxT("theta"),952 },
818 { wxT("thetasym"),977 },
819 { wxT("thinsp"),8201 },
820 { wxT("thorn"),254 },
821 { wxT("tilde"),732 },
822 { wxT("times"),215 },
823 { wxT("trade"),8482 },
824 { wxT("uArr"),8657 },
825 { wxT("uacute"),250 },
826 { wxT("uarr"),8593 },
827 { wxT("ucirc"),251 },
828 { wxT("ugrave"),249 },
830 { wxT("upsih"),978 },
831 { wxT("upsilon"),965 },
833 { wxT("weierp"),8472 },
835 { wxT("yacute"),253 },
840 { wxT("zwnj"),8204 },
842 static size_t substitutions_cnt
= 0;
844 if (substitutions_cnt
== 0)
845 while (substitutions
[substitutions_cnt
].code
!= 0)
848 wx28HtmlEntityInfo
*info
= NULL
;
850 // bsearch crashes under WinCE for some reason
852 for (i
= 0; i
< substitutions_cnt
; i
++)
854 if (entity
== substitutions
[i
].name
)
856 info
= & substitutions
[i
];
861 info
= (wx28HtmlEntityInfo
*) bsearch(entity
.c_str(), substitutions
,
863 sizeof(wx28HtmlEntityInfo
),
864 wx28HtmlEntityCompare
);
873 return GetCharForCode(code
);
876 wxFSFile
*wx28HtmlParser::OpenURL(wx28HtmlURLType
WXUNUSED(type
),
877 const wxString
& url
) const
879 return m_FS
? m_FS
->OpenFile(url
) : NULL
;
884 //-----------------------------------------------------------------------------
885 // wx28HtmlParser::ExtractCharsetInformation
886 //-----------------------------------------------------------------------------
888 class wxMetaTagParser
: public wx28HtmlParser
891 wxMetaTagParser() { }
893 wxObject
* GetProduct() { return NULL
; }
896 virtual void AddText(const wxChar
* WXUNUSED(txt
)) {}
898 DECLARE_NO_COPY_CLASS(wxMetaTagParser
)
901 class wxMetaTagHandler
: public wx28HtmlTagHandler
904 wxMetaTagHandler(wxString
*retval
) : wx28HtmlTagHandler(), m_retval(retval
) {}
905 wxString
GetSupportedTags() { return wxT("META,BODY"); }
906 bool HandleTag(const wx28HtmlTag
& tag
);
911 DECLARE_NO_COPY_CLASS(wxMetaTagHandler
)
914 bool wxMetaTagHandler::HandleTag(const wx28HtmlTag
& tag
)
916 if (tag
.GetName() == wxT("BODY"))
918 m_Parser
->StopParsing();
922 if (tag
.HasParam(wxT("HTTP-EQUIV")) &&
923 tag
.GetParam(wxT("HTTP-EQUIV")).IsSameAs(wxT("Content-Type"), false) &&
924 tag
.HasParam(wxT("CONTENT")))
926 wxString content
= tag
.GetParam(wxT("CONTENT")).Lower();
927 if (content
.Left(19) == wxT("text/html; charset="))
929 *m_retval
= content
.Mid(19);
930 m_Parser
->StopParsing();
938 wxString
wx28HtmlParser::ExtractCharsetInformation(const wxString
& markup
)
941 wxMetaTagParser
*parser
= new wxMetaTagParser();
944 parser
->AddTagHandler(new wxMetaTagHandler(&charset
));
945 parser
->Parse(markup
);