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();
81 wxCSConv
* customEncoding
= NULL
;
82 wxMBConv
* conv
= NULL
;
83 if (!GetEncoding().IsEmpty())
85 customEncoding
= new wxCSConv(GetEncoding());
86 if (!customEncoding
->IsOk())
88 delete customEncoding
;
89 customEncoding
= NULL
;
93 conv
= customEncoding
;
100 wxTextOutputStream
str(stream
, wxEOL_NATIVE
, *conv
);
102 wxTextOutputStream
str(stream
, wxEOL_NATIVE
);
105 wxTextAttr currentParaStyle
= buffer
->GetAttributes();
106 wxTextAttr 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 wxTextAttr
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 wxTextAttr
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 wxTextAttr
& currentStyle
, const wxTextAttr
& thisStyle
, const wxTextAttr
& 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()));
200 if (thisStyle
.GetTextColour() != currentStyle
.GetTextColour() )
202 wxString
color(thisStyle
.GetTextColour().GetAsString(wxC2S_HTML_SYNTAX
));
203 style
+= wxString::Format(wxT(" color=\"%s\""), color
.c_str());
208 str
<< wxString::Format(wxT("<font %s >"), style
.c_str());
212 if (thisStyle
.GetFontWeight() == wxBOLD
)
214 if (thisStyle
.GetFontStyle() == wxITALIC
)
216 if (thisStyle
.GetFontUnderlined())
219 if (thisStyle
.HasURL())
220 str
<< wxT("<a href=\"") << thisStyle
.GetURL() << wxT("\">");
223 void wxRichTextHTMLHandler::EndCharacterFormatting(const wxTextAttr
& WXUNUSED(currentStyle
), const wxTextAttr
& thisStyle
, const wxTextAttr
& WXUNUSED(paraStyle
), wxTextOutputStream
& stream
)
225 if (thisStyle
.HasURL())
226 stream
<< wxT("</a>");
228 if (thisStyle
.GetFontUnderlined())
229 stream
<< wxT("</u>");
230 if (thisStyle
.GetFontStyle() == wxITALIC
)
231 stream
<< wxT("</i>");
232 if (thisStyle
.GetFontWeight() == wxBOLD
)
233 stream
<< wxT("</b>");
238 stream
<< wxT("</font>");
242 /// Begin paragraph formatting
243 void wxRichTextHTMLHandler::BeginParagraphFormatting(const wxTextAttr
& WXUNUSED(currentStyle
), const wxTextAttr
& thisStyle
, wxTextOutputStream
& str
)
245 if (thisStyle
.HasPageBreak())
247 str
<< wxT("<div style=\"page-break-after:always\"></div>\n");
250 if (thisStyle
.HasLeftIndent() && thisStyle
.GetLeftIndent() != 0)
252 if (thisStyle
.HasBulletStyle())
254 int indent
= thisStyle
.GetLeftIndent();
256 // Close levels high than this
257 CloseLists(indent
, str
);
259 if (m_indents
.GetCount() > 0 && indent
== m_indents
.Last())
261 // Same level, no need to start a new list
263 else if (m_indents
.GetCount() == 0 || indent
> m_indents
.Last())
265 m_indents
.Add(indent
);
268 int listType
= TypeOfList(thisStyle
, tag
);
269 m_listTypes
.Add(listType
);
271 // wxHTML needs an extra <p> before a list when using <p> ... </p> in previous paragraphs.
272 // TODO: pass a flag that indicates we're using wxHTML.
284 wxString align
= GetAlignment(thisStyle
);
285 str
<< wxString::Format(wxT("<p align=\"%s\""), align
.c_str());
289 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasParagraphSpacingBefore())
291 float spacingBeforeMM
= thisStyle
.GetParagraphSpacingBefore() / 10.0;
293 styleStr
+= wxString::Format(wxT("margin-top: %.2fmm; "), spacingBeforeMM
);
295 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasParagraphSpacingAfter())
297 float spacingAfterMM
= thisStyle
.GetParagraphSpacingAfter() / 10.0;
299 styleStr
+= wxString::Format(wxT("margin-bottom: %.2fmm; "), spacingAfterMM
);
302 float indentLeftMM
= (thisStyle
.GetLeftIndent() + thisStyle
.GetLeftSubIndent())/10.0;
303 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && (indentLeftMM
> 0.0))
305 styleStr
+= wxString::Format(wxT("margin-left: %.2fmm; "), indentLeftMM
);
307 float indentRightMM
= thisStyle
.GetRightIndent()/10.0;
308 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasRightIndent() && (indentRightMM
> 0.0))
310 styleStr
+= wxString::Format(wxT("margin-right: %.2fmm; "), indentRightMM
);
312 // First line indentation
313 float firstLineIndentMM
= - thisStyle
.GetLeftSubIndent() / 10.0;
314 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && (firstLineIndentMM
> 0.0))
316 styleStr
+= wxString::Format(wxT("text-indent: %.2fmm; "), firstLineIndentMM
);
319 if (!styleStr
.IsEmpty())
320 str
<< wxT(" style=\"") << styleStr
<< wxT("\"");
324 // TODO: convert to pixels
325 int indentPixels
= static_cast<int>(indentLeftMM
*10/4);
327 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) == 0)
329 // Use a table to do indenting if we don't have CSS
330 str
<< wxString::Format(wxT("<table border=0 cellpadding=0 cellspacing=0><tr><td width=\"%d\"></td><td>"), indentPixels
);
334 if (((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) == 0) && (thisStyle
.GetLeftSubIndent() < 0))
336 str
<< SymbolicIndent( - thisStyle
.GetLeftSubIndent());
344 wxString align
= GetAlignment(thisStyle
);
345 str
<< wxString::Format(wxT("<p align=\"%s\""), align
.c_str());
349 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasParagraphSpacingBefore())
351 float spacingBeforeMM
= thisStyle
.GetParagraphSpacingBefore() / 10.0;
353 styleStr
+= wxString::Format(wxT("margin-top: %.2fmm; "), spacingBeforeMM
);
355 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasParagraphSpacingAfter())
357 float spacingAfterMM
= thisStyle
.GetParagraphSpacingAfter() / 10.0;
359 styleStr
+= wxString::Format(wxT("margin-bottom: %.2fmm; "), spacingAfterMM
);
362 if (!styleStr
.IsEmpty())
363 str
<< wxT(" style=\"") << styleStr
<< wxT("\"");
367 OutputFont(thisStyle
, str
);
370 /// End paragraph formatting
371 void wxRichTextHTMLHandler::EndParagraphFormatting(const wxTextAttr
& WXUNUSED(currentStyle
), const wxTextAttr
& thisStyle
, wxTextOutputStream
& stream
)
373 if (thisStyle
.HasFont())
374 stream
<< wxT("</font>");
378 stream
<< wxT("</td></tr></table></p>\n");
381 else if (!thisStyle
.HasBulletStyle())
382 stream
<< wxT("</p>\n");
385 /// Closes lists to level (-1 means close all)
386 void wxRichTextHTMLHandler::CloseLists(int level
, wxTextOutputStream
& str
)
388 // Close levels high than this
389 int i
= m_indents
.GetCount()-1;
392 int l
= m_indents
[i
];
395 if (m_listTypes
[i
] == 0)
399 m_indents
.RemoveAt(i
);
400 m_listTypes
.RemoveAt(i
);
409 void wxRichTextHTMLHandler::OutputFont(const wxTextAttr
& style
, wxTextOutputStream
& stream
)
413 stream
<< wxString::Format(wxT("<font face=\"%s\" size=\"%ld\""), style
.GetFontFaceName().c_str(), PtToSize(style
.GetFontSize()));
414 if (style
.HasTextColour())
415 stream
<< wxString::Format(wxT(" color=\"%s\""), style
.GetTextColour().GetAsString(wxC2S_HTML_SYNTAX
).c_str());
420 int wxRichTextHTMLHandler::TypeOfList( const wxTextAttr
& thisStyle
, wxString
& tag
)
422 // We can use number attribute of li tag but not all the browsers support it.
423 // also wxHtmlWindow doesn't support type attribute.
425 bool m_is_ul
= false;
426 if (thisStyle
.GetBulletStyle() == (wxTEXT_ATTR_BULLET_STYLE_ARABIC
|wxTEXT_ATTR_BULLET_STYLE_PERIOD
))
427 tag
= wxT("<ol type=\"1\">");
428 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER
)
429 tag
= wxT("<ol type=\"A\">");
430 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER
)
431 tag
= wxT("<ol type=\"a\">");
432 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER
)
433 tag
= wxT("<ol type=\"I\">");
434 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER
)
435 tag
= wxT("<ol type=\"i\">");
448 wxString
wxRichTextHTMLHandler::GetAlignment( const wxTextAttr
& thisStyle
)
450 switch( thisStyle
.GetAlignment() )
452 case wxTEXT_ALIGNMENT_LEFT
:
454 case wxTEXT_ALIGNMENT_RIGHT
:
456 case wxTEXT_ALIGNMENT_CENTER
:
457 return wxT("center");
458 case wxTEXT_ALIGNMENT_JUSTIFIED
:
459 return wxT("justify");
465 void wxRichTextHTMLHandler::WriteImage(wxRichTextImage
* image
, wxOutputStream
& stream
)
467 wxTextOutputStream
str(stream
);
469 str
<< wxT("<img src=\"");
472 if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_MEMORY
)
474 if (!image
->GetImage().Ok() && image
->GetImageBlock().GetData())
475 image
->LoadFromBlock();
476 if (image
->GetImage().Ok() && !image
->GetImageBlock().GetData())
479 if (image
->GetImage().Ok())
481 wxString
ext(image
->GetImageBlock().GetExtension());
482 wxString
tempFilename(wxString::Format(wxT("image%d.%s"), sm_fileCounter
, ext
));
483 wxMemoryFSHandler::AddFile(tempFilename
, image
->GetImage(), image
->GetImageBlock().GetImageType());
485 m_imageLocations
.Add(tempFilename
);
487 str
<< wxT("memory:") << tempFilename
;
490 str
<< wxT("memory:?");
494 else if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES
)
496 if (!image
->GetImage().Ok() && image
->GetImageBlock().GetData())
497 image
->LoadFromBlock();
498 if (image
->GetImage().Ok() && !image
->GetImageBlock().GetData())
501 if (image
->GetImage().Ok())
503 wxString
tempDir(GetTempDir());
504 if (tempDir
.IsEmpty())
505 tempDir
= wxFileName::GetTempDir();
507 wxString
ext(image
->GetImageBlock().GetExtension());
508 wxString
tempFilename(wxString::Format(wxT("%s/image%d.%s"), tempDir
, sm_fileCounter
, ext
));
509 image
->GetImageBlock().Write(tempFilename
);
511 m_imageLocations
.Add(tempFilename
);
513 str
<< wxFileSystem::FileNameToURL(tempFilename
);
516 str
<< wxT("file:?");
520 else // if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_BASE64) // this is implied
524 str
<< GetMimeType(image
->GetImageBlock().GetImageType());
525 str
<< wxT(";base64,");
527 if (image
->GetImage().Ok() && !image
->GetImageBlock().GetData())
530 wxChar
* data
= b64enc( image
->GetImageBlock().GetData(), image
->GetImageBlock().GetDataSize() );
539 long wxRichTextHTMLHandler::PtToSize(long size
)
542 int len
= m_fontSizeMapping
.GetCount();
543 for (i
= 0; i
< len
; i
++)
544 if (size
<= m_fontSizeMapping
[i
])
549 wxString
wxRichTextHTMLHandler::SymbolicIndent(long indent
)
552 for(;indent
> 0; indent
-= 20)
553 in
.Append( wxT(" ") );
557 const wxChar
* wxRichTextHTMLHandler::GetMimeType(int imageType
)
561 case wxBITMAP_TYPE_BMP
:
562 return wxT("image/bmp");
563 case wxBITMAP_TYPE_TIF
:
564 return wxT("image/tiff");
565 case wxBITMAP_TYPE_GIF
:
566 return wxT("image/gif");
567 case wxBITMAP_TYPE_PNG
:
568 return wxT("image/png");
569 case wxBITMAP_TYPE_JPEG
:
570 return wxT("image/jpeg");
572 return wxT("image/unknown");
576 // exim-style base64 encoder
577 wxChar
* wxRichTextHTMLHandler::b64enc( unsigned char* input
, size_t in_len
)
579 // elements of enc64 array must be 8 bit values
580 // otherwise encoder will fail
581 // hmmm.. Does wxT macro define a char as 16 bit value
582 // when compiling with UNICODE option?
583 static const wxChar enc64
[] = wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
584 wxChar
* output
= new wxChar
[4*((in_len
+2)/3)+1];
587 while( in_len
-- > 0 )
589 register wxChar a
, b
;
593 *p
++ = enc64
[ (a
>> 2) & 0x3f ];
597 *p
++ = enc64
[ (a
<< 4 ) & 0x30 ];
605 *p
++ = enc64
[(( a
<< 4 ) | ((b
>> 4) &0xf )) & 0x3f];
609 *p
++ = enc64
[ (b
<< 2) & 0x3f ];
616 *p
++ = enc64
[ ((( b
<< 2 ) & 0x3f ) | ((a
>> 6)& 0x3)) & 0x3f ];
618 *p
++ = enc64
[ a
& 0x3f ];
627 /// Delete the in-memory or temporary files generated by the last operation
628 bool wxRichTextHTMLHandler::DeleteTemporaryImages()
630 return DeleteTemporaryImages(GetFlags(), m_imageLocations
);
633 /// Delete the in-memory or temporary files generated by the last operation
634 bool wxRichTextHTMLHandler::DeleteTemporaryImages(int flags
, const wxArrayString
& imageLocations
)
637 for (i
= 0; i
< imageLocations
.GetCount(); i
++)
639 wxString location
= imageLocations
[i
];
641 if (flags
& wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_MEMORY
)
644 wxMemoryFSHandler::RemoveFile(location
);
647 else if (flags
& wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES
)
649 if (wxFileExists(location
))
650 wxRemoveFile(location
);