Add <span> tag and limited support for CSS styles to wxHTML.
[wxWidgets.git] / src / html / htmltag.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/html/htmltag.cpp
3 // Purpose: wxHtmlTag class (represents single tag)
4 // Author: Vaclav Slavik
5 // RCS-ID: $Id$
6 // Copyright: (c) 1999 Vaclav Slavik
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 #include "wx/wxprec.h"
11
12 #ifdef __BORLANDC__
13 #pragma hdrstop
14 #endif
15
16 #if wxUSE_HTML
17
18 #include "wx/html/htmltag.h"
19
20 #ifndef WX_PRECOMP
21 #include "wx/colour.h"
22 #include "wx/wxcrtvararg.h"
23 #endif
24
25 #include "wx/html/htmlpars.h"
26 #include "wx/html/styleparams.h"
27
28 #include "wx/vector.h"
29
30 #include <stdio.h> // for vsscanf
31 #include <stdarg.h>
32
33 //-----------------------------------------------------------------------------
34 // wxHtmlTagsCache
35 //-----------------------------------------------------------------------------
36
37 struct wxHtmlCacheItem
38 {
39 // this is "pos" value passed to wxHtmlTag's constructor.
40 // it is position of '<' character of the tag
41 wxString::const_iterator Key;
42
43 // Tag type
44 enum Type
45 {
46 Type_Normal, // normal tag with a matching ending tag
47 Type_NoMatchingEndingTag, // there's no ending tag for this tag
48 Type_EndingTag // this is ending tag </..>
49 };
50 Type type;
51
52 // end positions for the tag:
53 // end1 is '<' of ending tag,
54 // end2 is '>' or both are
55 wxString::const_iterator End1, End2;
56
57 // name of this tag
58 wxChar *Name;
59 };
60
61 // NB: this is an empty class and not typedef because of forward declaration
62 class wxHtmlTagsCacheData : public wxVector<wxHtmlCacheItem>
63 {
64 };
65
66 bool wxIsCDATAElement(const wxChar *tag)
67 {
68 return (wxStrcmp(tag, wxT("SCRIPT")) == 0) ||
69 (wxStrcmp(tag, wxT("STYLE")) == 0);
70 }
71
72 bool wxIsCDATAElement(const wxString& tag)
73 {
74 return (wxStrcmp(tag.wx_str(), wxS("SCRIPT")) == 0) ||
75 (wxStrcmp(tag.wx_str(), wxS("STYLE")) == 0);
76 }
77
78 wxHtmlTagsCache::wxHtmlTagsCache(const wxString& source)
79 {
80 m_Cache = new wxHtmlTagsCacheData;
81 m_CachePos = 0;
82
83 wxChar tagBuffer[256];
84
85 const wxString::const_iterator end = source.end();
86 for ( wxString::const_iterator pos = source.begin(); pos < end; ++pos )
87 {
88 if (*pos == wxT('<')) // tag found:
89 {
90 // don't cache comment tags
91 if ( wxHtmlParser::SkipCommentTag(pos, source.end()) )
92 continue;
93
94 size_t tg = Cache().size();
95 Cache().push_back(wxHtmlCacheItem());
96
97 wxString::const_iterator stpos = pos++;
98 Cache()[tg].Key = stpos;
99
100 int i;
101 for ( i = 0;
102 pos < end && i < (int)WXSIZEOF(tagBuffer) - 1 &&
103 *pos != wxT('>') && !wxIsspace(*pos);
104 ++i, ++pos )
105 {
106 tagBuffer[i] = (wxChar)wxToupper(*pos);
107 }
108 tagBuffer[i] = wxT('\0');
109
110 Cache()[tg].Name = new wxChar[i+1];
111 memcpy(Cache()[tg].Name, tagBuffer, (i+1)*sizeof(wxChar));
112
113 while (pos < end && *pos != wxT('>'))
114 ++pos;
115
116 if ((stpos+1) < end && *(stpos+1) == wxT('/')) // ending tag:
117 {
118 Cache()[tg].type = wxHtmlCacheItem::Type_EndingTag;
119 // find matching begin tag:
120 for (i = tg; i >= 0; i--)
121 {
122 if ((Cache()[i].type == wxHtmlCacheItem::Type_NoMatchingEndingTag) && (wxStrcmp(Cache()[i].Name, tagBuffer+1) == 0))
123 {
124 Cache()[i].type = wxHtmlCacheItem::Type_Normal;
125 Cache()[i].End1 = stpos;
126 Cache()[i].End2 = pos + 1;
127 break;
128 }
129 }
130 }
131 else
132 {
133 Cache()[tg].type = wxHtmlCacheItem::Type_NoMatchingEndingTag;
134
135 if (wxIsCDATAElement(tagBuffer))
136 {
137 // store the orig pos in case we are missing the closing
138 // tag (see below)
139 const wxString::const_iterator old_pos = pos;
140 bool foundCloseTag = false;
141
142 // find next matching tag
143 int tag_len = wxStrlen(tagBuffer);
144 while (pos < end)
145 {
146 // find the ending tag
147 while (pos + 1 < end &&
148 (*pos != '<' || *(pos+1) != '/'))
149 ++pos;
150 if (*pos == '<')
151 ++pos;
152
153 // see if it matches
154 int match_pos = 0;
155 while (pos < end && match_pos < tag_len )
156 {
157 wxChar c = *pos;
158 if ( c == '>' || c == '<' )
159 break;
160
161 // cast to wxChar needed to suppress warning in
162 // Unicode build
163 if ((wxChar)wxToupper(c) == tagBuffer[match_pos])
164 {
165 ++match_pos;
166 }
167 else if (c == wxT(' ') || c == wxT('\n') ||
168 c == wxT('\r') || c == wxT('\t'))
169 {
170 // need to skip over these
171 }
172 else
173 {
174 match_pos = 0;
175 }
176 ++pos;
177 }
178
179 // found a match
180 if (match_pos == tag_len)
181 {
182 pos = pos - tag_len - 3;
183 foundCloseTag = true;
184 break;
185 }
186 else // keep looking for the closing tag
187 {
188 ++pos;
189 }
190 }
191 if (!foundCloseTag)
192 {
193 // we didn't find closing tag; this means the markup
194 // is incorrect and the best thing we can do is to
195 // ignore the unclosed tag and continue parsing as if
196 // it didn't exist:
197 pos = old_pos;
198 }
199 }
200 }
201 }
202 }
203
204 // ok, we're done, now we'll free .Name members of cache - we don't need it anymore:
205 for ( wxHtmlTagsCacheData::iterator i = Cache().begin();
206 i != Cache().end(); ++i )
207 {
208 delete[] i->Name;
209 i->Name = NULL;
210 }
211 }
212
213 wxHtmlTagsCache::~wxHtmlTagsCache()
214 {
215 delete m_Cache;
216 }
217
218 void wxHtmlTagsCache::QueryTag(const wxString::const_iterator& at,
219 const wxString::const_iterator& inputEnd,
220 wxString::const_iterator *end1,
221 wxString::const_iterator *end2,
222 bool *hasEnding)
223 {
224 if (Cache().empty())
225 return;
226
227 if (Cache()[m_CachePos].Key != at)
228 {
229 int delta = (at < Cache()[m_CachePos].Key) ? -1 : 1;
230 do
231 {
232 m_CachePos += delta;
233
234 if ( m_CachePos < 0 || m_CachePos >= (int)Cache().size() )
235 {
236 if ( m_CachePos < 0 )
237 m_CachePos = 0;
238 else
239 m_CachePos = Cache().size() - 1;
240 // something is very wrong with HTML, give up by returning an
241 // impossibly large value which is going to be ignored by the
242 // caller
243 *end1 =
244 *end2 = inputEnd;
245 *hasEnding = true;
246 return;
247 }
248 }
249 while (Cache()[m_CachePos].Key != at);
250 }
251
252 switch ( Cache()[m_CachePos].type )
253 {
254 case wxHtmlCacheItem::Type_Normal:
255 *end1 = Cache()[m_CachePos].End1;
256 *end2 = Cache()[m_CachePos].End2;
257 *hasEnding = true;
258 break;
259
260 case wxHtmlCacheItem::Type_EndingTag:
261 wxFAIL_MSG("QueryTag called for ending tag - can't be");
262 // but if it does happen, fall through, better than crashing
263
264 case wxHtmlCacheItem::Type_NoMatchingEndingTag:
265 // If input HTML is invalid and there's no closing tag for this
266 // one, pretend that it runs all the way to the end of input
267 *end1 = inputEnd;
268 *end2 = inputEnd;
269 *hasEnding = false;
270 break;
271 }
272 }
273
274
275
276
277 //-----------------------------------------------------------------------------
278 // wxHtmlTag
279 //-----------------------------------------------------------------------------
280
281 wxHtmlTag::wxHtmlTag(wxHtmlTag *parent,
282 const wxString *source,
283 const wxString::const_iterator& pos,
284 const wxString::const_iterator& end_pos,
285 wxHtmlTagsCache *cache,
286 wxHtmlEntitiesParser *entParser)
287 {
288 /* Setup DOM relations */
289
290 m_Next = NULL;
291 m_FirstChild = m_LastChild = NULL;
292 m_Parent = parent;
293 if (parent)
294 {
295 m_Prev = m_Parent->m_LastChild;
296 if (m_Prev == NULL)
297 m_Parent->m_FirstChild = this;
298 else
299 m_Prev->m_Next = this;
300 m_Parent->m_LastChild = this;
301 }
302 else
303 m_Prev = NULL;
304
305 /* Find parameters and their values: */
306
307 wxChar c wxDUMMY_INITIALIZE(0);
308
309 // fill-in name, params and begin pos:
310 wxString::const_iterator i(pos+1);
311
312 // find tag's name and convert it to uppercase:
313 while ((i < end_pos) &&
314 ((c = *(i++)) != wxT(' ') && c != wxT('\r') &&
315 c != wxT('\n') && c != wxT('\t') &&
316 c != wxT('>') && c != wxT('/')))
317 {
318 if ((c >= wxT('a')) && (c <= wxT('z')))
319 c -= (wxT('a') - wxT('A'));
320 m_Name << c;
321 }
322
323 // if the tag has parameters, read them and "normalize" them,
324 // i.e. convert to uppercase, replace whitespaces by spaces and
325 // remove whitespaces around '=':
326 if (*(i-1) != wxT('>'))
327 {
328 #define IS_WHITE(c) (c == wxT(' ') || c == wxT('\r') || \
329 c == wxT('\n') || c == wxT('\t'))
330 wxString pname, pvalue;
331 wxChar quote;
332 enum
333 {
334 ST_BEFORE_NAME = 1,
335 ST_NAME,
336 ST_BEFORE_EQ,
337 ST_BEFORE_VALUE,
338 ST_VALUE
339 } state;
340
341 quote = 0;
342 state = ST_BEFORE_NAME;
343 while (i < end_pos)
344 {
345 c = *(i++);
346
347 if (c == wxT('>') && !(state == ST_VALUE && quote != 0))
348 {
349 if (state == ST_BEFORE_EQ || state == ST_NAME)
350 {
351 m_ParamNames.Add(pname);
352 m_ParamValues.Add(wxGetEmptyString());
353 }
354 else if (state == ST_VALUE && quote == 0)
355 {
356 m_ParamNames.Add(pname);
357 if (entParser)
358 m_ParamValues.Add(entParser->Parse(pvalue));
359 else
360 m_ParamValues.Add(pvalue);
361 }
362 break;
363 }
364 switch (state)
365 {
366 case ST_BEFORE_NAME:
367 if (!IS_WHITE(c))
368 {
369 pname = c;
370 state = ST_NAME;
371 }
372 break;
373 case ST_NAME:
374 if (IS_WHITE(c))
375 state = ST_BEFORE_EQ;
376 else if (c == wxT('='))
377 state = ST_BEFORE_VALUE;
378 else
379 pname << c;
380 break;
381 case ST_BEFORE_EQ:
382 if (c == wxT('='))
383 state = ST_BEFORE_VALUE;
384 else if (!IS_WHITE(c))
385 {
386 m_ParamNames.Add(pname);
387 m_ParamValues.Add(wxGetEmptyString());
388 pname = c;
389 state = ST_NAME;
390 }
391 break;
392 case ST_BEFORE_VALUE:
393 if (!IS_WHITE(c))
394 {
395 if (c == wxT('"') || c == wxT('\''))
396 quote = c, pvalue = wxGetEmptyString();
397 else
398 quote = 0, pvalue = c;
399 state = ST_VALUE;
400 }
401 break;
402 case ST_VALUE:
403 if ((quote != 0 && c == quote) ||
404 (quote == 0 && IS_WHITE(c)))
405 {
406 m_ParamNames.Add(pname);
407 if (quote == 0)
408 {
409 // VS: backward compatibility, no real reason,
410 // but wxHTML code relies on this... :(
411 pvalue.MakeUpper();
412 }
413 if (entParser)
414 m_ParamValues.Add(entParser->Parse(pvalue));
415 else
416 m_ParamValues.Add(pvalue);
417 state = ST_BEFORE_NAME;
418 }
419 else
420 pvalue << c;
421 break;
422 }
423 }
424
425 #undef IS_WHITE
426 }
427 m_Begin = i;
428 cache->QueryTag(pos, source->end(), &m_End1, &m_End2, &m_hasEnding);
429 if (m_End1 > end_pos) m_End1 = end_pos;
430 if (m_End2 > end_pos) m_End2 = end_pos;
431
432 #if WXWIN_COMPATIBILITY_2_8
433 m_sourceStart = source->begin();
434 #endif
435
436 // Try to parse any style parameters that can be handled simply by
437 // converting them to the equivalent HTML 3 attributes: this is a far cry
438 // from perfect but better than nothing.
439 static const struct EquivAttr
440 {
441 const char *style;
442 const char *attr;
443 } equivAttrs[] =
444 {
445 { "text-align", "ALIGN" },
446 { "width", "WIDTH" },
447 { "vertical-align", "VALIGN" },
448 { "background", "BGCOLOR" },
449 };
450
451 wxHtmlStyleParams styleParams(*this);
452 for ( unsigned n = 0; n < WXSIZEOF(equivAttrs); n++ )
453 {
454 const EquivAttr& ea = equivAttrs[n];
455 if ( styleParams.HasParam(ea.style) && !HasParam(ea.attr) )
456 {
457 m_ParamNames.Add(ea.attr);
458 m_ParamValues.Add(styleParams.GetParam(ea.style));
459 }
460 }
461 }
462
463 wxHtmlTag::~wxHtmlTag()
464 {
465 wxHtmlTag *t1, *t2;
466 t1 = m_FirstChild;
467 while (t1)
468 {
469 t2 = t1->GetNextSibling();
470 delete t1;
471 t1 = t2;
472 }
473 }
474
475 bool wxHtmlTag::HasParam(const wxString& par) const
476 {
477 return (m_ParamNames.Index(par, false) != wxNOT_FOUND);
478 }
479
480 wxString wxHtmlTag::GetParam(const wxString& par, bool with_quotes) const
481 {
482 int index = m_ParamNames.Index(par, false);
483 if (index == wxNOT_FOUND)
484 return wxGetEmptyString();
485 if (with_quotes)
486 {
487 // VS: backward compatibility, seems to be never used by wxHTML...
488 wxString s;
489 s << wxT('"') << m_ParamValues[index] << wxT('"');
490 return s;
491 }
492 else
493 return m_ParamValues[index];
494 }
495
496 int wxHtmlTag::ScanParam(const wxString& par,
497 const char *format,
498 void *param) const
499 {
500 wxString parval = GetParam(par);
501 return wxSscanf(parval, format, param);
502 }
503
504 int wxHtmlTag::ScanParam(const wxString& par,
505 const wchar_t *format,
506 void *param) const
507 {
508 wxString parval = GetParam(par);
509 return wxSscanf(parval, format, param);
510 }
511
512 /* static */
513 bool wxHtmlTag::ParseAsColour(const wxString& str, wxColour *clr)
514 {
515 wxCHECK_MSG( clr, false, wxT("invalid colour argument") );
516
517 // handle colours defined in HTML 4.0 first:
518 if (str.length() > 1 && str[0] != wxT('#'))
519 {
520 #define HTML_COLOUR(name, r, g, b) \
521 if (str.IsSameAs(wxS(name), false)) \
522 { clr->Set(r, g, b); return true; }
523 HTML_COLOUR("black", 0x00,0x00,0x00)
524 HTML_COLOUR("silver", 0xC0,0xC0,0xC0)
525 HTML_COLOUR("gray", 0x80,0x80,0x80)
526 HTML_COLOUR("white", 0xFF,0xFF,0xFF)
527 HTML_COLOUR("maroon", 0x80,0x00,0x00)
528 HTML_COLOUR("red", 0xFF,0x00,0x00)
529 HTML_COLOUR("purple", 0x80,0x00,0x80)
530 HTML_COLOUR("fuchsia", 0xFF,0x00,0xFF)
531 HTML_COLOUR("green", 0x00,0x80,0x00)
532 HTML_COLOUR("lime", 0x00,0xFF,0x00)
533 HTML_COLOUR("olive", 0x80,0x80,0x00)
534 HTML_COLOUR("yellow", 0xFF,0xFF,0x00)
535 HTML_COLOUR("navy", 0x00,0x00,0x80)
536 HTML_COLOUR("blue", 0x00,0x00,0xFF)
537 HTML_COLOUR("teal", 0x00,0x80,0x80)
538 HTML_COLOUR("aqua", 0x00,0xFF,0xFF)
539 #undef HTML_COLOUR
540 }
541
542 // then try to parse #rrggbb representations or set from other well
543 // known names (note that this doesn't strictly conform to HTML spec,
544 // but it doesn't do real harm -- but it *must* be done after the standard
545 // colors are handled above):
546 if (clr->Set(str))
547 return true;
548
549 return false;
550 }
551
552 bool wxHtmlTag::GetParamAsColour(const wxString& par, wxColour *clr) const
553 {
554 const wxString str = GetParam(par);
555 return !str.empty() && ParseAsColour(str, clr);
556 }
557
558 bool wxHtmlTag::GetParamAsInt(const wxString& par, int *clr) const
559 {
560 if ( !HasParam(par) )
561 return false;
562
563 long i;
564 if ( !GetParam(par).ToLong(&i) )
565 return false;
566
567 *clr = (int)i;
568 return true;
569 }
570
571 wxString wxHtmlTag::GetAllParams() const
572 {
573 // VS: this function is for backward compatibility only,
574 // never used by wxHTML
575 wxString s;
576 size_t cnt = m_ParamNames.GetCount();
577 for (size_t i = 0; i < cnt; i++)
578 {
579 s << m_ParamNames[i];
580 s << wxT('=');
581 if (m_ParamValues[i].Find(wxT('"')) != wxNOT_FOUND)
582 s << wxT('\'') << m_ParamValues[i] << wxT('\'');
583 else
584 s << wxT('"') << m_ParamValues[i] << wxT('"');
585 }
586 return s;
587 }
588
589 wxHtmlTag *wxHtmlTag::GetFirstSibling() const
590 {
591 if (m_Parent)
592 return m_Parent->m_FirstChild;
593 else
594 {
595 wxHtmlTag *cur = (wxHtmlTag*)this;
596 while (cur->m_Prev)
597 cur = cur->m_Prev;
598 return cur;
599 }
600 }
601
602 wxHtmlTag *wxHtmlTag::GetLastSibling() const
603 {
604 if (m_Parent)
605 return m_Parent->m_LastChild;
606 else
607 {
608 wxHtmlTag *cur = (wxHtmlTag*)this;
609 while (cur->m_Next)
610 cur = cur->m_Next;
611 return cur;
612 }
613 }
614
615 wxHtmlTag *wxHtmlTag::GetNextTag() const
616 {
617 if (m_FirstChild) return m_FirstChild;
618 if (m_Next) return m_Next;
619 wxHtmlTag *cur = m_Parent;
620 if (!cur) return NULL;
621 while (cur->m_Parent && !cur->m_Next)
622 cur = cur->m_Parent;
623 return cur->m_Next;
624 }
625
626 #endif