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"
22 #include "wx/richtext/richtextstyles.h"
27 #include "wx/filename.h"
28 #include "wx/wfstream.h"
29 #include "wx/txtstrm.h"
32 #include "wx/filesys.h"
33 #include "wx/fs_mem.h"
36 IMPLEMENT_DYNAMIC_CLASS(wxRichTextHTMLHandler
, wxRichTextFileHandler
)
38 int wxRichTextHTMLHandler::sm_fileCounter
= 1;
40 wxRichTextHTMLHandler::wxRichTextHTMLHandler(const wxString
& name
, const wxString
& ext
, int type
)
41 : wxRichTextFileHandler(name
, ext
, type
), m_buffer(NULL
), m_font(false), m_inTable(false)
43 m_fontSizeMapping
.Add(8);
44 m_fontSizeMapping
.Add(10);
45 m_fontSizeMapping
.Add(13);
46 m_fontSizeMapping
.Add(17);
47 m_fontSizeMapping
.Add(22);
48 m_fontSizeMapping
.Add(30);
49 m_fontSizeMapping
.Add(100);
52 /// Can we handle this filename (if using files)? By default, checks the extension.
53 bool wxRichTextHTMLHandler::CanHandle(const wxString
& filename
) const
55 wxString path
, file
, ext
;
56 wxFileName::SplitPath(filename
, & path
, & file
, & ext
);
58 return (ext
.Lower() == wxT("html") || ext
.Lower() == wxT("htm"));
63 bool wxRichTextHTMLHandler::DoLoadFile(wxRichTextBuffer
*WXUNUSED(buffer
), wxInputStream
& WXUNUSED(stream
))
69 * We need to output only _changes_ in character formatting.
72 bool wxRichTextHTMLHandler::DoSaveFile(wxRichTextBuffer
*buffer
, wxOutputStream
& stream
)
76 ClearTemporaryImageLocations();
78 wxRichTextDrawingContext
context(buffer
);
79 buffer
->Defragment(context
);
82 wxCSConv
* customEncoding
= NULL
;
83 wxMBConv
* conv
= NULL
;
84 if (!GetEncoding().IsEmpty())
86 customEncoding
= new wxCSConv(GetEncoding());
87 if (!customEncoding
->IsOk())
89 wxDELETE(customEncoding
);
93 conv
= customEncoding
;
100 wxTextOutputStream
str(stream
, wxEOL_NATIVE
, *conv
);
102 wxTextOutputStream
str(stream
, wxEOL_NATIVE
);
105 wxRichTextAttr currentParaStyle
= buffer
->GetAttributes();
106 wxRichTextAttr currentCharStyle
= buffer
->GetAttributes();
108 if ((GetFlags() & wxRICHTEXT_HANDLER_NO_HEADER_FOOTER
) == 0)
109 str
<< wxT("<html><head></head><body>\n");
111 OutputFont(currentParaStyle
, str
);
119 wxRichTextObjectList::compatibility_iterator node
= buffer
->GetChildren().GetFirst();
122 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
123 wxASSERT (para
!= NULL
);
127 wxRichTextAttr
paraStyle(para
->GetCombinedAttributes());
129 BeginParagraphFormatting(currentParaStyle
, paraStyle
, str
);
131 wxRichTextObjectList::compatibility_iterator node2
= para
->GetChildren().GetFirst();
134 wxRichTextObject
* obj
= node2
->GetData();
135 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
136 if (textObj
&& !textObj
->IsEmpty())
138 wxRichTextAttr
charStyle(para
->GetCombinedAttributes(obj
->GetAttributes()));
139 BeginCharacterFormatting(currentCharStyle
, charStyle
, paraStyle
, str
);
141 wxString text
= textObj
->GetText();
143 if (charStyle
.HasTextEffects() && (charStyle
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
146 wxString toReplace
= wxRichTextLineBreakChar
;
147 text
.Replace(toReplace
, wxT("<br>"));
151 EndCharacterFormatting(currentCharStyle
, charStyle
, paraStyle
, str
);
154 wxRichTextImage
* image
= wxDynamicCast(obj
, wxRichTextImage
);
155 if( image
&& (!image
->IsEmpty() || image
->GetImageBlock().GetData()))
156 WriteImage( image
, stream
);
158 node2
= node2
->GetNext();
161 EndParagraphFormatting(currentParaStyle
, paraStyle
, str
);
165 node
= node
->GetNext();
170 str
<< wxT("</font>");
172 if ((GetFlags() & wxRICHTEXT_HANDLER_NO_HEADER_FOOTER
) == 0)
173 str
<< wxT("</body></html>");
180 delete customEncoding
;
188 void wxRichTextHTMLHandler::BeginCharacterFormatting(const wxRichTextAttr
& currentStyle
, const wxRichTextAttr
& thisStyle
, const wxRichTextAttr
& WXUNUSED(paraStyle
), wxTextOutputStream
& str
)
192 // Is there any change in the font properties of the item?
193 if (thisStyle
.GetFontFaceName() != currentStyle
.GetFontFaceName())
195 wxString
faceName(thisStyle
.GetFontFaceName());
196 style
+= wxString::Format(wxT(" face=\"%s\""), faceName
.c_str());
198 if (thisStyle
.GetFontSize() != currentStyle
.GetFontSize())
199 style
+= wxString::Format(wxT(" size=\"%ld\""), PtToSize(thisStyle
.GetFontSize()));
201 bool bTextColourChanged
= (thisStyle
.GetTextColour() != currentStyle
.GetTextColour());
202 bool bBackgroundColourChanged
= (thisStyle
.GetBackgroundColour() != currentStyle
.GetBackgroundColour());
203 if (bTextColourChanged
|| bBackgroundColourChanged
)
205 style
+= wxT(" style=\"");
207 if (bTextColourChanged
)
209 wxString
color(thisStyle
.GetTextColour().GetAsString(wxC2S_HTML_SYNTAX
));
210 style
+= wxString::Format(wxT("color: %s"), color
.c_str());
212 if (bTextColourChanged
&& bBackgroundColourChanged
)
214 if (bBackgroundColourChanged
)
216 wxString
color(thisStyle
.GetBackgroundColour().GetAsString(wxC2S_HTML_SYNTAX
));
217 style
+= wxString::Format(wxT("background-color: %s"), color
.c_str());
225 str
<< wxString::Format(wxT("<font %s >"), style
.c_str());
229 if (thisStyle
.GetFontWeight() == wxFONTWEIGHT_BOLD
)
231 if (thisStyle
.GetFontStyle() == wxFONTSTYLE_ITALIC
)
233 if (thisStyle
.GetFontUnderlined())
236 if (thisStyle
.HasURL())
237 str
<< wxT("<a href=\"") << thisStyle
.GetURL() << wxT("\">");
239 if (thisStyle
.HasTextEffects())
241 if (thisStyle
.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH
)
243 if (thisStyle
.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUPERSCRIPT
)
245 if (thisStyle
.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUBSCRIPT
)
250 void wxRichTextHTMLHandler::EndCharacterFormatting(const wxRichTextAttr
& WXUNUSED(currentStyle
), const wxRichTextAttr
& thisStyle
, const wxRichTextAttr
& WXUNUSED(paraStyle
), wxTextOutputStream
& stream
)
252 if (thisStyle
.HasURL())
253 stream
<< wxT("</a>");
255 if (thisStyle
.GetFontUnderlined())
256 stream
<< wxT("</u>");
257 if (thisStyle
.GetFontStyle() == wxFONTSTYLE_ITALIC
)
258 stream
<< wxT("</i>");
259 if (thisStyle
.GetFontWeight() == wxFONTWEIGHT_BOLD
)
260 stream
<< wxT("</b>");
262 if (thisStyle
.HasTextEffects())
264 if (thisStyle
.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH
)
265 stream
<< wxT("</del>");
266 if (thisStyle
.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUPERSCRIPT
)
267 stream
<< wxT("</sup>");
268 if (thisStyle
.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUBSCRIPT
)
269 stream
<< wxT("</sub>");
275 stream
<< wxT("</font>");
279 /// Begin paragraph formatting
280 void wxRichTextHTMLHandler::BeginParagraphFormatting(const wxRichTextAttr
& WXUNUSED(currentStyle
), const wxRichTextAttr
& thisStyle
, wxTextOutputStream
& str
)
282 if (thisStyle
.HasPageBreak())
284 str
<< wxT("<div style=\"page-break-after:always\"></div>\n");
287 if (thisStyle
.HasLeftIndent() && thisStyle
.GetLeftIndent() != 0)
289 if (thisStyle
.HasBulletStyle())
291 int indent
= thisStyle
.GetLeftIndent();
293 // Close levels high than this
294 CloseLists(indent
, str
);
296 if (m_indents
.GetCount() > 0 && indent
== m_indents
.Last())
298 // Same level, no need to start a new list
300 else if (m_indents
.GetCount() == 0 || indent
> m_indents
.Last())
302 m_indents
.Add(indent
);
305 int listType
= TypeOfList(thisStyle
, tag
);
306 m_listTypes
.Add(listType
);
308 // wxHTML needs an extra <p> before a list when using <p> ... </p> in previous paragraphs.
309 // TODO: pass a flag that indicates we're using wxHTML.
321 wxString align
= GetAlignment(thisStyle
);
322 str
<< wxString::Format(wxT("<p align=\"%s\""), align
.c_str());
326 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasParagraphSpacingBefore())
328 float spacingBeforeMM
= thisStyle
.GetParagraphSpacingBefore() / 10.0;
330 styleStr
+= wxString::Format(wxT("margin-top: %.2fmm; "), spacingBeforeMM
);
332 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasParagraphSpacingAfter())
334 float spacingAfterMM
= thisStyle
.GetParagraphSpacingAfter() / 10.0;
336 styleStr
+= wxString::Format(wxT("margin-bottom: %.2fmm; "), spacingAfterMM
);
339 float indentLeftMM
= (thisStyle
.GetLeftIndent() + thisStyle
.GetLeftSubIndent())/10.0;
340 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && (indentLeftMM
> 0.0))
342 styleStr
+= wxString::Format(wxT("margin-left: %.2fmm; "), indentLeftMM
);
344 float indentRightMM
= thisStyle
.GetRightIndent()/10.0;
345 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasRightIndent() && (indentRightMM
> 0.0))
347 styleStr
+= wxString::Format(wxT("margin-right: %.2fmm; "), indentRightMM
);
349 // First line indentation
350 float firstLineIndentMM
= - thisStyle
.GetLeftSubIndent() / 10.0;
351 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && (firstLineIndentMM
> 0.0))
353 styleStr
+= wxString::Format(wxT("text-indent: %.2fmm; "), firstLineIndentMM
);
356 if (!styleStr
.IsEmpty())
357 str
<< wxT(" style=\"") << styleStr
<< wxT("\"");
361 // TODO: convert to pixels
362 int indentPixels
= static_cast<int>(indentLeftMM
*10/4);
364 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) == 0)
366 // Use a table to do indenting if we don't have CSS
367 str
<< wxString::Format(wxT("<table border=0 cellpadding=0 cellspacing=0><tr><td width=\"%d\"></td><td>"), indentPixels
);
371 if (((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) == 0) && (thisStyle
.GetLeftSubIndent() < 0))
373 str
<< SymbolicIndent( - thisStyle
.GetLeftSubIndent());
381 wxString align
= GetAlignment(thisStyle
);
382 str
<< wxString::Format(wxT("<p align=\"%s\""), align
.c_str());
386 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasParagraphSpacingBefore())
388 float spacingBeforeMM
= thisStyle
.GetParagraphSpacingBefore() / 10.0;
390 styleStr
+= wxString::Format(wxT("margin-top: %.2fmm; "), spacingBeforeMM
);
392 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasParagraphSpacingAfter())
394 float spacingAfterMM
= thisStyle
.GetParagraphSpacingAfter() / 10.0;
396 styleStr
+= wxString::Format(wxT("margin-bottom: %.2fmm; "), spacingAfterMM
);
399 if (!styleStr
.IsEmpty())
400 str
<< wxT(" style=\"") << styleStr
<< wxT("\"");
404 OutputFont(thisStyle
, str
);
407 /// End paragraph formatting
408 void wxRichTextHTMLHandler::EndParagraphFormatting(const wxRichTextAttr
& WXUNUSED(currentStyle
), const wxRichTextAttr
& thisStyle
, wxTextOutputStream
& stream
)
410 if (thisStyle
.HasFont())
411 stream
<< wxT("</font>");
415 stream
<< wxT("</td></tr></table></p>\n");
418 else if (!thisStyle
.HasBulletStyle())
419 stream
<< wxT("</p>\n");
422 /// Closes lists to level (-1 means close all)
423 void wxRichTextHTMLHandler::CloseLists(int level
, wxTextOutputStream
& str
)
425 // Close levels high than this
426 int i
= m_indents
.GetCount()-1;
429 int l
= m_indents
[i
];
432 if (m_listTypes
[i
] == 0)
436 m_indents
.RemoveAt(i
);
437 m_listTypes
.RemoveAt(i
);
446 void wxRichTextHTMLHandler::OutputFont(const wxRichTextAttr
& style
, wxTextOutputStream
& stream
)
450 stream
<< wxString::Format(wxT("<font face=\"%s\" size=\"%ld\""), style
.GetFontFaceName().c_str(), PtToSize(style
.GetFontSize()));
451 if (style
.HasTextColour())
452 stream
<< wxString::Format(wxT(" color=\"%s\""), style
.GetTextColour().GetAsString(wxC2S_HTML_SYNTAX
).c_str());
457 int wxRichTextHTMLHandler::TypeOfList( const wxRichTextAttr
& thisStyle
, wxString
& tag
)
459 // We can use number attribute of li tag but not all the browsers support it.
460 // also wxHtmlWindow doesn't support type attribute.
462 bool m_is_ul
= false;
463 if (thisStyle
.GetBulletStyle() == (wxTEXT_ATTR_BULLET_STYLE_ARABIC
|wxTEXT_ATTR_BULLET_STYLE_PERIOD
))
464 tag
= wxT("<ol type=\"1\">");
465 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER
)
466 tag
= wxT("<ol type=\"A\">");
467 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER
)
468 tag
= wxT("<ol type=\"a\">");
469 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER
)
470 tag
= wxT("<ol type=\"I\">");
471 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER
)
472 tag
= wxT("<ol type=\"i\">");
485 wxString
wxRichTextHTMLHandler::GetAlignment( const wxRichTextAttr
& thisStyle
)
487 switch( thisStyle
.GetAlignment() )
489 case wxTEXT_ALIGNMENT_LEFT
:
491 case wxTEXT_ALIGNMENT_RIGHT
:
493 case wxTEXT_ALIGNMENT_CENTER
:
494 return wxT("center");
495 case wxTEXT_ALIGNMENT_JUSTIFIED
:
496 return wxT("justify");
502 void wxRichTextHTMLHandler::WriteImage(wxRichTextImage
* image
, wxOutputStream
& stream
)
504 wxTextOutputStream
str(stream
);
506 str
<< wxT("<img src=\"");
509 if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_MEMORY
)
512 if (!image
->GetImage().IsOk() && image
->GetImageBlock().GetData())
513 image
->LoadFromBlock();
514 if (image
->GetImage().IsOk() && !image
->GetImageBlock().GetData())
518 if (image
->GetImageBlock().IsOk())
521 image
->GetImageBlock().Load(img
);
524 wxString
ext(image
->GetImageBlock().GetExtension());
525 wxString
tempFilename(wxString::Format(wxT("image%d.%s"), sm_fileCounter
, ext
.c_str()));
526 wxMemoryFSHandler::AddFile(tempFilename
, img
, image
->GetImageBlock().GetImageType());
528 m_imageLocations
.Add(tempFilename
);
530 str
<< wxT("memory:") << tempFilename
;
534 str
<< wxT("memory:?");
538 else if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES
)
541 if (!image
->GetImage().IsOk() && image
->GetImageBlock().GetData())
542 image
->LoadFromBlock();
543 if (image
->GetImage().IsOk() && !image
->GetImageBlock().GetData())
547 if (image
->GetImageBlock().IsOk())
549 wxString
tempDir(GetTempDir());
550 if (tempDir
.IsEmpty())
551 tempDir
= wxFileName::GetTempDir();
553 wxString
ext(image
->GetImageBlock().GetExtension());
554 wxString
tempFilename(wxString::Format(wxT("%s/image%d.%s"), tempDir
.c_str(), sm_fileCounter
, ext
.c_str()));
555 image
->GetImageBlock().Write(tempFilename
);
557 m_imageLocations
.Add(tempFilename
);
559 str
<< wxFileSystem::FileNameToURL(tempFilename
);
562 str
<< wxT("file:?");
566 else // if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_BASE64) // this is implied
570 str
<< GetMimeType(image
->GetImageBlock().GetImageType());
571 str
<< wxT(";base64,");
573 if (image
->GetImage().IsOk() && !image
->GetImageBlock().GetData())
576 if (image
->GetImageBlock().IsOk())
578 wxChar
* data
= b64enc( image
->GetImageBlock().GetData(), image
->GetImageBlock().GetDataSize() );
588 long wxRichTextHTMLHandler::PtToSize(long size
)
591 int len
= m_fontSizeMapping
.GetCount();
592 for (i
= 0; i
< len
; i
++)
593 if (size
<= m_fontSizeMapping
[i
])
598 wxString
wxRichTextHTMLHandler::SymbolicIndent(long indent
)
601 for(;indent
> 0; indent
-= 20)
602 in
.Append( wxT(" ") );
606 const wxChar
* wxRichTextHTMLHandler::GetMimeType(int imageType
)
610 case wxBITMAP_TYPE_BMP
:
611 return wxT("image/bmp");
612 case wxBITMAP_TYPE_TIFF
:
613 return wxT("image/tiff");
614 case wxBITMAP_TYPE_GIF
:
615 return wxT("image/gif");
616 case wxBITMAP_TYPE_PNG
:
617 return wxT("image/png");
618 case wxBITMAP_TYPE_JPEG
:
619 return wxT("image/jpeg");
621 return wxT("image/unknown");
625 // exim-style base64 encoder
626 wxChar
* wxRichTextHTMLHandler::b64enc( unsigned char* input
, size_t in_len
)
628 // elements of enc64 array must be 8 bit values
629 // otherwise encoder will fail
630 // hmmm.. Does wxT macro define a char as 16 bit value
631 // when compiling with UNICODE option?
632 static const wxChar enc64
[] = wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
633 wxChar
* output
= new wxChar
[4*((in_len
+2)/3)+1];
636 while( in_len
-- > 0 )
638 register wxChar a
, b
;
642 *p
++ = enc64
[ (a
>> 2) & 0x3f ];
646 *p
++ = enc64
[ (a
<< 4 ) & 0x30 ];
654 *p
++ = enc64
[(( a
<< 4 ) | ((b
>> 4) &0xf )) & 0x3f];
658 *p
++ = enc64
[ (b
<< 2) & 0x3f ];
665 *p
++ = enc64
[ ((( b
<< 2 ) & 0x3f ) | ((a
>> 6)& 0x3)) & 0x3f ];
667 *p
++ = enc64
[ a
& 0x3f ];
676 /// Delete the in-memory or temporary files generated by the last operation
677 bool wxRichTextHTMLHandler::DeleteTemporaryImages()
679 return DeleteTemporaryImages(GetFlags(), m_imageLocations
);
682 /// Delete the in-memory or temporary files generated by the last operation
683 bool wxRichTextHTMLHandler::DeleteTemporaryImages(int flags
, const wxArrayString
& imageLocations
)
686 for (i
= 0; i
< imageLocations
.GetCount(); i
++)
688 wxString location
= imageLocations
[i
];
690 if (flags
& wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_MEMORY
)
693 wxMemoryFSHandler::RemoveFile(location
);
696 else if (flags
& wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES
)
698 if (wxFileExists(location
))
699 wxRemoveFile(location
);