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 str
<< textObj
->GetText();
106 EndCharacterFormatting(currentCharStyle
, charStyle
, paraStyle
, stream
);
109 wxRichTextImage
* image
= wxDynamicCast(obj
, wxRichTextImage
);
110 if( image
&& !image
->IsEmpty())
111 WriteImage( image
, stream
);
113 node2
= node2
->GetNext();
117 node
= node
->GetNext();
120 str
<< wxT("</font></td></tr></table></body></html>\n");
125 void wxRichTextHTMLHandler::BeginCharacterFormatting(const wxTextAttrEx
& currentStyle
, const wxTextAttrEx
& thisStyle
, const wxTextAttrEx
& paraStyle
, wxOutputStream
& stream
)
127 wxTextOutputStream
str(stream
);
129 // Is the item a bulleted one?
130 if ( paraStyle
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
132 // Is there any opened list?
137 // Is the item among the previous ones?
138 // Is the item one of the previous list tag's child items?
139 if ((paraStyle
.GetLeftIndent() == (m_indent
+ 100)) || (paraStyle
.GetLeftIndent() < 100))
140 str
<< wxT("<li>"); //Yes it is
143 // No it isn't, so we should close the list tag
144 str
<< (m_is_ul
? wxT("</ul>") : wxT("</ol>"));
146 // And renavigate to new list's horizontal position
147 NavigateToListPosition(paraStyle
, str
);
149 // Get the appropriate tag, an ol for numerical values, an ul for dot, square etc.
151 TypeOfList(paraStyle
, tag
);
152 str
<< tag
<< wxT("<li>");
157 // No there isn't a list.
158 // navigate to new list's horizontal position(indent)
159 NavigateToListPosition(paraStyle
, str
);
161 // Get the appropriate tag, an ol for numerical values, an ul for dot, square etc.
163 TypeOfList(paraStyle
, tag
);
164 str
<< tag
<< wxT("<li>");
166 // Now we have a list, mark it.
172 // The item is not bulleted and there is a list what should be closed now.
175 str
<< (m_is_ul
? wxT("</ul>") : wxT("</ol>"));
177 // And mark as there is no an opened list
181 // does the item have an indentation ?
182 if( paraStyle
.GetLeftIndent() )
184 if (paraStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE
)
188 if ((paraStyle
.GetLeftIndent() + paraStyle
.GetLeftSubIndent()) == m_indent
)
190 if (paraStyle
.GetLeftSubIndent() < 0)
192 str
<< SymbolicIndent(~paraStyle
.GetLeftSubIndent());
197 if (paraStyle
.GetLeftIndent() + paraStyle
.GetLeftSubIndent() > m_indent
)
199 Indent(paraStyle
, str
);
200 m_indent
= paraStyle
.GetLeftIndent() + paraStyle
.GetLeftSubIndent();
201 m_indents
.Add( m_indent
);
205 int i
= m_indents
.size() - 1;
208 if (m_indent
< (paraStyle
.GetLeftIndent() + paraStyle
.GetLeftSubIndent()))
210 Indent(paraStyle
, str
);
211 m_indent
= paraStyle
.GetLeftIndent() + paraStyle
.GetLeftSubIndent();
212 m_indents
.Add( m_indent
);
216 else if (m_indent
== (paraStyle
.GetLeftIndent() + paraStyle
.GetLeftSubIndent()))
218 if (paraStyle
.GetLeftSubIndent() < 0)
220 str
<< SymbolicIndent(~paraStyle
.GetLeftSubIndent());
226 str
<< wxT("</td></tr></table>");
228 m_indents
.RemoveAt(i
);
234 m_indent
= m_indents
[i
-1];
242 Indent(paraStyle
, str
);
243 m_indent
= paraStyle
.GetLeftIndent() + paraStyle
.GetLeftSubIndent();
244 m_indents
.Add( m_indent
);
250 // The item is not indented and there is a table(s) that should be closed now.
252 for (unsigned int i
= 0; i
< m_indents
.size(); i
++)
253 str
<< wxT("</td></tr></table>");
262 // Is there any change in the font properties of the item?
263 if (thisStyle
.GetFont().GetFaceName() != currentStyle
.GetFont().GetFaceName())
265 wxString
faceName(thisStyle
.GetFont().GetFaceName());
266 style
+= wxString::Format(wxT(" face=\"%s\""), faceName
.c_str());
268 if (thisStyle
.GetFont().GetPointSize() != currentStyle
.GetFont().GetPointSize())
269 style
+= wxString::Format(wxT(" size=\"%ld\""), PtToSize(thisStyle
.GetFont().GetPointSize()));
270 if (thisStyle
.GetTextColour() != currentStyle
.GetTextColour() )
272 wxString
color(thisStyle
.GetTextColour().GetAsString(wxC2S_HTML_SYNTAX
));
273 style
+= wxString::Format(wxT(" color=\"%s\""), color
.c_str());
278 str
<< wxString::Format(wxT("<font %s >"), style
.c_str());
282 if (thisStyle
.GetFont().GetWeight() == wxBOLD
)
284 if (thisStyle
.GetFont().GetStyle() == wxITALIC
)
286 if (thisStyle
.GetFont().GetUnderlined())
289 if (thisStyle
.HasURL())
290 str
<< wxT("<a href=\"") << thisStyle
.GetURL() << wxT("\">");
293 void wxRichTextHTMLHandler::EndCharacterFormatting(const wxTextAttrEx
& WXUNUSED(currentStyle
), const wxTextAttrEx
& thisStyle
, const wxTextAttrEx
& WXUNUSED(paraStyle
), wxOutputStream
& stream
)
295 wxTextOutputStream
str(stream
);
297 if (thisStyle
.HasURL())
300 if (thisStyle
.GetFont().GetUnderlined())
302 if (thisStyle
.GetFont().GetStyle() == wxITALIC
)
304 if (thisStyle
.GetFont().GetWeight() == wxBOLD
)
310 str
<< wxT("</font>");
314 /// Output paragraph formatting
315 void wxRichTextHTMLHandler::OutputParagraphFormatting(const wxTextAttrEx
& WXUNUSED(currentStyle
), const wxTextAttrEx
& thisStyle
, wxOutputStream
& stream
)
317 // If there is no opened list currently, insert a <p> after every paragraph
320 wxTextOutputStream
str(stream
);
321 wxString align
= GetAlignment(thisStyle
);
322 str
<< wxString::Format(wxT("<p align=\"%s\">"), align
.c_str());
326 void wxRichTextHTMLHandler::NavigateToListPosition(const wxTextAttrEx
& thisStyle
, wxTextOutputStream
& str
)
328 // indenting an item using an ul/ol tag is equal to inserting 5 x on its left side.
329 // so we should start from 100 point left
331 // Is the second td's left wall of the current indentaion table at the 100+ point-left-side
332 // of the item, horizontally?
333 if (m_indent
+ 100 < thisStyle
.GetLeftIndent())
336 LIndent(thisStyle
, str
);
337 m_indent
= thisStyle
.GetLeftIndent() - 100;
338 m_indents
.Add( m_indent
);
343 int i
= m_indents
.size() - 1;
346 //Is the second td's left wall of the current indentaion table at the 100+ point-left-side
348 if (m_indent
+ 100 < thisStyle
.GetLeftIndent())
351 LIndent(thisStyle
, str
);
352 m_indent
= thisStyle
.GetLeftIndent() - 100;
353 m_indents
.Add( m_indent
);
356 else if (m_indent
+ 100 == thisStyle
.GetLeftIndent())
360 // No it is not, the second td's left wall of the current indentaion table is at the
361 //right side of the current item horizontally, so close it.
362 str
<< wxT("</td></tr></table>");
364 m_indents
.RemoveAt(i
);
370 m_indent
= m_indents
[i
-1];
374 void wxRichTextHTMLHandler::Indent( const wxTextAttrEx
& thisStyle
, wxTextOutputStream
& str
)
376 //There is no way to indent an item in HTML, but we can use tables.
378 // Item -> "Hello world"
379 // Its Left Indentation -> 100
380 // Its Left Sub-Indentation ->40
381 // A typical indentation-table for the item will be construct as the following
385 // LSI = Left Sub Indent
386 // LI = Left Indent - LSI
388 // -------------------------------------------
389 // | nbsp;|nbsp;nbsp;Hello World |
392 // | --LI-- | --LSI-- |
393 // -------------------------------------------
395 str
<< wxT("<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
397 wxString symbolic_indent
= SymbolicIndent( (thisStyle
.GetLeftIndent() + thisStyle
.GetLeftSubIndent()) - m_indent
);
398 str
<< wxString::Format( wxT("<td>%s</td>"), symbolic_indent
.c_str() );
399 str
<< wxT("<td width=\"100%\">");
401 if (thisStyle
.GetLeftSubIndent() < 0)
403 str
<< SymbolicIndent(~thisStyle
.GetLeftSubIndent());
407 void wxRichTextHTMLHandler::LIndent( const wxTextAttrEx
& thisStyle
, wxTextOutputStream
& str
)
410 // r.BeginNumberedBullet(1, 200, 60);
412 // r.WriteText(wxT("first item"));
413 // r.EndNumberedBullet();
414 // r.BeginNumberedBullet(2, 200, 60);
416 // r.WriteText(wxT("second item."));
417 // r.EndNumberedBullet();
419 // A typical indentation-table for the item will be construct as the following
421 // 1 x nbsp = 20 point
422 // ULI -> 100pt (UL/OL tag indents its sub element by 100 point)
423 // <--------- 100 pt ---------->|
424 // ------------------------------------------------------
425 // | nbsp; nbsp;|<ul> |
426 // | |<-ULI-><li>first item |
427 // | |<-ULI-><li>second item |
429 // ------------------------------------------------------
433 str
<< wxT("<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
435 wxString symbolic_indent
= SymbolicIndent( (thisStyle
.GetLeftIndent() - m_indent
) - 100);
436 str
<< wxString::Format( wxT("<td>%s</td>"), symbolic_indent
.c_str() );
437 str
<< wxT("<td width=\"100%\">");
440 void wxRichTextHTMLHandler::TypeOfList( const wxTextAttrEx
& thisStyle
, wxString
& tag
)
442 // We can use number attribute of li tag but not all the browsers support it.
443 // also wxHtmlWindow doesn't support type attribute.
446 if (thisStyle
.GetBulletStyle() == (wxTEXT_ATTR_BULLET_STYLE_ARABIC
|wxTEXT_ATTR_BULLET_STYLE_PERIOD
))
447 tag
= wxT("<ol type=\"1\">");
448 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER
)
449 tag
= wxT("<ol type=\"A\">");
450 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER
)
451 tag
= wxT("<ol type=\"a\">");
452 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER
)
453 tag
= wxT("<ol type=\"I\">");
454 else if (thisStyle
.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER
)
455 tag
= wxT("<ol type=\"i\">");
463 wxString
wxRichTextHTMLHandler::GetAlignment( const wxTextAttrEx
& thisStyle
)
465 switch( thisStyle
.GetAlignment() )
467 case wxTEXT_ALIGNMENT_LEFT
:
469 case wxTEXT_ALIGNMENT_RIGHT
:
471 case wxTEXT_ALIGNMENT_CENTER
:
472 return wxT("center");
473 case wxTEXT_ALIGNMENT_JUSTIFIED
:
474 return wxT("justify");
480 void wxRichTextHTMLHandler::WriteImage(wxRichTextImage
* image
, wxOutputStream
& stream
)
482 wxTextOutputStream
str(stream
);
484 str
<< wxT("<img src=\"");
487 if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_MEMORY
)
489 if (!image
->GetImage().Ok() && image
->GetImageBlock().GetData())
490 image
->LoadFromBlock();
491 if (image
->GetImage().Ok() && !image
->GetImageBlock().GetData())
494 if (image
->GetImage().Ok())
496 wxString
ext(image
->GetImageBlock().GetExtension());
497 wxString
tempFilename(wxString::Format(wxT("image%d.%s"), sm_fileCounter
, (const wxChar
*) ext
));
498 wxMemoryFSHandler::AddFile(tempFilename
, image
->GetImage(), image
->GetImageBlock().GetImageType());
500 m_imageLocations
.Add(tempFilename
);
502 str
<< wxT("memory:") << tempFilename
;
505 str
<< wxT("memory:?");
509 else if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES
)
511 if (!image
->GetImage().Ok() && image
->GetImageBlock().GetData())
512 image
->LoadFromBlock();
513 if (image
->GetImage().Ok() && !image
->GetImageBlock().GetData())
516 if (image
->GetImage().Ok())
518 wxString
tempDir(GetTempDir());
519 if (tempDir
.IsEmpty())
520 tempDir
= wxFileName::GetTempDir();
522 wxString
ext(image
->GetImageBlock().GetExtension());
523 wxString
tempFilename(wxString::Format(wxT("%s/image%d.%s"), (const wxChar
*) tempDir
, sm_fileCounter
, (const wxChar
*) ext
));
524 image
->GetImageBlock().Write(tempFilename
);
526 m_imageLocations
.Add(tempFilename
);
528 str
<< wxFileSystem::FileNameToURL(tempFilename
);
531 str
<< wxT("file:?");
535 else // if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_BASE64) // this is implied
539 str
<< GetMimeType(image
->GetImageBlock().GetImageType());
540 str
<< wxT(";base64,");
542 if (image
->GetImage().Ok() && !image
->GetImageBlock().GetData())
545 wxChar
* data
= b64enc( image
->GetImageBlock().GetData(), image
->GetImageBlock().GetDataSize() );
554 long wxRichTextHTMLHandler::PtToSize(long size
)
556 // return approximate size
557 if (size
< 9 ) return 1;
558 else if( size
< 11 ) return 2;
559 else if( size
< 14 ) return 3;
560 else if( size
< 18 ) return 4;
561 else if( size
< 23 ) return 5;
562 else if( size
< 30 ) return 6;
566 wxString
wxRichTextHTMLHandler::SymbolicIndent(long indent
)
569 for(;indent
> 0; indent
-= 20)
570 in
.Append( wxT(" ") );
574 const wxChar
* wxRichTextHTMLHandler::GetMimeType(int imageType
)
578 case wxBITMAP_TYPE_BMP
:
579 return wxT("image/bmp");
580 case wxBITMAP_TYPE_TIF
:
581 return wxT("image/tiff");
582 case wxBITMAP_TYPE_GIF
:
583 return wxT("image/gif");
584 case wxBITMAP_TYPE_PNG
:
585 return wxT("image/png");
586 case wxBITMAP_TYPE_JPEG
:
587 return wxT("image/jpeg");
589 return wxT("image/unknown");
593 // exim-style base64 encoder
594 wxChar
* wxRichTextHTMLHandler::b64enc( unsigned char* input
, size_t in_len
)
596 // elements of enc64 array must be 8 bit values
597 // otherwise encoder will fail
598 // hmmm.. Does wxT macro define a char as 16 bit value
599 // when compiling with UNICODE option?
600 static const wxChar enc64
[] = wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
601 wxChar
* output
= new wxChar
[4*((in_len
+2)/3)+1];
604 while( in_len
-- > 0 )
606 register wxChar a
, b
;
610 *p
++ = enc64
[ (a
>> 2) & 0x3f ];
614 *p
++ = enc64
[ (a
<< 4 ) & 0x30 ];
622 *p
++ = enc64
[(( a
<< 4 ) | ((b
>> 4) &0xf )) & 0x3f];
626 *p
++ = enc64
[ (b
<< 2) & 0x3f ];
633 *p
++ = enc64
[ ((( b
<< 2 ) & 0x3f ) | ((a
>> 6)& 0x3)) & 0x3f ];
635 *p
++ = enc64
[ a
& 0x3f ];
644 /// Delete the in-memory or temporary files generated by the last operation
645 bool wxRichTextHTMLHandler::DeleteTemporaryImages()
647 return DeleteTemporaryImages(GetFlags(), m_imageLocations
);
650 /// Delete the in-memory or temporary files generated by the last operation
651 bool wxRichTextHTMLHandler::DeleteTemporaryImages(int flags
, const wxArrayString
& imageLocations
)
654 for (i
= 0; i
< imageLocations
.GetCount(); i
++)
656 wxString location
= imageLocations
[i
];
658 if (flags
& wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_MEMORY
)
661 wxMemoryFSHandler::RemoveFile(location
);
664 else if (flags
& wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES
)
666 if (wxFileExists(location
))
667 wxRemoveFile(location
);