Fixed #10702 (encoding not used in HTML handler)
[wxWidgets.git] / src / richtext / richtexthtml.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/richtext/richtexthtml.cpp
3 // Purpose: HTML I/O for wxRichTextCtrl
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 2005-09-30
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // For compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
14
15 #ifdef __BORLANDC__
16 #pragma hdrstop
17 #endif
18
19 #if wxUSE_RICHTEXT
20
21 #include "wx/richtext/richtexthtml.h"
22 #include "wx/richtext/richtextstyles.h"
23
24 #ifndef WX_PRECOMP
25 #endif
26
27 #include "wx/filename.h"
28 #include "wx/wfstream.h"
29 #include "wx/txtstrm.h"
30
31 #if wxUSE_FILESYSTEM
32 #include "wx/filesys.h"
33 #include "wx/fs_mem.h"
34 #endif
35
36 IMPLEMENT_DYNAMIC_CLASS(wxRichTextHTMLHandler, wxRichTextFileHandler)
37
38 int wxRichTextHTMLHandler::sm_fileCounter = 1;
39
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)
42 {
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);
50 }
51
52 /// Can we handle this filename (if using files)? By default, checks the extension.
53 bool wxRichTextHTMLHandler::CanHandle(const wxString& filename) const
54 {
55 wxString path, file, ext;
56 wxFileName::SplitPath(filename, & path, & file, & ext);
57
58 return (ext.Lower() == wxT("html") || ext.Lower() == wxT("htm"));
59 }
60
61
62 #if wxUSE_STREAMS
63 bool wxRichTextHTMLHandler::DoLoadFile(wxRichTextBuffer *WXUNUSED(buffer), wxInputStream& WXUNUSED(stream))
64 {
65 return false;
66 }
67
68 /*
69 * We need to output only _changes_ in character formatting.
70 */
71
72 bool wxRichTextHTMLHandler::DoSaveFile(wxRichTextBuffer *buffer, wxOutputStream& stream)
73 {
74 m_buffer = buffer;
75
76 ClearTemporaryImageLocations();
77
78 buffer->Defragment();
79
80 #if wxUSE_UNICODE
81 wxCSConv* customEncoding = NULL;
82 wxMBConv* conv = NULL;
83 if (!GetEncoding().IsEmpty())
84 {
85 customEncoding = new wxCSConv(GetEncoding());
86 if (!customEncoding->IsOk())
87 {
88 delete customEncoding;
89 customEncoding = NULL;
90 }
91 }
92 if (customEncoding)
93 conv = customEncoding;
94 else
95 conv = & wxConvUTF8;
96 #endif
97
98 {
99 #if wxUSE_UNICODE
100 wxTextOutputStream str(stream, wxEOL_NATIVE, *conv);
101 #else
102 wxTextOutputStream str(stream, wxEOL_NATIVE);
103 #endif
104
105 wxTextAttr currentParaStyle = buffer->GetAttributes();
106 wxTextAttr currentCharStyle = buffer->GetAttributes();
107
108 if ((GetFlags() & wxRICHTEXT_HANDLER_NO_HEADER_FOOTER) == 0)
109 str << wxT("<html><head></head><body>\n");
110
111 OutputFont(currentParaStyle, str);
112
113 m_font = false;
114 m_inTable = false;
115
116 m_indents.Clear();
117 m_listTypes.Clear();
118
119 wxRichTextObjectList::compatibility_iterator node = buffer->GetChildren().GetFirst();
120 while (node)
121 {
122 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
123 wxASSERT (para != NULL);
124
125 if (para)
126 {
127 wxTextAttr paraStyle(para->GetCombinedAttributes());
128
129 BeginParagraphFormatting(currentParaStyle, paraStyle, str);
130
131 wxRichTextObjectList::compatibility_iterator node2 = para->GetChildren().GetFirst();
132 while (node2)
133 {
134 wxRichTextObject* obj = node2->GetData();
135 wxRichTextPlainText* textObj = wxDynamicCast(obj, wxRichTextPlainText);
136 if (textObj && !textObj->IsEmpty())
137 {
138 wxTextAttr charStyle(para->GetCombinedAttributes(obj->GetAttributes()));
139 BeginCharacterFormatting(currentCharStyle, charStyle, paraStyle, str);
140
141 wxString text = textObj->GetText();
142
143 if (charStyle.HasTextEffects() && (charStyle.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS))
144 text.MakeUpper();
145
146 wxString toReplace = wxRichTextLineBreakChar;
147 text.Replace(toReplace, wxT("<br>"));
148
149 str << text;
150
151 EndCharacterFormatting(currentCharStyle, charStyle, paraStyle, str);
152 }
153
154 wxRichTextImage* image = wxDynamicCast(obj, wxRichTextImage);
155 if( image && (!image->IsEmpty() || image->GetImageBlock().GetData()))
156 WriteImage( image, stream );
157
158 node2 = node2->GetNext();
159 }
160
161 EndParagraphFormatting(currentParaStyle, paraStyle, str);
162
163 str << wxT("\n");
164 }
165 node = node->GetNext();
166 }
167
168 CloseLists(-1, str);
169
170 str << wxT("</font>");
171
172 if ((GetFlags() & wxRICHTEXT_HANDLER_NO_HEADER_FOOTER) == 0)
173 str << wxT("</body></html>");
174
175 str << wxT("\n");
176 }
177
178 #if wxUSE_UNICODE
179 if (customEncoding)
180 delete customEncoding;
181 #endif
182
183 m_buffer = NULL;
184
185 return true;
186 }
187
188 void wxRichTextHTMLHandler::BeginCharacterFormatting(const wxTextAttr& currentStyle, const wxTextAttr& thisStyle, const wxTextAttr& WXUNUSED(paraStyle), wxTextOutputStream& str)
189 {
190 wxString style;
191
192 // Is there any change in the font properties of the item?
193 if (thisStyle.GetFontFaceName() != currentStyle.GetFontFaceName())
194 {
195 wxString faceName(thisStyle.GetFontFaceName());
196 style += wxString::Format(wxT(" face=\"%s\""), faceName.c_str());
197 }
198 if (thisStyle.GetFontSize() != currentStyle.GetFontSize())
199 style += wxString::Format(wxT(" size=\"%ld\""), PtToSize(thisStyle.GetFontSize()));
200 if (thisStyle.GetTextColour() != currentStyle.GetTextColour() )
201 {
202 wxString color(thisStyle.GetTextColour().GetAsString(wxC2S_HTML_SYNTAX));
203 style += wxString::Format(wxT(" color=\"%s\""), color.c_str());
204 }
205
206 if (style.size())
207 {
208 str << wxString::Format(wxT("<font %s >"), style.c_str());
209 m_font = true;
210 }
211
212 if (thisStyle.GetFontWeight() == wxBOLD)
213 str << wxT("<b>");
214 if (thisStyle.GetFontStyle() == wxITALIC)
215 str << wxT("<i>");
216 if (thisStyle.GetFontUnderlined())
217 str << wxT("<u>");
218
219 if (thisStyle.HasURL())
220 str << wxT("<a href=\"") << thisStyle.GetURL() << wxT("\">");
221 }
222
223 void wxRichTextHTMLHandler::EndCharacterFormatting(const wxTextAttr& WXUNUSED(currentStyle), const wxTextAttr& thisStyle, const wxTextAttr& WXUNUSED(paraStyle), wxTextOutputStream& stream)
224 {
225 if (thisStyle.HasURL())
226 stream << wxT("</a>");
227
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>");
234
235 if (m_font)
236 {
237 m_font = false;
238 stream << wxT("</font>");
239 }
240 }
241
242 /// Begin paragraph formatting
243 void wxRichTextHTMLHandler::BeginParagraphFormatting(const wxTextAttr& WXUNUSED(currentStyle), const wxTextAttr& thisStyle, wxTextOutputStream& str)
244 {
245 if (thisStyle.HasPageBreak())
246 {
247 str << wxT("<div style=\"page-break-after:always\"></div>\n");
248 }
249
250 if (thisStyle.HasLeftIndent() && thisStyle.GetLeftIndent() != 0)
251 {
252 if (thisStyle.HasBulletStyle())
253 {
254 int indent = thisStyle.GetLeftIndent();
255
256 // Close levels high than this
257 CloseLists(indent, str);
258
259 if (m_indents.GetCount() > 0 && indent == m_indents.Last())
260 {
261 // Same level, no need to start a new list
262 }
263 else if (m_indents.GetCount() == 0 || indent > m_indents.Last())
264 {
265 m_indents.Add(indent);
266
267 wxString tag;
268 int listType = TypeOfList(thisStyle, tag);
269 m_listTypes.Add(listType);
270
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.
273 str << wxT("<p>\n");
274
275 str << tag;
276 }
277
278 str << wxT("<li> ");
279 }
280 else
281 {
282 CloseLists(-1, str);
283
284 wxString align = GetAlignment(thisStyle);
285 str << wxString::Format(wxT("<p align=\"%s\""), align.c_str());
286
287 if (thisStyle.HasParagraphSpacingAfter() && thisStyle.GetParagraphSpacingAfter() == 0)
288 str << wxT(" style=\"margin: 0px;\"");
289
290 str << wxT(">");
291
292 // Use a table
293 int indentTenthsMM = thisStyle.GetLeftIndent() + thisStyle.GetLeftSubIndent();
294 // TODO: convert to pixels
295 int indentPixels = indentTenthsMM/4;
296 str << wxString::Format(wxT("<table border=0 cellpadding=0 cellspacing=0><tr><td width=\"%d\"></td><td>"), indentPixels);
297
298 OutputFont(thisStyle, str);
299
300 if (thisStyle.GetLeftSubIndent() < 0)
301 {
302 str << SymbolicIndent( - thisStyle.GetLeftSubIndent());
303 }
304
305 m_inTable = true;
306 }
307 }
308 else
309 {
310 CloseLists(-1, str);
311
312 wxString align = GetAlignment(thisStyle);
313 str << wxString::Format(wxT("<p align=\"%s\""), align.c_str());
314
315 if (thisStyle.HasParagraphSpacingAfter() && thisStyle.GetParagraphSpacingAfter() == 0)
316 str << wxT(" style=\"margin: 0px;\"");
317
318 str << wxT(">");
319 }
320 }
321
322 /// End paragraph formatting
323 void wxRichTextHTMLHandler::EndParagraphFormatting(const wxTextAttr& WXUNUSED(currentStyle), const wxTextAttr& thisStyle, wxTextOutputStream& stream)
324 {
325 if (m_inTable)
326 {
327 if (thisStyle.HasFont())
328 stream << wxT("</font>");
329
330 stream << wxT("</td></tr></table></p>\n");
331 m_inTable = false;
332 }
333 else if (!thisStyle.HasBulletStyle())
334 stream << wxT("</p>\n");
335 }
336
337 /// Closes lists to level (-1 means close all)
338 void wxRichTextHTMLHandler::CloseLists(int level, wxTextOutputStream& str)
339 {
340 // Close levels high than this
341 int i = m_indents.GetCount()-1;
342 while (i >= 0)
343 {
344 int l = m_indents[i];
345 if (l > level)
346 {
347 if (m_listTypes[i] == 0)
348 str << wxT("</ol>");
349 else
350 str << wxT("</ul>");
351 m_indents.RemoveAt(i);
352 m_listTypes.RemoveAt(i);
353 }
354 else
355 break;
356 i --;
357 }
358 }
359
360 /// Output font tag
361 void wxRichTextHTMLHandler::OutputFont(const wxTextAttr& style, wxTextOutputStream& stream)
362 {
363 if (style.HasFont())
364 {
365 stream << wxString::Format(wxT("<font face=\"%s\" size=\"%ld\""), style.GetFontFaceName().c_str(), PtToSize(style.GetFontSize()));
366 if (style.HasTextColour())
367 stream << wxString::Format(wxT(" color=\"%s\""), style.GetTextColour().GetAsString(wxC2S_HTML_SYNTAX).c_str());
368 stream << wxT(" >");
369 }
370 }
371
372 int wxRichTextHTMLHandler::TypeOfList( const wxTextAttr& thisStyle, wxString& tag )
373 {
374 // We can use number attribute of li tag but not all the browsers support it.
375 // also wxHtmlWindow doesn't support type attribute.
376
377 bool m_is_ul = false;
378 if (thisStyle.GetBulletStyle() == (wxTEXT_ATTR_BULLET_STYLE_ARABIC|wxTEXT_ATTR_BULLET_STYLE_PERIOD))
379 tag = wxT("<ol type=\"1\">");
380 else if (thisStyle.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER)
381 tag = wxT("<ol type=\"A\">");
382 else if (thisStyle.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER)
383 tag = wxT("<ol type=\"a\">");
384 else if (thisStyle.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER)
385 tag = wxT("<ol type=\"I\">");
386 else if (thisStyle.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER)
387 tag = wxT("<ol type=\"i\">");
388 else
389 {
390 tag = wxT("<ul>");
391 m_is_ul = true;
392 }
393
394 if (m_is_ul)
395 return 1;
396 else
397 return 0;
398 }
399
400 wxString wxRichTextHTMLHandler::GetAlignment( const wxTextAttr& thisStyle )
401 {
402 switch( thisStyle.GetAlignment() )
403 {
404 case wxTEXT_ALIGNMENT_LEFT:
405 return wxT("left");
406 case wxTEXT_ALIGNMENT_RIGHT:
407 return wxT("right");
408 case wxTEXT_ALIGNMENT_CENTER:
409 return wxT("center");
410 case wxTEXT_ALIGNMENT_JUSTIFIED:
411 return wxT("justify");
412 default:
413 return wxT("left");
414 }
415 }
416
417 void wxRichTextHTMLHandler::WriteImage(wxRichTextImage* image, wxOutputStream& stream)
418 {
419 wxTextOutputStream str(stream);
420
421 str << wxT("<img src=\"");
422
423 #if wxUSE_FILESYSTEM
424 if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_MEMORY)
425 {
426 if (!image->GetImage().Ok() && image->GetImageBlock().GetData())
427 image->LoadFromBlock();
428 if (image->GetImage().Ok() && !image->GetImageBlock().GetData())
429 image->MakeBlock();
430
431 if (image->GetImage().Ok())
432 {
433 wxString ext(image->GetImageBlock().GetExtension());
434 wxString tempFilename(wxString::Format(wxT("image%d.%s"), sm_fileCounter, ext));
435 wxMemoryFSHandler::AddFile(tempFilename, image->GetImage(), image->GetImageBlock().GetImageType());
436
437 m_imageLocations.Add(tempFilename);
438
439 str << wxT("memory:") << tempFilename;
440 }
441 else
442 str << wxT("memory:?");
443
444 sm_fileCounter ++;
445 }
446 else if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES)
447 {
448 if (!image->GetImage().Ok() && image->GetImageBlock().GetData())
449 image->LoadFromBlock();
450 if (image->GetImage().Ok() && !image->GetImageBlock().GetData())
451 image->MakeBlock();
452
453 if (image->GetImage().Ok())
454 {
455 wxString tempDir(GetTempDir());
456 if (tempDir.IsEmpty())
457 tempDir = wxFileName::GetTempDir();
458
459 wxString ext(image->GetImageBlock().GetExtension());
460 wxString tempFilename(wxString::Format(wxT("%s/image%d.%s"), tempDir, sm_fileCounter, ext));
461 image->GetImageBlock().Write(tempFilename);
462
463 m_imageLocations.Add(tempFilename);
464
465 str << wxFileSystem::FileNameToURL(tempFilename);
466 }
467 else
468 str << wxT("file:?");
469
470 sm_fileCounter ++;
471 }
472 else // if (GetFlags() & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_BASE64) // this is implied
473 #endif
474 {
475 str << wxT("data:");
476 str << GetMimeType(image->GetImageBlock().GetImageType());
477 str << wxT(";base64,");
478
479 if (image->GetImage().Ok() && !image->GetImageBlock().GetData())
480 image->MakeBlock();
481
482 wxChar* data = b64enc( image->GetImageBlock().GetData(), image->GetImageBlock().GetDataSize() );
483 str << data;
484
485 delete[] data;
486 }
487
488 str << wxT("\" />");
489 }
490
491 long wxRichTextHTMLHandler::PtToSize(long size)
492 {
493 int i;
494 int len = m_fontSizeMapping.GetCount();
495 for (i = 0; i < len; i++)
496 if (size <= m_fontSizeMapping[i])
497 return i+1;
498 return 7;
499 }
500
501 wxString wxRichTextHTMLHandler::SymbolicIndent(long indent)
502 {
503 wxString in;
504 for(;indent > 0; indent -= 20)
505 in.Append( wxT("&nbsp;") );
506 return in;
507 }
508
509 const wxChar* wxRichTextHTMLHandler::GetMimeType(int imageType)
510 {
511 switch(imageType)
512 {
513 case wxBITMAP_TYPE_BMP:
514 return wxT("image/bmp");
515 case wxBITMAP_TYPE_TIF:
516 return wxT("image/tiff");
517 case wxBITMAP_TYPE_GIF:
518 return wxT("image/gif");
519 case wxBITMAP_TYPE_PNG:
520 return wxT("image/png");
521 case wxBITMAP_TYPE_JPEG:
522 return wxT("image/jpeg");
523 default:
524 return wxT("image/unknown");
525 }
526 }
527
528 // exim-style base64 encoder
529 wxChar* wxRichTextHTMLHandler::b64enc( unsigned char* input, size_t in_len )
530 {
531 // elements of enc64 array must be 8 bit values
532 // otherwise encoder will fail
533 // hmmm.. Does wxT macro define a char as 16 bit value
534 // when compiling with UNICODE option?
535 static const wxChar enc64[] = wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
536 wxChar* output = new wxChar[4*((in_len+2)/3)+1];
537 wxChar* p = output;
538
539 while( in_len-- > 0 )
540 {
541 register wxChar a, b;
542
543 a = *input++;
544
545 *p++ = enc64[ (a >> 2) & 0x3f ];
546
547 if( in_len-- == 0 )
548 {
549 *p++ = enc64[ (a << 4 ) & 0x30 ];
550 *p++ = '=';
551 *p++ = '=';
552 break;
553 }
554
555 b = *input++;
556
557 *p++ = enc64[(( a << 4 ) | ((b >> 4) &0xf )) & 0x3f];
558
559 if( in_len-- == 0 )
560 {
561 *p++ = enc64[ (b << 2) & 0x3f ];
562 *p++ = '=';
563 break;
564 }
565
566 a = *input++;
567
568 *p++ = enc64[ ((( b << 2 ) & 0x3f ) | ((a >> 6)& 0x3)) & 0x3f ];
569
570 *p++ = enc64[ a & 0x3f ];
571 }
572 *p = 0;
573
574 return output;
575 }
576 #endif
577 // wxUSE_STREAMS
578
579 /// Delete the in-memory or temporary files generated by the last operation
580 bool wxRichTextHTMLHandler::DeleteTemporaryImages()
581 {
582 return DeleteTemporaryImages(GetFlags(), m_imageLocations);
583 }
584
585 /// Delete the in-memory or temporary files generated by the last operation
586 bool wxRichTextHTMLHandler::DeleteTemporaryImages(int flags, const wxArrayString& imageLocations)
587 {
588 size_t i;
589 for (i = 0; i < imageLocations.GetCount(); i++)
590 {
591 wxString location = imageLocations[i];
592
593 if (flags & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_MEMORY)
594 {
595 #if wxUSE_FILESYSTEM
596 wxMemoryFSHandler::RemoveFile(location);
597 #endif
598 }
599 else if (flags & wxRICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES)
600 {
601 if (wxFileExists(location))
602 wxRemoveFile(location);
603 }
604 }
605
606 return true;
607 }
608
609
610 #endif
611 // wxUSE_RICHTEXT
612