1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/richtext/richtexthtml.cpp
3 // Purpose: HTML I/O for wxRichTextCtrl
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // For compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
21 #include "wx/richtext/richtexthtml.h"
26 #include "wx/filename.h"
27 #include "wx/wfstream.h"
28 #include "wx/txtstrm.h"
31 #include "wx/filesys.h"
32 #include "wx/fs_mem.h"
35 IMPLEMENT_DYNAMIC_CLASS(wxRichTextHTMLHandler
, wxRichTextFileHandler
)
37 int wxRichTextHTMLHandler::sm_fileCounter
= 1;
39 /// Can we handle this filename (if using files)? By default, checks the extension.
40 bool wxRichTextHTMLHandler::CanHandle(const wxString
& filename
) const
42 wxString path
, file
, ext
;
43 wxSplitPath(filename
, & path
, & file
, & ext
);
45 return (ext
.Lower() == wxT("html") || ext
.Lower() == wxT("htm"));
50 bool wxRichTextHTMLHandler::DoLoadFile(wxRichTextBuffer
*WXUNUSED(buffer
), wxInputStream
& WXUNUSED(stream
))
56 * We need to output only _changes_ in character formatting.
59 bool wxRichTextHTMLHandler::DoSaveFile(wxRichTextBuffer
*buffer
, wxOutputStream
& stream
)
61 ClearTemporaryImageLocations();
65 wxTextOutputStream
str(stream
);
67 wxTextAttrEx currentParaStyle
= buffer
->GetAttributes();
68 wxTextAttrEx currentCharStyle
= buffer
->GetAttributes();
70 str
<< wxT("<html><head></head><body>\n");
72 str
<< wxT("<table border=0 cellpadding=0 cellspacing=0><tr><td width=\"100%\">");
74 str
<< wxString::Format(wxT("<font face=\"%s\" size=\"%ld\" color=\"%s\" >"),
75 currentParaStyle
.GetFont().GetFaceName().c_str(), PtToSize(currentParaStyle
.GetFont().GetPointSize()),
76 currentParaStyle
.GetTextColour().GetAsString(wxC2S_HTML_SYNTAX
).c_str());
82 wxRichTextObjectList::compatibility_iterator node
= buffer
->GetChildren().GetFirst();
85 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
86 wxASSERT (para
!= NULL
);
90 wxTextAttrEx
paraStyle(para
->GetCombinedAttributes());
92 OutputParagraphFormatting(currentParaStyle
, paraStyle
, stream
);
94 wxRichTextObjectList::compatibility_iterator node2
= para
->GetChildren().GetFirst();
97 wxRichTextObject
* obj
= node2
->GetData();
98 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
99 if (textObj
&& !textObj
->IsEmpty())
101 wxTextAttrEx
charStyle(para
->GetCombinedAttributes(obj
->GetAttributes()));
102 BeginCharacterFormatting(currentCharStyle
, charStyle
, paraStyle
, stream
);
104 wxString text
= textObj
->GetText();
106 if (charStyle
.HasTextEffects() && (charStyle
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
111 EndCharacterFormatting(currentCharStyle
, charStyle
, paraStyle
, stream
);
114 wxRichTextImage
* image
= wxDynamicCast(obj
, wxRichTextImage
);
115 if( image
&& !image
->IsEmpty())
116 WriteImage( image
, stream
);
118 node2
= node2
->GetNext();
122 node
= node
->GetNext();
125 str
<< wxT("</font></td></tr></table></body></html>\n");
130 void wxRichTextHTMLHandler::BeginCharacterFormatting(const wxTextAttrEx
& currentStyle
, const wxTextAttrEx
& thisStyle
, const wxTextAttrEx
& paraStyle
, wxOutputStream
& stream
)
132 wxTextOutputStream
str(stream
);
134 // Is the item a bulleted one?
135 if ( paraStyle
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
137 // Is there any opened list?
142 // Is the item among the previous ones?
143 // Is the item one of the previous list tag's child items?
144 if ((paraStyle
.GetLeftIndent() == (m_indent
+ 100)) || (paraStyle
.GetLeftIndent() < 100))
145 str
<< wxT("<li>"); //Yes it is
148 // No it isn't, so we should close the list tag
149 str
<< (m_is_ul
? wxT("</ul>") : wxT("</ol>"));
151 // And renavigate to new list's horizontal position
152 NavigateToListPosition(paraStyle
, str
);
154 // Get the appropriate tag, an ol for numerical values, an ul for dot, square etc.
156 TypeOfList(paraStyle
, tag
);
157 str
<< tag
<< wxT("<li>");
162 // No there isn't a list.
163 // navigate to new list's horizontal position(indent)
164 NavigateToListPosition(paraStyle
, str
);
166 // Get the appropriate tag, an ol for numerical values, an ul for dot, square etc.
168 TypeOfList(paraStyle
, tag
);
169 str
<< tag
<< wxT("<li>");
171 // Now we have a list, mark it.
177 // The item is not bulleted and there is a list what should be closed now.
180 str
<< (m_is_ul
? wxT("</ul>") : wxT("</ol>"));
182 // And mark as there is no an opened list
186 // does the item have an indentation ?
187 if( paraStyle
.GetLeftIndent() )
189 if (paraStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE
)
193 if ((paraStyle
.GetLeftIndent() + paraStyle
.GetLeftSubIndent()) == m_indent
)
195 if (paraStyle
.GetLeftSubIndent() < 0)
197 str
<< SymbolicIndent(~paraStyle
.GetLeftSubIndent());
202 if (paraStyle
.GetLeftIndent() + paraStyle
.GetLeftSubIndent() > m_indent
)
204 Indent(paraStyle
, str
);
205 m_indent
= paraStyle
.GetLeftIndent() + paraStyle
.GetLeftSubIndent();
206 m_indents
.Add( m_indent
);
210 int i
= m_indents
.size() - 1;
213 if (m_indent
< (paraStyle
.GetLeftIndent() + paraStyle
.GetLeftSubIndent()))
215 Indent(paraStyle
, str
);
216 m_indent
= paraStyle
.GetLeftIndent() + paraStyle
.GetLeftSubIndent();
217 m_indents
.Add( m_indent
);
221 else if (m_indent
== (paraStyle
.GetLeftIndent() + paraStyle
.GetLeftSubIndent()))
223 if (paraStyle
.GetLeftSubIndent() < 0)
225 str
<< SymbolicIndent(~paraStyle
.GetLeftSubIndent());
231 str
<< wxT("</td></tr></table>");
233 m_indents
.RemoveAt(i
);
239 m_indent
= m_indents
[i
-1];
247 Indent(paraStyle
, str
);
248 m_indent
= paraStyle
.GetLeftIndent() + paraStyle
.GetLeftSubIndent();
249 m_indents
.Add( m_indent
);
255 // The item is not indented and there is a table(s) that should be closed now.
257 for (unsigned int i
= 0; i
< m_indents
.size(); i
++)
258 str
<< wxT("</td></tr></table>");
267 // Is there any change in the font properties of the item?
268 if (thisStyle
.GetFont().GetFaceName() != currentStyle
.GetFont().GetFaceName())
270 wxString
faceName(thisStyle
.GetFont().GetFaceName());
271 style
+= wxString::Format(wxT(" face=\"%s\""), faceName
.c_str());
273 if (thisStyle
.GetFont().GetPointSize() != currentStyle
.GetFont().GetPointSize())
274 style
+= wxString::Format(wxT(" size=\"%ld\""), PtToSize(thisStyle
.GetFont().GetPointSize()));
275 if (thisStyle
.GetTextColour() != currentStyle
.GetTextColour() )
277 wxString
color(thisStyle
.GetTextColour().GetAsString(wxC2S_HTML_SYNTAX
));
278 style
+= wxString::Format(wxT(" color=\"%s\""), color
.c_str());
283 str
<< wxString::Format(wxT("<font %s >"), style
.c_str());
287 if (thisStyle
.GetFont().GetWeight() == wxBOLD
)
289 if (thisStyle
.GetFont().GetStyle() == wxITALIC
)
291 if (thisStyle
.GetFont().GetUnderlined())
294 if (thisStyle
.HasURL())
295 str
<< wxT("<a href=\"") << thisStyle
.GetURL() << wxT("\">");
298 void wxRichTextHTMLHandler::EndCharacterFormatting(const wxTextAttrEx
& WXUNUSED(currentStyle
), const wxTextAttrEx
& thisStyle
, const wxTextAttrEx
& WXUNUSED(paraStyle
), wxOutputStream
& stream
)
300 wxTextOutputStream
str(stream
);
302 if (thisStyle
.HasURL())
305 if (thisStyle
.GetFont().GetUnderlined())
307 if (thisStyle
.GetFont().GetStyle() == wxITALIC
)
309 if (thisStyle
.GetFont().GetWeight() == wxBOLD
)
315 str
<< wxT("</font>");
319 /// Output paragraph formatting
320 void wxRichTextHTMLHandler::OutputParagraphFormatting(const wxTextAttrEx
& WXUNUSED(currentStyle
), const wxTextAttrEx
& thisStyle
, wxOutputStream
& stream
)
322 // If there is no opened list currently, insert a <p> after every paragraph
325 wxTextOutputStream
str(stream
);
326 wxString align
= GetAlignment(thisStyle
);
327 str
<< wxString::Format(wxT("<p align=\"%s\">"), align
.c_str());
330 if (thisStyle
.HasPageBreak())
332 wxTextOutputStream
str(stream
);
333 str
<< wxT("<div style=\"page-break-after:always\"></div>\n");
337 void wxRichTextHTMLHandler::NavigateToListPosition(const wxTextAttrEx
& thisStyle
, wxTextOutputStream
& str
)
339 // indenting an item using an ul/ol tag is equal to inserting 5 x on its left side.
340 // so we should start from 100 point left
342 // Is the second td's left wall of the current indentaion table at the 100+ point-left-side
343 // of the item, horizontally?
344 if (m_indent
+ 100 < thisStyle
.GetLeftIndent())
347 LIndent(thisStyle
, str
);
348 m_indent
= thisStyle
.GetLeftIndent() - 100;
349 m_indents
.Add( m_indent
);
354 int i
= m_indents
.size() - 1;
357 //Is the second td's left wall of the current indentaion table at the 100+ point-left-side
359 if (m_indent
+ 100 < thisStyle
.GetLeftIndent())
362 LIndent(thisStyle
, str
);
363 m_indent
= thisStyle
.GetLeftIndent() - 100;
364 m_indents
.Add( m_indent
);
367 else if (m_indent
+ 100 == thisStyle
.GetLeftIndent())
371 // No it is not, the second td's left wall of the current indentaion table is at the
372 //right side of the current item horizontally, so close it.
373 str
<< wxT("</td></tr></table>");
375 m_indents
.RemoveAt(i
);
381 m_indent
= m_indents
[i
-1];
385 void wxRichTextHTMLHandler::Indent( const wxTextAttrEx
& thisStyle
, wxTextOutputStream
& str
)
387 //There is no way to indent an item in HTML, but we can use tables.
389 // Item -> "Hello world"
390 // Its Left Indentation -> 100
391 // Its Left Sub-Indentation ->40
392 // A typical indentation-table for the item will be construct as the following
396 // LSI = Left Sub Indent
397 // LI = Left Indent - LSI
399 // -------------------------------------------
400 // | nbsp;|nbsp;nbsp;Hello World |
403 // | --LI-- | --LSI-- |
404 // -------------------------------------------
406 str
<< wxT("<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
408 wxString symbolic_indent
= SymbolicIndent( (thisStyle
.GetLeftIndent() + thisStyle
.GetLeftSubIndent()) - m_indent
);
409 str
<< wxString::Format( wxT("<td>%s</td>"), symbolic_indent
.c_str() );
410 str
<< wxT("<td width=\"100%\">");
412 if (thisStyle
.GetLeftSubIndent() < 0)
414 str
<< SymbolicIndent(~thisStyle
.GetLeftSubIndent());
418 void wxRichTextHTMLHandler::LIndent( const wxTextAttrEx
& thisStyle
, wxTextOutputStream
& str
)
421 // r.BeginNumberedBullet(1, 200, 60);
423 // r.WriteText(wxT("first item"));
424 // r.EndNumberedBullet();
425 // r.BeginNumberedBullet(2, 200, 60);
427 // r.WriteText(wxT("second item."));
428 // r.EndNumberedBullet();
430 // A typical indentation-table for the item will be construct as the following
432 // 1 x nbsp = 20 point
433 // ULI -> 100pt (UL/OL tag indents its sub element by 100 point)
434 // <--------- 100 pt ---------->|
435 // ------------------------------------------------------
436 // | nbsp; nbsp;|<ul> |
437 // | |<-ULI-><li>first item |
438 // | |<-ULI-><li>second item |
440 // ------------------------------------------------------
444 str
<< wxT("<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
446 wxString symbolic_indent
= SymbolicIndent( (thisStyle
.GetLeftIndent() - m_indent
) - 100);
447 str
<< wxString::Format( wxT("<td>%s</td>"), symbolic_indent
.c_str() );
448 str
<< wxT("<td width=\"100%\">");
451 void wxRichTextHTMLHandler::TypeOfList( const wxTextAttrEx
& thisStyle
, wxString
& tag
)
453 // We can use number attribute of li tag but not all the browsers support it.
454 // also wxHtmlWindow doesn't support type attribute.
457 if (thisStyle
.GetBulletStyle() == (wxTEXT_ATTR_BULLET_STYLE_ARABIC
|wxTEXT_ATTR_BULLET_STYLE_PERIOD
))
458 tag
= wxT("<ol type=\"1\">");
459 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER
)
460 tag
= wxT("<ol type=\"A\">");
461 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER
)
462 tag
= wxT("<ol type=\"a\">");
463 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER
)
464 tag
= wxT("<ol type=\"I\">");
465 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER
)
466 tag
= wxT("<ol type=\"i\">");
474 wxString
wxRichTextHTMLHandler::GetAlignment( const wxTextAttrEx
& thisStyle
)
476 switch( thisStyle
.GetAlignment() )
478 case wxTEXT_ALIGNMENT_LEFT
:
480 case wxTEXT_ALIGNMENT_RIGHT
:
482 case wxTEXT_ALIGNMENT_CENTER
:
483 return wxT("center");
484 case wxTEXT_ALIGNMENT_JUSTIFIED
:
485 return wxT("justify");
491 void wxRichTextHTMLHandler::WriteImage(wxRichTextImage
* image
, wxOutputStream
& stream
)
493 wxTextOutputStream
str(stream
);
495 str
<< wxT("<img src=\"");
498 if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_MEMORY
)
500 if (!image
->GetImage().Ok() && image
->GetImageBlock().GetData())
501 image
->LoadFromBlock();
502 if (image
->GetImage().Ok() && !image
->GetImageBlock().GetData())
505 if (image
->GetImage().Ok())
507 wxString
ext(image
->GetImageBlock().GetExtension());
508 wxString
tempFilename(wxString::Format(wxT("image%d.%s"), sm_fileCounter
, (const wxChar
*) ext
));
509 wxMemoryFSHandler::AddFile(tempFilename
, image
->GetImage(), image
->GetImageBlock().GetImageType());
511 m_imageLocations
.Add(tempFilename
);
513 str
<< wxT("memory:") << tempFilename
;
516 str
<< wxT("memory:?");
520 else if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES
)
522 if (!image
->GetImage().Ok() && image
->GetImageBlock().GetData())
523 image
->LoadFromBlock();
524 if (image
->GetImage().Ok() && !image
->GetImageBlock().GetData())
527 if (image
->GetImage().Ok())
529 wxString
tempDir(GetTempDir());
530 if (tempDir
.IsEmpty())
531 tempDir
= wxFileName::GetTempDir();
533 wxString
ext(image
->GetImageBlock().GetExtension());
534 wxString
tempFilename(wxString::Format(wxT("%s/image%d.%s"), (const wxChar
*) tempDir
, sm_fileCounter
, (const wxChar
*) ext
));
535 image
->GetImageBlock().Write(tempFilename
);
537 m_imageLocations
.Add(tempFilename
);
539 str
<< wxFileSystem::FileNameToURL(tempFilename
);
542 str
<< wxT("file:?");
546 else // if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_BASE64) // this is implied
550 str
<< GetMimeType(image
->GetImageBlock().GetImageType());
551 str
<< wxT(";base64,");
553 if (image
->GetImage().Ok() && !image
->GetImageBlock().GetData())
556 wxChar
* data
= b64enc( image
->GetImageBlock().GetData(), image
->GetImageBlock().GetDataSize() );
565 long wxRichTextHTMLHandler::PtToSize(long size
)
567 // return approximate size
568 if (size
< 9 ) return 1;
569 else if( size
< 11 ) return 2;
570 else if( size
< 14 ) return 3;
571 else if( size
< 18 ) return 4;
572 else if( size
< 23 ) return 5;
573 else if( size
< 30 ) return 6;
577 wxString
wxRichTextHTMLHandler::SymbolicIndent(long indent
)
580 for(;indent
> 0; indent
-= 20)
581 in
.Append( wxT(" ") );
585 const wxChar
* wxRichTextHTMLHandler::GetMimeType(int imageType
)
589 case wxBITMAP_TYPE_BMP
:
590 return wxT("image/bmp");
591 case wxBITMAP_TYPE_TIF
:
592 return wxT("image/tiff");
593 case wxBITMAP_TYPE_GIF
:
594 return wxT("image/gif");
595 case wxBITMAP_TYPE_PNG
:
596 return wxT("image/png");
597 case wxBITMAP_TYPE_JPEG
:
598 return wxT("image/jpeg");
600 return wxT("image/unknown");
604 // exim-style base64 encoder
605 wxChar
* wxRichTextHTMLHandler::b64enc( unsigned char* input
, size_t in_len
)
607 // elements of enc64 array must be 8 bit values
608 // otherwise encoder will fail
609 // hmmm.. Does wxT macro define a char as 16 bit value
610 // when compiling with UNICODE option?
611 static const wxChar enc64
[] = wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
612 wxChar
* output
= new wxChar
[4*((in_len
+2)/3)+1];
615 while( in_len
-- > 0 )
617 register wxChar a
, b
;
621 *p
++ = enc64
[ (a
>> 2) & 0x3f ];
625 *p
++ = enc64
[ (a
<< 4 ) & 0x30 ];
633 *p
++ = enc64
[(( a
<< 4 ) | ((b
>> 4) &0xf )) & 0x3f];
637 *p
++ = enc64
[ (b
<< 2) & 0x3f ];
644 *p
++ = enc64
[ ((( b
<< 2 ) & 0x3f ) | ((a
>> 6)& 0x3)) & 0x3f ];
646 *p
++ = enc64
[ a
& 0x3f ];
655 /// Delete the in-memory or temporary files generated by the last operation
656 bool wxRichTextHTMLHandler::DeleteTemporaryImages()
658 return DeleteTemporaryImages(GetFlags(), m_imageLocations
);
661 /// Delete the in-memory or temporary files generated by the last operation
662 bool wxRichTextHTMLHandler::DeleteTemporaryImages(int flags
, const wxArrayString
& imageLocations
)
665 for (i
= 0; i
< imageLocations
.GetCount(); i
++)
667 wxString location
= imageLocations
[i
];
669 if (flags
& wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_MEMORY
)
672 wxMemoryFSHandler::RemoveFile(location
);
675 else if (flags
& wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES
)
677 if (wxFileExists(location
))
678 wxRemoveFile(location
);