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 void wxHtmlParser::CreateDOMSubTree(wxHtmlTag
*cur
,
131 int begin_pos
, int end_pos
,
132 wxHtmlTagsCache
*cache
)
134 if (end_pos
<= begin_pos
) return;
138 int textBeginning
= begin_pos
;
142 c
= m_Source
.GetChar(i
);
146 // add text to m_TextPieces:
147 if (i
- textBeginning
> 0)
149 wxHtmlTextPiece(textBeginning
, i
- textBeginning
));
151 // if it is a comment, skip it:
152 if (i
< end_pos
-6 && m_Source
.GetChar(i
+1) == wxT('!') &&
153 m_Source
.GetChar(i
+2) == wxT('-') &&
154 m_Source
.GetChar(i
+3) == wxT('-'))
156 // Comments begin with "<!--" and end with "--[ \t\r\n]*>"
157 // according to HTML 4.0
162 c
= m_Source
.GetChar(i
++);
163 if ((c
== wxT(' ') || c
== wxT('\n') ||
164 c
== wxT('\r') || c
== wxT('\t')) && dashes
>= 2) {}
165 else if (c
== wxT('>') && dashes
>= 2)
170 else if (c
== wxT('-'))
177 // add another tag to the tree:
178 else if (i
< end_pos
-1 && m_Source
.GetChar(i
+1) != wxT('/'))
182 chd
= new wxHtmlTag(cur
, m_Source
,
183 i
, end_pos
, cache
, m_entitiesParser
);
186 chd
= new wxHtmlTag(NULL
, m_Source
,
187 i
, end_pos
, cache
, m_entitiesParser
);
190 // if this is the first tag to be created make the root
191 // m_Tags point to it:
196 // if there is already a root tag add this tag as
198 chd
->m_Prev
= m_Tags
->GetLastSibling();
199 chd
->m_Prev
->m_Next
= chd
;
203 if (chd
->HasEnding())
205 CreateDOMSubTree(chd
,
206 chd
->GetBeginPos(), chd
->GetEndPos1(),
208 i
= chd
->GetEndPos2();
211 i
= chd
->GetBeginPos();
215 // ... or skip ending tag:
218 while (i
< end_pos
&& m_Source
.GetChar(i
) != wxT('>')) i
++;
225 // add remaining text to m_TextPieces:
226 if (end_pos
- textBeginning
> 0)
228 wxHtmlTextPiece(textBeginning
, end_pos
- textBeginning
));
231 void wxHtmlParser::DestroyDOMTree()
237 t2
= t1
->GetNextSibling();
241 m_Tags
= m_CurTag
= NULL
;
247 void wxHtmlParser::DoParsing()
251 DoParsing(0, m_Source
.Length());
254 void wxHtmlParser::DoParsing(int begin_pos
, int end_pos
)
256 if (end_pos
<= begin_pos
) return;
258 wxHtmlTextPieces
& pieces
= *m_TextPieces
;
259 size_t piecesCnt
= pieces
.GetCount();
261 while (begin_pos
< end_pos
)
263 while (m_CurTag
&& m_CurTag
->GetBeginPos() < begin_pos
)
264 m_CurTag
= m_CurTag
->GetNextTag();
265 while (m_CurTextPiece
< piecesCnt
&&
266 pieces
[m_CurTextPiece
].m_pos
< begin_pos
)
269 if (m_CurTextPiece
< piecesCnt
&&
271 pieces
[m_CurTextPiece
].m_pos
< m_CurTag
->GetBeginPos()))
274 AddText(GetEntitiesParser()->Parse(
275 m_Source
.Mid(pieces
[m_CurTextPiece
].m_pos
,
276 pieces
[m_CurTextPiece
].m_lng
)));
277 begin_pos
= pieces
[m_CurTextPiece
].m_pos
+
278 pieces
[m_CurTextPiece
].m_lng
;
286 if (m_CurTag
->HasEnding())
287 begin_pos
= m_CurTag
->GetEndPos2();
289 begin_pos
= m_CurTag
->GetBeginPos();
291 wxHtmlTag
*t
= m_CurTag
;
292 m_CurTag
= m_CurTag
->GetNextTag();
301 void wxHtmlParser::AddTag(const wxHtmlTag
& tag
)
306 h
= (wxHtmlTagHandler
*) m_HandlersHash
.Get(tag
.GetName());
309 inner
= h
->HandleTag(tag
);
316 DoParsing(tag
.GetBeginPos(), tag
.GetEndPos1());
320 void wxHtmlParser::AddTagHandler(wxHtmlTagHandler
*handler
)
322 wxString
s(handler
->GetSupportedTags());
323 wxStringTokenizer
tokenizer(s
, wxT(", "));
325 while (tokenizer
.HasMoreTokens())
326 m_HandlersHash
.Put(tokenizer
.GetNextToken(), handler
);
328 if (m_HandlersList
.IndexOf(handler
) == wxNOT_FOUND
)
329 m_HandlersList
.Append(handler
);
331 handler
->SetParser(this);
334 void wxHtmlParser::PushTagHandler(wxHtmlTagHandler
*handler
, wxString tags
)
336 wxStringTokenizer
tokenizer(tags
, wxT(", "));
339 if (m_HandlersStack
== NULL
)
341 m_HandlersStack
= new wxList
;
342 m_HandlersStack
->DeleteContents(TRUE
);
345 m_HandlersStack
->Insert(new wxHashTable(m_HandlersHash
));
347 while (tokenizer
.HasMoreTokens())
349 key
= tokenizer
.GetNextToken();
350 m_HandlersHash
.Delete(key
);
351 m_HandlersHash
.Put(key
, handler
);
355 void wxHtmlParser::PopTagHandler()
359 if (m_HandlersStack
== NULL
||
360 (first
= m_HandlersStack
->GetFirst()) == NULL
)
362 wxLogWarning(_("Warning: attempt to remove HTML tag handler from empty stack."));
365 m_HandlersHash
= *((wxHashTable
*) first
->GetData());
366 m_HandlersStack
->DeleteNode(first
);
369 void wxHtmlParser::SetSourceAndSaveState(const wxString
& src
)
371 wxHtmlParserState
*s
= new wxHtmlParserState
;
373 s
->m_curTag
= m_CurTag
;
375 s
->m_textPieces
= m_TextPieces
;
376 s
->m_curTextPiece
= m_CurTextPiece
;
377 s
->m_source
= m_Source
;
379 s
->m_nextState
= m_SavedStates
;
386 m_Source
= wxEmptyString
;
391 bool wxHtmlParser::RestoreState()
393 if (!m_SavedStates
) return FALSE
;
397 wxHtmlParserState
*s
= m_SavedStates
;
398 m_SavedStates
= s
->m_nextState
;
400 m_CurTag
= s
->m_curTag
;
402 m_TextPieces
= s
->m_textPieces
;
403 m_CurTextPiece
= s
->m_curTextPiece
;
404 m_Source
= s
->m_source
;
410 //-----------------------------------------------------------------------------
412 //-----------------------------------------------------------------------------
414 IMPLEMENT_ABSTRACT_CLASS(wxHtmlTagHandler
,wxObject
)
417 //-----------------------------------------------------------------------------
418 // wxHtmlEntitiesParser
419 //-----------------------------------------------------------------------------
421 IMPLEMENT_DYNAMIC_CLASS(wxHtmlEntitiesParser
,wxObject
)
423 wxHtmlEntitiesParser::wxHtmlEntitiesParser()
424 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
425 : m_conv(NULL
), m_encoding(wxFONTENCODING_SYSTEM
)
430 wxHtmlEntitiesParser::~wxHtmlEntitiesParser()
432 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
437 void wxHtmlEntitiesParser::SetEncoding(wxFontEncoding encoding
)
439 #if wxUSE_WCHAR_T && !wxUSE_UNICODE
440 if (encoding
== m_encoding
)
445 m_encoding
= encoding
;
446 if (m_encoding
== wxFONTENCODING_SYSTEM
)
449 m_conv
= new wxCSConv(wxFontMapper::GetEncodingName(m_encoding
));
455 wxString
wxHtmlEntitiesParser::Parse(const wxString
& input
)
457 const wxChar
*c
, *last
;
458 const wxChar
*in_str
= input
.c_str();
461 output
.reserve(input
.length());
463 for (c
= in_str
, last
= in_str
; *c
!= wxT('\0'); c
++)
468 output
.append(last
, c
- last
);
469 if (++c
== wxT('\0')) break;
472 const wxChar
*ent_s
= c
;
475 for (; (*c
>= wxT('a') && *c
<= wxT('z')) ||
476 (*c
>= wxT('A') && *c
<= wxT('Z')) ||
477 (*c
>= wxT('0') && *c
<= wxT('9')) ||
478 *c
== wxT('_') || *c
== wxT('#'); c
++) {}
479 entity
.append(ent_s
, c
- ent_s
);
480 if (*c
!= wxT(';')) c
--;
482 entity_char
= GetEntityChar(entity
);
484 output
<< entity_char
;
487 output
.append(ent_s
-1, c
-ent_s
+2);
488 wxLogDebug(wxT("Unrecognized HTML entity: '%s'"), entity
.c_str());
492 if (*last
!= wxT('\0'))
497 struct wxHtmlEntityInfo
503 extern "C" int LINKAGEMODE
wxHtmlEntityCompare(const void *key
, const void *item
)
505 return wxStrcmp((wxChar
*)key
, ((wxHtmlEntityInfo
*)item
)->name
);
509 wxChar
wxHtmlEntitiesParser::GetCharForCode(unsigned code
)
514 wbuf
[0] = (wchar_t)code
;
516 wxMBConv
*conv
= m_conv
? m_conv
: &wxConvLocal
;
517 if (conv
->WC2MB(buf
, wbuf
, 2) == (size_t)-1)
521 return (code
< 256) ? (wxChar
)code
: '?';
526 wxChar
wxHtmlEntitiesParser::GetEntityChar(const wxString
& entity
)
530 if (entity
[0] == wxT('#'))
532 const wxChar
*ent_s
= entity
.c_str();
533 const wxChar
*format
;
535 if (ent_s
[1] == wxT('x') || ent_s
[1] == wxT('X'))
544 if (wxSscanf(ent_s
, format
, &code
) != 1)
549 static wxHtmlEntityInfo substitutions
[] = {
550 { wxT("AElig"),198 },
551 { wxT("Aacute"),193 },
552 { wxT("Acirc"),194 },
553 { wxT("Agrave"),192 },
554 { wxT("Alpha"),913 },
555 { wxT("Aring"),197 },
556 { wxT("Atilde"),195 },
559 { wxT("Ccedil"),199 },
561 { wxT("Dagger"),8225 },
562 { wxT("Delta"),916 },
564 { wxT("Eacute"),201 },
565 { wxT("Ecirc"),202 },
566 { wxT("Egrave"),200 },
567 { wxT("Epsilon"),917 },
570 { wxT("Gamma"),915 },
571 { wxT("Iacute"),205 },
572 { wxT("Icirc"),206 },
573 { wxT("Igrave"),204 },
576 { wxT("Kappa"),922 },
577 { wxT("Lambda"),923 },
579 { wxT("Ntilde"),209 },
581 { wxT("OElig"),338 },
582 { wxT("Oacute"),211 },
583 { wxT("Ocirc"),212 },
584 { wxT("Ograve"),210 },
585 { wxT("Omega"),937 },
586 { wxT("Omicron"),927 },
587 { wxT("Oslash"),216 },
588 { wxT("Otilde"),213 },
592 { wxT("Prime"),8243 },
595 { wxT("Scaron"),352 },
596 { wxT("Sigma"),931 },
597 { wxT("THORN"),222 },
599 { wxT("Theta"),920 },
600 { wxT("Uacute"),218 },
601 { wxT("Ucirc"),219 },
602 { wxT("Ugrave"),217 },
603 { wxT("Upsilon"),933 },
606 { wxT("Yacute"),221 },
609 { wxT("aacute"),225 },
610 { wxT("acirc"),226 },
611 { wxT("acute"),180 },
612 { wxT("aelig"),230 },
613 { wxT("agrave"),224 },
614 { wxT("alefsym"),8501 },
615 { wxT("alpha"),945 },
619 { wxT("aring"),229 },
620 { wxT("asymp"),8776 },
621 { wxT("atilde"),227 },
623 { wxT("bdquo"),8222 },
625 { wxT("brvbar"),166 },
626 { wxT("bull"),8226 },
628 { wxT("ccedil"),231 },
629 { wxT("cedil"),184 },
633 { wxT("clubs"),9827 },
634 { wxT("cong"),8773 },
636 { wxT("crarr"),8629 },
638 { wxT("curren"),164 },
639 { wxT("dArr"),8659 },
640 { wxT("dagger"),8224 },
641 { wxT("darr"),8595 },
643 { wxT("delta"),948 },
644 { wxT("diams"),9830 },
645 { wxT("divide"),247 },
646 { wxT("eacute"),233 },
647 { wxT("ecirc"),234 },
648 { wxT("egrave"),232 },
649 { wxT("empty"),8709 },
650 { wxT("emsp"),8195 },
651 { wxT("ensp"),8194 },
652 { wxT("epsilon"),949 },
653 { wxT("equiv"),8801 },
657 { wxT("euro"),8364 },
658 { wxT("exist"),8707 },
660 { wxT("forall"),8704 },
661 { wxT("frac12"),189 },
662 { wxT("frac14"),188 },
663 { wxT("frac34"),190 },
664 { wxT("frasl"),8260 },
665 { wxT("gamma"),947 },
668 { wxT("hArr"),8660 },
669 { wxT("harr"),8596 },
670 { wxT("hearts"),9829 },
671 { wxT("hellip"),8230 },
672 { wxT("iacute"),237 },
673 { wxT("icirc"),238 },
674 { wxT("iexcl"),161 },
675 { wxT("igrave"),236 },
676 { wxT("image"),8465 },
677 { wxT("infin"),8734 },
680 { wxT("iquest"),191 },
681 { wxT("isin"),8712 },
683 { wxT("kappa"),954 },
684 { wxT("lArr"),8656 },
685 { wxT("lambda"),955 },
686 { wxT("lang"),9001 },
687 { wxT("laquo"),171 },
688 { wxT("larr"),8592 },
689 { wxT("lceil"),8968 },
690 { wxT("ldquo"),8220 },
692 { wxT("lfloor"),8970 },
693 { wxT("lowast"),8727 },
696 { wxT("lsaquo"),8249 },
697 { wxT("lsquo"),8216 },
700 { wxT("mdash"),8212 },
701 { wxT("micro"),181 },
702 { wxT("middot"),183 },
703 { wxT("minus"),8722 },
705 { wxT("nabla"),8711 },
707 { wxT("ndash"),8211 },
711 { wxT("notin"),8713 },
712 { wxT("nsub"),8836 },
713 { wxT("ntilde"),241 },
715 { wxT("oacute"),243 },
716 { wxT("ocirc"),244 },
717 { wxT("oelig"),339 },
718 { wxT("ograve"),242 },
719 { wxT("oline"),8254 },
720 { wxT("omega"),969 },
721 { wxT("omicron"),959 },
722 { wxT("oplus"),8853 },
726 { wxT("oslash"),248 },
727 { wxT("otilde"),245 },
728 { wxT("otimes"),8855 },
731 { wxT("part"),8706 },
732 { wxT("permil"),8240 },
733 { wxT("perp"),8869 },
737 { wxT("plusmn"),177 },
738 { wxT("pound"),163 },
739 { wxT("prime"),8242 },
740 { wxT("prod"),8719 },
741 { wxT("prop"),8733 },
744 { wxT("rArr"),8658 },
745 { wxT("radic"),8730 },
746 { wxT("rang"),9002 },
747 { wxT("raquo"),187 },
748 { wxT("rarr"),8594 },
749 { wxT("rceil"),8969 },
750 { wxT("rdquo"),8221 },
751 { wxT("real"),8476 },
753 { wxT("rfloor"),8971 },
756 { wxT("rsaquo"),8250 },
757 { wxT("rsquo"),8217 },
758 { wxT("sbquo"),8218 },
759 { wxT("scaron"),353 },
760 { wxT("sdot"),8901 },
763 { wxT("sigma"),963 },
764 { wxT("sigmaf"),962 },
766 { wxT("spades"),9824 },
768 { wxT("sube"),8838 },
774 { wxT("supe"),8839 },
775 { wxT("szlig"),223 },
777 { wxT("there4"),8756 },
778 { wxT("theta"),952 },
779 { wxT("thetasym"),977 },
780 { wxT("thinsp"),8201 },
781 { wxT("thorn"),254 },
782 { wxT("tilde"),732 },
783 { wxT("times"),215 },
784 { wxT("trade"),8482 },
785 { wxT("uArr"),8657 },
786 { wxT("uacute"),250 },
787 { wxT("uarr"),8593 },
788 { wxT("ucirc"),251 },
789 { wxT("ugrave"),249 },
791 { wxT("upsih"),978 },
792 { wxT("upsilon"),965 },
794 { wxT("weierp"),8472 },
796 { wxT("yacute"),253 },
801 { wxT("zwnj"),8204 },
803 static size_t substitutions_cnt
= 0;
805 if (substitutions_cnt
== 0)
806 while (substitutions
[substitutions_cnt
].code
!= 0)
809 wxHtmlEntityInfo
*info
;
810 info
= (wxHtmlEntityInfo
*) bsearch(entity
.c_str(), substitutions
,
812 sizeof(wxHtmlEntityInfo
),
813 wxHtmlEntityCompare
);
821 return GetCharForCode(code
);
824 wxFSFile
*wxHtmlParser::OpenURL(wxHtmlURLType
WXUNUSED(type
),
825 const wxString
& url
) const
827 return GetFS()->OpenFile(url
);
831 //-----------------------------------------------------------------------------
832 // wxHtmlParser::ExtractCharsetInformation
833 //-----------------------------------------------------------------------------
835 class wxMetaTagParser
: public wxHtmlParser
838 wxObject
* GetProduct() { return NULL
; }
840 virtual void AddText(const wxChar
* WXUNUSED(txt
)) {}
843 class wxMetaTagHandler
: public wxHtmlTagHandler
846 wxMetaTagHandler(wxString
*retval
) : wxHtmlTagHandler(), m_retval(retval
) {}
847 wxString
GetSupportedTags() { return wxT("META,BODY"); }
848 bool HandleTag(const wxHtmlTag
& tag
);
854 bool wxMetaTagHandler::HandleTag(const wxHtmlTag
& tag
)
856 if (tag
.GetName() == _T("BODY"))
858 m_Parser
->StopParsing();
862 if (tag
.HasParam(_T("HTTP-EQUIV")) &&
863 tag
.GetParam(_T("HTTP-EQUIV")) == _T("Content-Type") &&
864 tag
.HasParam(_T("CONTENT")))
866 wxString content
= tag
.GetParam(_T("CONTENT"));
867 if (content
.Left(19) == _T("text/html; charset="))
869 *m_retval
= content
.Mid(19);
870 m_Parser
->StopParsing();
878 wxString
wxHtmlParser::ExtractCharsetInformation(const wxString
& markup
)
881 wxMetaTagParser parser
;
882 parser
.AddTagHandler(new wxMetaTagHandler(&charset
));
883 parser
.Parse(markup
);