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()));
199 if (thisStyle
.GetTextColour() != currentStyle
.GetTextColour() )
201 wxString
color(thisStyle
.GetTextColour().GetAsString(wxC2S_HTML_SYNTAX
));
202 style
+= wxString::Format(wxT(" color=\"%s\""), color
.c_str());
207 str
<< wxString::Format(wxT("<font %s >"), style
.c_str());
211 if (thisStyle
.GetFontWeight() == wxBOLD
)
213 if (thisStyle
.GetFontStyle() == wxITALIC
)
215 if (thisStyle
.GetFontUnderlined())
218 if (thisStyle
.HasURL())
219 str
<< wxT("<a href=\"") << thisStyle
.GetURL() << wxT("\">");
222 void wxRichTextHTMLHandler::EndCharacterFormatting(const wxRichTextAttr
& WXUNUSED(currentStyle
), const wxRichTextAttr
& thisStyle
, const wxRichTextAttr
& WXUNUSED(paraStyle
), wxTextOutputStream
& stream
)
224 if (thisStyle
.HasURL())
225 stream
<< wxT("</a>");
227 if (thisStyle
.GetFontUnderlined())
228 stream
<< wxT("</u>");
229 if (thisStyle
.GetFontStyle() == wxITALIC
)
230 stream
<< wxT("</i>");
231 if (thisStyle
.GetFontWeight() == wxBOLD
)
232 stream
<< wxT("</b>");
237 stream
<< wxT("</font>");
241 /// Begin paragraph formatting
242 void wxRichTextHTMLHandler::BeginParagraphFormatting(const wxRichTextAttr
& WXUNUSED(currentStyle
), const wxRichTextAttr
& thisStyle
, wxTextOutputStream
& str
)
244 if (thisStyle
.HasPageBreak())
246 str
<< wxT("<div style=\"page-break-after:always\"></div>\n");
249 if (thisStyle
.HasLeftIndent() && thisStyle
.GetLeftIndent() != 0)
251 if (thisStyle
.HasBulletStyle())
253 int indent
= thisStyle
.GetLeftIndent();
255 // Close levels high than this
256 CloseLists(indent
, str
);
258 if (m_indents
.GetCount() > 0 && indent
== m_indents
.Last())
260 // Same level, no need to start a new list
262 else if (m_indents
.GetCount() == 0 || indent
> m_indents
.Last())
264 m_indents
.Add(indent
);
267 int listType
= TypeOfList(thisStyle
, tag
);
268 m_listTypes
.Add(listType
);
270 // wxHTML needs an extra <p> before a list when using <p> ... </p> in previous paragraphs.
271 // TODO: pass a flag that indicates we're using wxHTML.
283 wxString align
= GetAlignment(thisStyle
);
284 str
<< wxString::Format(wxT("<p align=\"%s\""), align
.c_str());
288 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasParagraphSpacingBefore())
290 float spacingBeforeMM
= thisStyle
.GetParagraphSpacingBefore() / 10.0;
292 styleStr
+= wxString::Format(wxT("margin-top: %.2fmm; "), spacingBeforeMM
);
294 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasParagraphSpacingAfter())
296 float spacingAfterMM
= thisStyle
.GetParagraphSpacingAfter() / 10.0;
298 styleStr
+= wxString::Format(wxT("margin-bottom: %.2fmm; "), spacingAfterMM
);
301 float indentLeftMM
= (thisStyle
.GetLeftIndent() + thisStyle
.GetLeftSubIndent())/10.0;
302 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && (indentLeftMM
> 0.0))
304 styleStr
+= wxString::Format(wxT("margin-left: %.2fmm; "), indentLeftMM
);
306 float indentRightMM
= thisStyle
.GetRightIndent()/10.0;
307 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasRightIndent() && (indentRightMM
> 0.0))
309 styleStr
+= wxString::Format(wxT("margin-right: %.2fmm; "), indentRightMM
);
311 // First line indentation
312 float firstLineIndentMM
= - thisStyle
.GetLeftSubIndent() / 10.0;
313 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && (firstLineIndentMM
> 0.0))
315 styleStr
+= wxString::Format(wxT("text-indent: %.2fmm; "), firstLineIndentMM
);
318 if (!styleStr
.IsEmpty())
319 str
<< wxT(" style=\"") << styleStr
<< wxT("\"");
323 // TODO: convert to pixels
324 int indentPixels
= static_cast<int>(indentLeftMM
*10/4);
326 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) == 0)
328 // Use a table to do indenting if we don't have CSS
329 str
<< wxString::Format(wxT("<table border=0 cellpadding=0 cellspacing=0><tr><td width=\"%d\"></td><td>"), indentPixels
);
333 if (((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) == 0) && (thisStyle
.GetLeftSubIndent() < 0))
335 str
<< SymbolicIndent( - thisStyle
.GetLeftSubIndent());
343 wxString align
= GetAlignment(thisStyle
);
344 str
<< wxString::Format(wxT("<p align=\"%s\""), align
.c_str());
348 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasParagraphSpacingBefore())
350 float spacingBeforeMM
= thisStyle
.GetParagraphSpacingBefore() / 10.0;
352 styleStr
+= wxString::Format(wxT("margin-top: %.2fmm; "), spacingBeforeMM
);
354 if ((GetFlags() & wxRICHTEXT_HANDLER_USE_CSS
) && thisStyle
.HasParagraphSpacingAfter())
356 float spacingAfterMM
= thisStyle
.GetParagraphSpacingAfter() / 10.0;
358 styleStr
+= wxString::Format(wxT("margin-bottom: %.2fmm; "), spacingAfterMM
);
361 if (!styleStr
.IsEmpty())
362 str
<< wxT(" style=\"") << styleStr
<< wxT("\"");
366 OutputFont(thisStyle
, str
);
369 /// End paragraph formatting
370 void wxRichTextHTMLHandler::EndParagraphFormatting(const wxRichTextAttr
& WXUNUSED(currentStyle
), const wxRichTextAttr
& thisStyle
, wxTextOutputStream
& stream
)
372 if (thisStyle
.HasFont())
373 stream
<< wxT("</font>");
377 stream
<< wxT("</td></tr></table></p>\n");
380 else if (!thisStyle
.HasBulletStyle())
381 stream
<< wxT("</p>\n");
384 /// Closes lists to level (-1 means close all)
385 void wxRichTextHTMLHandler::CloseLists(int level
, wxTextOutputStream
& str
)
387 // Close levels high than this
388 int i
= m_indents
.GetCount()-1;
391 int l
= m_indents
[i
];
394 if (m_listTypes
[i
] == 0)
398 m_indents
.RemoveAt(i
);
399 m_listTypes
.RemoveAt(i
);
408 void wxRichTextHTMLHandler::OutputFont(const wxRichTextAttr
& style
, wxTextOutputStream
& stream
)
412 stream
<< wxString::Format(wxT("<font face=\"%s\" size=\"%ld\""), style
.GetFontFaceName().c_str(), PtToSize(style
.GetFontSize()));
413 if (style
.HasTextColour())
414 stream
<< wxString::Format(wxT(" color=\"%s\""), style
.GetTextColour().GetAsString(wxC2S_HTML_SYNTAX
).c_str());
419 int wxRichTextHTMLHandler::TypeOfList( const wxRichTextAttr
& thisStyle
, wxString
& tag
)
421 // We can use number attribute of li tag but not all the browsers support it.
422 // also wxHtmlWindow doesn't support type attribute.
424 bool m_is_ul
= false;
425 if (thisStyle
.GetBulletStyle() == (wxTEXT_ATTR_BULLET_STYLE_ARABIC
|wxTEXT_ATTR_BULLET_STYLE_PERIOD
))
426 tag
= wxT("<ol type=\"1\">");
427 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER
)
428 tag
= wxT("<ol type=\"A\">");
429 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER
)
430 tag
= wxT("<ol type=\"a\">");
431 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER
)
432 tag
= wxT("<ol type=\"I\">");
433 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER
)
434 tag
= wxT("<ol type=\"i\">");
447 wxString
wxRichTextHTMLHandler::GetAlignment( const wxRichTextAttr
& thisStyle
)
449 switch( thisStyle
.GetAlignment() )
451 case wxTEXT_ALIGNMENT_LEFT
:
453 case wxTEXT_ALIGNMENT_RIGHT
:
455 case wxTEXT_ALIGNMENT_CENTER
:
456 return wxT("center");
457 case wxTEXT_ALIGNMENT_JUSTIFIED
:
458 return wxT("justify");
464 void wxRichTextHTMLHandler::WriteImage(wxRichTextImage
* image
, wxOutputStream
& stream
)
466 wxTextOutputStream
str(stream
);
468 str
<< wxT("<img src=\"");
471 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())
480 if (image
->GetImageBlock().IsOk())
483 image
->GetImageBlock().Load(img
);
486 wxString
ext(image
->GetImageBlock().GetExtension());
487 wxString
tempFilename(wxString::Format(wxT("image%d.%s"), sm_fileCounter
, ext
));
488 wxMemoryFSHandler::AddFile(tempFilename
, img
, image
->GetImageBlock().GetImageType());
490 m_imageLocations
.Add(tempFilename
);
492 str
<< wxT("memory:") << tempFilename
;
496 str
<< wxT("memory:?");
500 else if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES
)
503 if (!image
->GetImage().Ok() && image
->GetImageBlock().GetData())
504 image
->LoadFromBlock();
505 if (image
->GetImage().Ok() && !image
->GetImageBlock().GetData())
509 if (image
->GetImageBlock().Ok())
511 wxString
tempDir(GetTempDir());
512 if (tempDir
.IsEmpty())
513 tempDir
= wxFileName::GetTempDir();
515 wxString
ext(image
->GetImageBlock().GetExtension());
516 wxString
tempFilename(wxString::Format(wxT("%s/image%d.%s"), tempDir
, sm_fileCounter
, ext
));
517 image
->GetImageBlock().Write(tempFilename
);
519 m_imageLocations
.Add(tempFilename
);
521 str
<< wxFileSystem::FileNameToURL(tempFilename
);
524 str
<< wxT("file:?");
528 else // if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_BASE64) // this is implied
532 str
<< GetMimeType(image
->GetImageBlock().GetImageType());
533 str
<< wxT(";base64,");
535 if (image
->GetImage().Ok() && !image
->GetImageBlock().GetData())
538 if (image
->GetImageBlock().Ok())
540 wxChar
* data
= b64enc( image
->GetImageBlock().GetData(), image
->GetImageBlock().GetDataSize() );
550 long wxRichTextHTMLHandler::PtToSize(long size
)
553 int len
= m_fontSizeMapping
.GetCount();
554 for (i
= 0; i
< len
; i
++)
555 if (size
<= m_fontSizeMapping
[i
])
560 wxString
wxRichTextHTMLHandler::SymbolicIndent(long indent
)
563 for(;indent
> 0; indent
-= 20)
564 in
.Append( wxT(" ") );
568 const wxChar
* wxRichTextHTMLHandler::GetMimeType(int imageType
)
572 case wxBITMAP_TYPE_BMP
:
573 return wxT("image/bmp");
574 case wxBITMAP_TYPE_TIF
:
575 return wxT("image/tiff");
576 case wxBITMAP_TYPE_GIF
:
577 return wxT("image/gif");
578 case wxBITMAP_TYPE_PNG
:
579 return wxT("image/png");
580 case wxBITMAP_TYPE_JPEG
:
581 return wxT("image/jpeg");
583 return wxT("image/unknown");
587 // exim-style base64 encoder
588 wxChar
* wxRichTextHTMLHandler::b64enc( unsigned char* input
, size_t in_len
)
590 // elements of enc64 array must be 8 bit values
591 // otherwise encoder will fail
592 // hmmm.. Does wxT macro define a char as 16 bit value
593 // when compiling with UNICODE option?
594 static const wxChar enc64
[] = wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
595 wxChar
* output
= new wxChar
[4*((in_len
+2)/3)+1];
598 while( in_len
-- > 0 )
600 register wxChar a
, b
;
604 *p
++ = enc64
[ (a
>> 2) & 0x3f ];
608 *p
++ = enc64
[ (a
<< 4 ) & 0x30 ];
616 *p
++ = enc64
[(( a
<< 4 ) | ((b
>> 4) &0xf )) & 0x3f];
620 *p
++ = enc64
[ (b
<< 2) & 0x3f ];
627 *p
++ = enc64
[ ((( b
<< 2 ) & 0x3f ) | ((a
>> 6)& 0x3)) & 0x3f ];
629 *p
++ = enc64
[ a
& 0x3f ];
638 /// Delete the in-memory or temporary files generated by the last operation
639 bool wxRichTextHTMLHandler::DeleteTemporaryImages()
641 return DeleteTemporaryImages(GetFlags(), m_imageLocations
);
644 /// Delete the in-memory or temporary files generated by the last operation
645 bool wxRichTextHTMLHandler::DeleteTemporaryImages(int flags
, const wxArrayString
& imageLocations
)
648 for (i
= 0; i
< imageLocations
.GetCount(); i
++)
650 wxString location
= imageLocations
[i
];
652 if (flags
& wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_MEMORY
)
655 wxMemoryFSHandler::RemoveFile(location
);
658 else if (flags
& wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES
)
660 if (wxFileExists(location
))
661 wxRemoveFile(location
);