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 wxDELETE(customEncoding
);
92 conv
= customEncoding
;
99 wxTextOutputStream
str(stream
, wxEOL_NATIVE
, *conv
);
101 wxTextOutputStream
str(stream
, wxEOL_NATIVE
);
104 wxRichTextAttr currentParaStyle
= buffer
->GetAttributes();
105 wxRichTextAttr currentCharStyle
= buffer
->GetAttributes();
107 if ((GetFlags() & wxRICHTEXT_HANDLER_NO_HEADER_FOOTER
) == 0)
108 str
<< wxT("<html><head></head><body>\n");
110 OutputFont(currentParaStyle
, str
);
118 wxRichTextObjectList::compatibility_iterator node
= buffer
->GetChildren().GetFirst();
121 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
122 wxASSERT (para
!= NULL
);
126 wxRichTextAttr
paraStyle(para
->GetCombinedAttributes());
128 BeginParagraphFormatting(currentParaStyle
, paraStyle
, str
);
130 wxRichTextObjectList::compatibility_iterator node2
= para
->GetChildren().GetFirst();
133 wxRichTextObject
* obj
= node2
->GetData();
134 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
135 if (textObj
&& !textObj
->IsEmpty())
137 wxRichTextAttr
charStyle(para
->GetCombinedAttributes(obj
->GetAttributes()));
138 BeginCharacterFormatting(currentCharStyle
, charStyle
, paraStyle
, str
);
140 wxString text
= textObj
->GetText();
142 if (charStyle
.HasTextEffects() && (charStyle
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
145 wxString toReplace
= wxRichTextLineBreakChar
;
146 text
.Replace(toReplace
, wxT("<br>"));
150 EndCharacterFormatting(currentCharStyle
, charStyle
, paraStyle
, str
);
153 wxRichTextImage
* image
= wxDynamicCast(obj
, wxRichTextImage
);
154 if( image
&& (!image
->IsEmpty() || image
->GetImageBlock().GetData()))
155 WriteImage( image
, stream
);
157 node2
= node2
->GetNext();
160 EndParagraphFormatting(currentParaStyle
, paraStyle
, str
);
164 node
= node
->GetNext();
169 str
<< wxT("</font>");
171 if ((GetFlags() & wxRICHTEXT_HANDLER_NO_HEADER_FOOTER
) == 0)
172 str
<< wxT("</body></html>");
179 delete customEncoding
;
187 void wxRichTextHTMLHandler::BeginCharacterFormatting(const wxRichTextAttr
& currentStyle
, const wxRichTextAttr
& thisStyle
, const wxRichTextAttr
& WXUNUSED(paraStyle
), wxTextOutputStream
& str
)
191 // Is there any change in the font properties of the item?
192 if (thisStyle
.GetFontFaceName() != currentStyle
.GetFontFaceName())
194 wxString
faceName(thisStyle
.GetFontFaceName());
195 style
+= wxString::Format(wxT(" face=\"%s\""), faceName
.c_str());
197 if (thisStyle
.GetFontSize() != currentStyle
.GetFontSize())
198 style
+= wxString::Format(wxT(" size=\"%ld\""), PtToSize(thisStyle
.GetFontSize()));
200 bool bTextColourChanged
= (thisStyle
.GetTextColour() != currentStyle
.GetTextColour());
201 bool bBackgroundColourChanged
= (thisStyle
.GetBackgroundColour() != currentStyle
.GetBackgroundColour());
202 if (bTextColourChanged
|| bBackgroundColourChanged
)
204 style
+= wxT(" style=\"");
206 if (bTextColourChanged
)
208 wxString
color(thisStyle
.GetTextColour().GetAsString(wxC2S_HTML_SYNTAX
));
209 style
+= wxString::Format(wxT("color: %s"), color
.c_str());
211 if (bTextColourChanged
&& bBackgroundColourChanged
)
213 if (bBackgroundColourChanged
)
215 wxString
color(thisStyle
.GetBackgroundColour().GetAsString(wxC2S_HTML_SYNTAX
));
216 style
+= wxString::Format(wxT("background-color: %s"), color
.c_str());
224 str
<< wxString::Format(wxT("<font %s >"), style
.c_str());
228 if (thisStyle
.GetFontWeight() == wxBOLD
)
230 if (thisStyle
.GetFontStyle() == wxITALIC
)
232 if (thisStyle
.GetFontUnderlined())
235 if (thisStyle
.HasURL())
236 str
<< wxT("<a href=\"") << thisStyle
.GetURL() << wxT("\">");
239 void wxRichTextHTMLHandler::EndCharacterFormatting(const wxRichTextAttr
& WXUNUSED(currentStyle
), const wxRichTextAttr
& thisStyle
, const wxRichTextAttr
& WXUNUSED(paraStyle
), wxTextOutputStream
& stream
)
241 if (thisStyle
.HasURL())
242 stream
<< wxT("</a>");
244 if (thisStyle
.GetFontUnderlined())
245 stream
<< wxT("</u>");
246 if (thisStyle
.GetFontStyle() == wxITALIC
)
247 stream
<< wxT("</i>");
248 if (thisStyle
.GetFontWeight() == wxBOLD
)
249 stream
<< wxT("</b>");
254 stream
<< wxT("</font>");
258 /// Begin paragraph formatting
259 void wxRichTextHTMLHandler::BeginParagraphFormatting(const wxRichTextAttr
& WXUNUSED(currentStyle
), const wxRichTextAttr
& thisStyle
, wxTextOutputStream
& str
)
261 if (thisStyle
.HasPageBreak())
263 str
<< wxT("<div style=\"page-break-after:always\"></div>\n");
266 if (thisStyle
.HasLeftIndent() && thisStyle
.GetLeftIndent() != 0)
268 if (thisStyle
.HasBulletStyle())
270 int indent
= thisStyle
.GetLeftIndent();
272 // Close levels high than this
273 CloseLists(indent
, str
);
275 if (m_indents
.GetCount() > 0 && indent
== m_indents
.Last())
277 // Same level, no need to start a new list
279 else if (m_indents
.GetCount() == 0 || indent
> m_indents
.Last())
281 m_indents
.Add(indent
);
284 int listType
= TypeOfList(thisStyle
, tag
);
285 m_listTypes
.Add(listType
);
287 // wxHTML needs an extra <p> before a list when using <p> ... </p> in previous paragraphs.
288 // TODO: pass a flag that indicates we're using wxHTML.
300 wxString align
= GetAlignment(thisStyle
);
301 str
<< wxString::Format(wxT("<p align=\"%s\""), align
.c_str());
305 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasParagraphSpacingBefore())
307 float spacingBeforeMM
= thisStyle
.GetParagraphSpacingBefore() / 10.0;
309 styleStr
+= wxString::Format(wxT("margin-top: %.2fmm; "), spacingBeforeMM
);
311 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasParagraphSpacingAfter())
313 float spacingAfterMM
= thisStyle
.GetParagraphSpacingAfter() / 10.0;
315 styleStr
+= wxString::Format(wxT("margin-bottom: %.2fmm; "), spacingAfterMM
);
318 float indentLeftMM
= (thisStyle
.GetLeftIndent() + thisStyle
.GetLeftSubIndent())/10.0;
319 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && (indentLeftMM
> 0.0))
321 styleStr
+= wxString::Format(wxT("margin-left: %.2fmm; "), indentLeftMM
);
323 float indentRightMM
= thisStyle
.GetRightIndent()/10.0;
324 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasRightIndent() && (indentRightMM
> 0.0))
326 styleStr
+= wxString::Format(wxT("margin-right: %.2fmm; "), indentRightMM
);
328 // First line indentation
329 float firstLineIndentMM
= - thisStyle
.GetLeftSubIndent() / 10.0;
330 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && (firstLineIndentMM
> 0.0))
332 styleStr
+= wxString::Format(wxT("text-indent: %.2fmm; "), firstLineIndentMM
);
335 if (!styleStr
.IsEmpty())
336 str
<< wxT(" style=\"") << styleStr
<< wxT("\"");
340 // TODO: convert to pixels
341 int indentPixels
= static_cast<int>(indentLeftMM
*10/4);
343 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) == 0)
345 // Use a table to do indenting if we don't have CSS
346 str
<< wxString::Format(wxT("<table border=0 cellpadding=0 cellspacing=0><tr><td width=\"%d\"></td><td>"), indentPixels
);
350 if (((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) == 0) && (thisStyle
.GetLeftSubIndent() < 0))
352 str
<< SymbolicIndent( - thisStyle
.GetLeftSubIndent());
360 wxString align
= GetAlignment(thisStyle
);
361 str
<< wxString::Format(wxT("<p align=\"%s\""), align
.c_str());
365 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasParagraphSpacingBefore())
367 float spacingBeforeMM
= thisStyle
.GetParagraphSpacingBefore() / 10.0;
369 styleStr
+= wxString::Format(wxT("margin-top: %.2fmm; "), spacingBeforeMM
);
371 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasParagraphSpacingAfter())
373 float spacingAfterMM
= thisStyle
.GetParagraphSpacingAfter() / 10.0;
375 styleStr
+= wxString::Format(wxT("margin-bottom: %.2fmm; "), spacingAfterMM
);
378 if (!styleStr
.IsEmpty())
379 str
<< wxT(" style=\"") << styleStr
<< wxT("\"");
383 OutputFont(thisStyle
, str
);
386 /// End paragraph formatting
387 void wxRichTextHTMLHandler::EndParagraphFormatting(const wxRichTextAttr
& WXUNUSED(currentStyle
), const wxRichTextAttr
& thisStyle
, wxTextOutputStream
& stream
)
389 if (thisStyle
.HasFont())
390 stream
<< wxT("</font>");
394 stream
<< wxT("</td></tr></table></p>\n");
397 else if (!thisStyle
.HasBulletStyle())
398 stream
<< wxT("</p>\n");
401 /// Closes lists to level (-1 means close all)
402 void wxRichTextHTMLHandler::CloseLists(int level
, wxTextOutputStream
& str
)
404 // Close levels high than this
405 int i
= m_indents
.GetCount()-1;
408 int l
= m_indents
[i
];
411 if (m_listTypes
[i
] == 0)
415 m_indents
.RemoveAt(i
);
416 m_listTypes
.RemoveAt(i
);
425 void wxRichTextHTMLHandler::OutputFont(const wxRichTextAttr
& style
, wxTextOutputStream
& stream
)
429 stream
<< wxString::Format(wxT("<font face=\"%s\" size=\"%ld\""), style
.GetFontFaceName().c_str(), PtToSize(style
.GetFontSize()));
430 if (style
.HasTextColour())
431 stream
<< wxString::Format(wxT(" color=\"%s\""), style
.GetTextColour().GetAsString(wxC2S_HTML_SYNTAX
).c_str());
436 int wxRichTextHTMLHandler::TypeOfList( const wxRichTextAttr
& thisStyle
, wxString
& tag
)
438 // We can use number attribute of li tag but not all the browsers support it.
439 // also wxHtmlWindow doesn't support type attribute.
441 bool m_is_ul
= false;
442 if (thisStyle
.GetBulletStyle() == (wxTEXT_ATTR_BULLET_STYLE_ARABIC
|wxTEXT_ATTR_BULLET_STYLE_PERIOD
))
443 tag
= wxT("<ol type=\"1\">");
444 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER
)
445 tag
= wxT("<ol type=\"A\">");
446 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER
)
447 tag
= wxT("<ol type=\"a\">");
448 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER
)
449 tag
= wxT("<ol type=\"I\">");
450 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER
)
451 tag
= wxT("<ol type=\"i\">");
464 wxString
wxRichTextHTMLHandler::GetAlignment( const wxRichTextAttr
& thisStyle
)
466 switch( thisStyle
.GetAlignment() )
468 case wxTEXT_ALIGNMENT_LEFT
:
470 case wxTEXT_ALIGNMENT_RIGHT
:
472 case wxTEXT_ALIGNMENT_CENTER
:
473 return wxT("center");
474 case wxTEXT_ALIGNMENT_JUSTIFIED
:
475 return wxT("justify");
481 void wxRichTextHTMLHandler::WriteImage(wxRichTextImage
* image
, wxOutputStream
& stream
)
483 wxTextOutputStream
str(stream
);
485 str
<< wxT("<img src=\"");
488 if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_MEMORY
)
491 if (!image
->GetImage().IsOk() && image
->GetImageBlock().GetData())
492 image
->LoadFromBlock();
493 if (image
->GetImage().IsOk() && !image
->GetImageBlock().GetData())
497 if (image
->GetImageBlock().IsOk())
500 image
->GetImageBlock().Load(img
);
503 wxString
ext(image
->GetImageBlock().GetExtension());
504 wxString
tempFilename(wxString::Format(wxT("image%d.%s"), sm_fileCounter
, ext
));
505 wxMemoryFSHandler::AddFile(tempFilename
, img
, image
->GetImageBlock().GetImageType());
507 m_imageLocations
.Add(tempFilename
);
509 str
<< wxT("memory:") << tempFilename
;
513 str
<< wxT("memory:?");
517 else if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES
)
520 if (!image
->GetImage().IsOk() && image
->GetImageBlock().GetData())
521 image
->LoadFromBlock();
522 if (image
->GetImage().IsOk() && !image
->GetImageBlock().GetData())
526 if (image
->GetImageBlock().IsOk())
528 wxString
tempDir(GetTempDir());
529 if (tempDir
.IsEmpty())
530 tempDir
= wxFileName::GetTempDir();
532 wxString
ext(image
->GetImageBlock().GetExtension());
533 wxString
tempFilename(wxString::Format(wxT("%s/image%d.%s"), tempDir
, sm_fileCounter
, ext
));
534 image
->GetImageBlock().Write(tempFilename
);
536 m_imageLocations
.Add(tempFilename
);
538 str
<< wxFileSystem::FileNameToURL(tempFilename
);
541 str
<< wxT("file:?");
545 else // if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_BASE64) // this is implied
549 str
<< GetMimeType(image
->GetImageBlock().GetImageType());
550 str
<< wxT(";base64,");
552 if (image
->GetImage().IsOk() && !image
->GetImageBlock().GetData())
555 if (image
->GetImageBlock().IsOk())
557 wxChar
* data
= b64enc( image
->GetImageBlock().GetData(), image
->GetImageBlock().GetDataSize() );
567 long wxRichTextHTMLHandler::PtToSize(long size
)
570 int len
= m_fontSizeMapping
.GetCount();
571 for (i
= 0; i
< len
; i
++)
572 if (size
<= m_fontSizeMapping
[i
])
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
);