Added conversion to HTML, by Akin Demirtug
[wxWidgets.git] / src / richtext / richtexthtml.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: 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
23 #ifndef WX_PRECOMP
24 #include "wx/wx.h"
25 #endif
26
27 #include "wx/filename.h"
28 #include "wx/wfstream.h"
29 #include "wx/txtstrm.h"
30
31 IMPLEMENT_DYNAMIC_CLASS(wxRichTextHTMLHandler, wxRichTextFileHandler)
32
33 /// Can we handle this filename (if using files)? By default, checks the extension.
34 bool wxRichTextHTMLHandler::CanHandle(const wxString& filename) const
35 {
36 wxString path, file, ext;
37 wxSplitPath(filename, & path, & file, & ext);
38
39 return (ext.Lower() == wxT("html") || ext.Lower() == wxT("htm"));
40 }
41
42
43 #if wxUSE_STREAMS
44 bool wxRichTextHTMLHandler::DoLoadFile(wxRichTextBuffer *WXUNUSED(buffer), wxInputStream& WXUNUSED(stream))
45 {
46 return false;
47 }
48
49 /*
50 * We need to output only _changes_ in character formatting.
51 */
52
53 bool wxRichTextHTMLHandler::DoSaveFile(wxRichTextBuffer *buffer, wxOutputStream& stream)
54 {
55 buffer->Defragment();
56
57 wxTextOutputStream str(stream);
58
59 wxTextAttrEx currentParaStyle = buffer->GetAttributes();
60 wxTextAttrEx currentCharStyle = buffer->GetAttributes();
61
62 str << wxT("<html><head></head><body>\n");
63
64 /*
65 wxRichText may be support paper formats like a1/a2/a3/a4
66 when this widget grown enough, i should turn back and support its new features
67 but not yet
68
69 str << wxT("<table border=0 cellpadding=0 cellspacing=0><tr><td>");
70
71 wxString left_indent = SymbolicIndent(currentParaStyle.GetLeftIndent());
72 wxString right_indent = SymbolicIndent(currentParaStyle.GetRightIndent());
73
74 str << wxString::Format(wxT("%s</td><td></td><td>%s</td></tr><tr>"),
75 left_indent.c_str(), //Document-Wide Left Indent
76 right_indent.c_str()); //Document-Wide Right Indent
77
78 str << wxT("<td></td><td width=\"100%\">");
79 */
80
81 str << wxT("<table border=0 cellpadding=0 cellspacing=0><tr><td width=\"100%\">");
82
83 str << wxString::Format(wxT("<font face=\"%s\" size=\"%i\" color=\"#%02X%02X%02X\" >"),
84 currentParaStyle.GetFont().GetFaceName(), Pt_To_Size( currentParaStyle.GetFont().GetPointSize() ),
85 currentParaStyle.GetTextColour().Red(), currentParaStyle.GetTextColour().Green(),
86 currentParaStyle.GetTextColour().Blue());
87
88 //wxString align = GetAlignment( currentParaStyle.GetAlignment() );
89 //str << wxString::Format(wxT("<p align=\"%s\">"), align );
90
91 m_font = false;
92 m_indent = 0;
93 m_list = false;
94
95 wxRichTextObjectList::compatibility_iterator node = buffer->GetChildren().GetFirst();
96 while (node)
97 {
98 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
99 wxASSERT (para != NULL);
100
101 if (para)
102 {
103 OutputParagraphFormatting(currentParaStyle, para->GetAttributes(), stream);
104
105 wxRichTextObjectList::compatibility_iterator node2 = para->GetChildren().GetFirst();
106 while (node2)
107 {
108 wxRichTextObject* obj = node2->GetData();
109 wxRichTextPlainText* textObj = wxDynamicCast(obj, wxRichTextPlainText);
110 if (textObj && !textObj->IsEmpty())
111 {
112 BeginCharacterFormatting(currentCharStyle, obj->GetAttributes(), stream);
113
114 str << textObj->GetText();
115
116 EndCharacterFormatting(currentCharStyle, obj->GetAttributes(), stream);
117 }
118
119 wxRichTextImage* image = wxDynamicCast(obj, wxRichTextImage);
120 if( image && !image->IsEmpty())
121 Image_to_Base64( image, stream );
122
123 node2 = node2->GetNext();
124 }
125 //OutputParagraphFormatting(currentParaStyle, para->GetAttributes(), stream, false);
126 }
127 node = node->GetNext();
128 }
129
130 str << wxT("</font></td></tr></table></body></html>\n");
131
132 return true;
133 }
134
135 void wxRichTextHTMLHandler::BeginCharacterFormatting(const wxTextAttrEx& currentStyle, const wxTextAttrEx& thisStyle, wxOutputStream& stream)
136 {
137 wxTextOutputStream str(stream);
138
139 //Is the item bulleted one?
140 if( thisStyle.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE )
141 {
142 //Is there any opened list?
143 if( m_list )
144 {
145 //Yes there is
146
147 //Is the item among the previous ones
148 //Is the item one of the previous list tag's child items
149 if( (thisStyle.GetLeftIndent() == (m_indent + 100)) || (thisStyle.GetLeftIndent() < 100) )
150 str << wxT("<li>");//Yes it is
151 else
152 {
153 //No it isn't
154
155 //So we should close the list tag
156 str << (m_is_ul ? wxT("</ul>") : wxT("</ol>"));
157
158 //And renavigate to new list's horizontal position
159 NavigateToListPosition(thisStyle, str);
160 //Ok it's done
161
162 //Get the appropriate tag, an ol for numerical values, an ul for dot, square etc.
163 wxString tag;
164 TypeOfList(thisStyle, tag);
165 str << wxString::Format(wxT("%s<li>"), tag);
166 }
167 }
168 else
169 {
170 //No there isn't a list
171
172 //navigate to new list's horizontal position(indent)
173 NavigateToListPosition(thisStyle, str);
174
175 //Get the appropriate tag, an ol for numerical values, an ul for dot, square etc.
176 wxString tag;
177 TypeOfList(thisStyle, tag);
178 str << wxString::Format(wxT("%s<li>"), tag);
179
180 //Now we have a list, mark it.
181 m_list = true;
182 }
183 }
184 else if( m_list )
185 {
186 //The item is not bulleted and there is a list what should be closed now.
187 //So close the list
188
189 str << (m_is_ul ? wxT("</ul>") : wxT("</ol>"));
190 //And mark as there is no an opened list
191 m_list = false;
192 }
193
194 // does the item have an indentation ?
195 if( thisStyle.GetLeftIndent() )
196 {
197 if( thisStyle.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE )
198 {
199 if( m_indent )
200 {
201 if( (thisStyle.GetLeftIndent() + thisStyle.GetLeftSubIndent()) == m_indent )
202 {
203 if( thisStyle.GetLeftSubIndent() < 0 )
204 {
205 wxString symbolic_indent = SymbolicIndent(~thisStyle.GetLeftSubIndent());
206 str << wxString::Format(wxT("%s"), symbolic_indent);
207 }
208 }
209 else
210 {
211 if( thisStyle.GetLeftIndent() + thisStyle.GetLeftSubIndent() > m_indent )
212 {
213 Indent(thisStyle, str);
214 m_indent = thisStyle.GetLeftIndent() + thisStyle.GetLeftSubIndent();
215 m_indents.Add( m_indent );
216 }
217 else
218 {
219 int i = m_indents.size() - 1;
220 for(; i > -1; i--)
221 {
222 if( m_indent < (thisStyle.GetLeftIndent() + thisStyle.GetLeftSubIndent()) )
223 {
224 Indent(thisStyle, str);
225 m_indent = thisStyle.GetLeftIndent() + thisStyle.GetLeftSubIndent();
226 m_indents.Add( m_indent );
227
228 break;
229 }
230 else if( m_indent == (thisStyle.GetLeftIndent() + thisStyle.GetLeftSubIndent()) )
231 {
232 if( thisStyle.GetLeftSubIndent() < 0 )
233 {
234 wxString symbolic_indent = SymbolicIndent(~thisStyle.GetLeftSubIndent());
235 str << wxString::Format(wxT("%s"), symbolic_indent);
236 }
237 break;
238 }
239 else
240 {
241 str << wxT("</td></tr></table>");
242
243 m_indents.RemoveAt(i);
244
245 if( i < 1 ){m_indent=0; break;}
246 m_indent = m_indents[i-1];
247 }
248 }
249 }
250 }
251 }
252 else
253 {
254 Indent(thisStyle, str);
255 m_indent = thisStyle.GetLeftIndent() + thisStyle.GetLeftSubIndent();
256 m_indents.Add( m_indent );
257 }
258 }
259 }
260 else if( m_indent )
261 {
262 //The item is not indented and there is a table(s) what should be closed now.
263
264 //So close them
265 for(unsigned int i = 0; i < m_indents.size(); i++ )
266 str << wxT("</td></tr></table>");
267
268 m_indent = 0;
269 m_indents.Clear();
270 }
271
272
273 wxString style;
274
275 //Is there any change on the font properties of the item
276 if( thisStyle.GetFont().GetFaceName() != currentStyle.GetFont().GetFaceName() )
277 style += wxString::Format(wxT(" face=\"%s\""), thisStyle.GetFont().GetFaceName());
278 if( thisStyle.GetFont().GetPointSize() != currentStyle.GetFont().GetPointSize() )
279 style += wxString::Format(wxT(" size=\"%i\""), Pt_To_Size(thisStyle.GetFont().GetPointSize()) );
280 if( thisStyle.GetTextColour() != currentStyle.GetTextColour() )
281 style += wxString::Format(wxT(" color=\"#%02X%02X%02X\""), thisStyle.GetTextColour().Red(),
282 thisStyle.GetTextColour().Green(), thisStyle.GetTextColour().Blue());
283
284 if( style.size() ){str << wxString::Format(wxT("<font %s >"), style); m_font = true;}
285
286 if( thisStyle.GetFont().GetWeight() == wxBOLD )
287 str << wxT("<b>");
288 if( thisStyle.GetFont().GetStyle() == wxITALIC )
289 str << wxT("<i>");
290 if( thisStyle.GetFont().GetUnderlined() )
291 str << wxT("<u>");
292 }
293
294 void wxRichTextHTMLHandler::EndCharacterFormatting(const wxTextAttrEx& WXUNUSED(currentStyle), const wxTextAttrEx& thisStyle, wxOutputStream& stream)
295 {
296 wxTextOutputStream str(stream);
297
298 if( thisStyle.GetFont().GetUnderlined() )
299 str << wxT("</u>");
300 if( thisStyle.GetFont().GetStyle() == wxITALIC )
301 str << wxT("</i>");
302 if( thisStyle.GetFont().GetWeight() == wxBOLD )
303 str << wxT("</b>");
304
305 if( m_font )
306 {
307 m_font = false;
308 str << wxT("</font>");
309 }
310 }
311
312 /// Output paragraph formatting
313 void wxRichTextHTMLHandler::OutputParagraphFormatting(const wxTextAttrEx& WXUNUSED(currentStyle), const wxTextAttrEx& thisStyle, wxOutputStream& stream)
314 {
315 //If there is no opened list currently, insert a <p> after every paragraph
316 if(!m_list)
317 {
318 wxTextOutputStream str(stream);
319 wxString align = GetAlignment( thisStyle );
320 str << wxString::Format(wxT("<p align=\"%s\">"), align);
321 }
322 }
323
324 void wxRichTextHTMLHandler::NavigateToListPosition(const wxTextAttrEx& thisStyle, wxTextOutputStream& str)
325 {
326 //indenting an item using an ul/ol tag is equal to inserting 5 x &nbsp; on its left side.
327 //so we should start from 100 point left
328
329 //Is the second td's left wall of the current indentaion table at the 100+ point-left-side
330 //of the item, horizontally?
331 if( m_indent + 100 < thisStyle.GetLeftIndent() )
332 {
333 //yes it is
334 LIndent(thisStyle, str);
335 m_indent = thisStyle.GetLeftIndent() - 100;
336 m_indents.Add( m_indent );
337 return;
338 }
339 //No it isn't
340
341 int i = m_indents.size() - 1;
342 for(; i > -1; i--)
343 {
344 //Is the second td's left wall of the current indentaion table at the 100+ point-left-side
345 //of the item ?
346 if( m_indent + 100 < thisStyle.GetLeftIndent() )
347 {
348 //Yes it is
349 LIndent(thisStyle, str);
350 m_indent = thisStyle.GetLeftIndent() - 100;
351 m_indents.Add( m_indent );
352 break;
353 }
354 else if( m_indent + 100 == thisStyle.GetLeftIndent() )
355 break;//exact match
356 else
357 {
358 //No it is not, the second td's left wall of the current indentaion table is at the
359 //right side of the current item horizontally, so close it.
360 str << wxT("</td></tr></table>");
361
362 m_indents.RemoveAt(i);
363
364 if( i < 1 ){m_indent=0; break;}
365 m_indent = m_indents[i-1];
366 }
367 }
368 }
369 void wxRichTextHTMLHandler::Indent( const wxTextAttrEx& thisStyle, wxTextOutputStream& str )
370 {
371 //As a five year experienced web developer i assure you there is no way to indent an item
372 //in html way, but we can use tables.
373
374
375
376 //Item -> "Hello world"
377 //Its Left Indentation -> 100
378 //Its Left Sub-Indentation ->40
379 //A typical indentation-table for the item will be construct as the following
380
381 //3 x nbsp = 60
382 //2 x nbsp = 40
383 //LSI = Left Sub Indent
384 //LI = Left Indent - LSI
385 //
386 //-------------------------------------------
387 //|&nbsp;&nbsp;nbsp;|nbsp;nbsp;Hello World |
388 //| | | | |
389 //| V | V |
390 //| --LI-- | --LSI-- |
391 //-------------------------------------------
392
393 str << wxT("<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
394
395 wxString symbolic_indent = SymbolicIndent( (thisStyle.GetLeftIndent() + thisStyle.GetLeftSubIndent()) - m_indent );
396 str << wxString::Format( wxT("<td>%s</td>"), symbolic_indent );
397 str << wxT("<td width=\"100%\">");
398
399 if( thisStyle.GetLeftSubIndent() < 0 )
400 {
401 symbolic_indent = SymbolicIndent(~thisStyle.GetLeftSubIndent());
402 str << wxString::Format(wxT("%s"), symbolic_indent);
403 }
404 }
405
406 void wxRichTextHTMLHandler::LIndent( const wxTextAttrEx& thisStyle, wxTextOutputStream& str )
407 {
408 //Code:
409 //r.BeginNumberedBullet(1, 200, 60);
410 //r.Newline();
411 //r.WriteText(wxT("first item"));
412 //r.EndNumberedBullet();
413 //r.BeginNumberedBullet(2, 200, 60);
414 //r.Newline();
415 //r.WriteText(wxT("second item."));
416 //r.EndNumberedBullet();
417 //
418 //A typical indentation-table for the item will be construct as the following
419
420 //1 x nbsp = 20 point
421 //ULI -> 100pt (UL/OL tag indents its sub element by 100 point)
422 //<--------- 100 pt ---------->|
423 //------------------------------------------------------
424 //|&nbsp;&nbsp;nbsp;&nbsp;nbsp;|<ul> |
425 //| |<-ULI-><li>first item |
426 //| |<-ULI-><li>second item |
427 //| |</ul> |
428 //------------------------------------------------------
429 // |<-100->|
430
431
432 str << wxT("<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
433
434 wxString symbolic_indent = SymbolicIndent( (thisStyle.GetLeftIndent() - m_indent) - 100);
435 str << wxString::Format( wxT("<td>%s</td>"), symbolic_indent );
436 str << wxT("<td width=\"100%\">");
437 }
438
439 void wxRichTextHTMLHandler::TypeOfList( const wxTextAttrEx& thisStyle, wxString& tag )
440 {
441 //We can use number attribute of li tag but not all the browsers support it.
442 //also wxHtmlWindow doesn't support type attribute.
443
444 m_is_ul = false;
445 if( thisStyle.GetBulletStyle() == (wxTEXT_ATTR_BULLET_STYLE_ARABIC|wxTEXT_ATTR_BULLET_STYLE_PERIOD))
446 tag = wxT("<ol type=\"1\">");
447 else if( thisStyle.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER )
448 tag = wxT("<ol type=\"A\">");
449 else if( thisStyle.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER )
450 tag = wxT("<ol type=\"a\">");
451 else if( thisStyle.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER )
452 tag = wxT("<ol type=\"I\">");
453 else if( thisStyle.GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER )
454 tag = wxT("<ol type=\"i\">");
455 else
456 {
457 tag = wxT("<ul>");
458 m_is_ul = true;
459 }
460 }
461
462 wxString wxRichTextHTMLHandler::GetAlignment( const wxTextAttrEx& thisStyle )
463 {
464 switch( thisStyle.GetAlignment() )
465 {
466 case wxTEXT_ALIGNMENT_LEFT:
467 return wxT("left");
468 case wxTEXT_ALIGNMENT_RIGHT:
469 return wxT("right");
470 case wxTEXT_ALIGNMENT_CENTER:
471 return wxT("center");
472 case wxTEXT_ALIGNMENT_JUSTIFIED:
473 return wxT("justify");
474 default:
475 return wxT("left");
476 }
477 }
478
479 void wxRichTextHTMLHandler::Image_to_Base64(wxRichTextImage* image, wxOutputStream& stream)
480 {
481 wxTextOutputStream str(stream);
482
483 str << wxT("<img src=\"");
484 str << wxT("data:");
485 str << GetMimeType(image->GetImageBlock().GetImageType());
486 str << wxT(";base64,");
487
488 wxChar* data = b64enc( image->GetImageBlock().GetData(), image->GetImageBlock().GetDataSize() );
489 str << data;
490
491 delete[] data;
492
493 str << wxT("\" />");
494 }
495
496 long wxRichTextHTMLHandler::Pt_To_Size(long size)
497 {
498 //return most approximate size
499 if(size < 9 ) return 1;
500 else if( size < 11 ) return 2;
501 else if( size < 14 ) return 3;
502 else if( size < 18 ) return 4;
503 else if( size < 23 ) return 5;
504 else if( size < 30 ) return 6;
505 else return 7;
506 }
507
508 wxString wxRichTextHTMLHandler::SymbolicIndent(long indent)
509 {
510 wxString in;
511 for(;indent > 0; indent -= 20)
512 in.Append( wxT("&nbsp;") );
513 return in;
514 }
515
516 wxChar* wxRichTextHTMLHandler::GetMimeType(int imageType)
517 {
518 switch(imageType)
519 {
520 case wxBITMAP_TYPE_BMP:
521 return wxT("image/bmp");
522 case wxBITMAP_TYPE_TIF:
523 return wxT("image/tiff");
524 case wxBITMAP_TYPE_GIF:
525 return wxT("image/gif");
526 case wxBITMAP_TYPE_PNG:
527 return wxT("image/png");
528 case wxBITMAP_TYPE_JPEG:
529 return wxT("image/jpeg");
530 default:
531 return wxT("image/unknown");
532 }
533 }
534
535 //exim-style base64 encoder
536 wxChar* wxRichTextHTMLHandler::b64enc( unsigned char* input, size_t in_len )
537 {
538 //elements of enc64 array must be 8 bit values
539 //otherwise encoder will fail
540 //hmmm.. Does wxT macro define a char as 16 bit value
541 //when compiling with UNICODE option?
542 const static wxChar* enc64 = wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
543 wxChar* output = new wxChar[4*((in_len+2)/3)+1];
544 wxChar* p = output;
545
546 while( in_len-- > 0 )
547 {
548 register wxChar a, b;
549
550 a = *input++;
551
552 *p++ = enc64[ (a >> 2) & 0x3f ];
553
554 if( in_len-- <= 0 )
555 {
556 *p++ = enc64[ (a << 4 ) & 0x30 ];
557 *p++ = '=';
558 *p++ = '=';
559 break;
560 }
561
562 b = *input++;
563
564 *p++ = enc64[(( a << 4 ) | ((b >> 4) &0xf )) & 0x3f];
565
566 if( in_len-- <= 0 )
567 {
568 *p++ = enc64[ (b << 2) & 0x3f ];
569 *p++ = '=';
570 break;
571 }
572
573 a = *input++;
574
575 *p++ = enc64[ ((( b << 2 ) & 0x3f ) | ((a >> 6)& 0x3)) & 0x3f ];
576
577 *p++ = enc64[ a & 0x3f ];
578 }
579 *p = 0;
580
581 return output;
582 }
583 #endif
584 // wxUSE_STREAMS
585
586 #endif
587 // wxUSE_RICHTEXT
588