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