Don't clear background in Refresh (to suit poor implementations of Refresh)
[wxWidgets.git] / src / richtext / richtextbuffer.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: richtext/richtextbuffer.cpp
3 // Purpose: Buffer 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 #ifndef WX_PRECOMP
20 #include "wx/wx.h"
21 #endif
22
23 #include "wx/image.h"
24
25 #if wxUSE_RICHTEXT
26
27 #include "wx/filename.h"
28 #include "wx/clipbrd.h"
29 #include "wx/dataobj.h"
30 #include "wx/wfstream.h"
31 #include "wx/module.h"
32 #include "wx/mstream.h"
33 #include "wx/sstream.h"
34
35 #include "wx/richtext/richtextbuffer.h"
36 #include "wx/richtext/richtextctrl.h"
37 #include "wx/richtext/richtextstyles.h"
38
39 #include "wx/listimpl.cpp"
40
41 WX_DEFINE_LIST(wxRichTextObjectList);
42 WX_DEFINE_LIST(wxRichTextLineList);
43
44 /*!
45 * wxRichTextObject
46 * This is the base for drawable objects.
47 */
48
49 IMPLEMENT_CLASS(wxRichTextObject, wxObject)
50
51 wxRichTextObject::wxRichTextObject(wxRichTextObject* parent)
52 {
53 m_dirty = false;
54 m_refCount = 1;
55 m_parent = parent;
56 m_leftMargin = 0;
57 m_rightMargin = 0;
58 m_topMargin = 0;
59 m_bottomMargin = 0;
60 m_descent = 0;
61 }
62
63 wxRichTextObject::~wxRichTextObject()
64 {
65 }
66
67 void wxRichTextObject::Dereference()
68 {
69 m_refCount --;
70 if (m_refCount <= 0)
71 delete this;
72 }
73
74 /// Copy
75 void wxRichTextObject::Copy(const wxRichTextObject& obj)
76 {
77 m_size = obj.m_size;
78 m_pos = obj.m_pos;
79 m_dirty = obj.m_dirty;
80 m_range = obj.m_range;
81 m_attributes = obj.m_attributes;
82 m_descent = obj.m_descent;
83
84 if (!m_attributes.GetFont().Ok())
85 wxLogDebug(wxT("No font!"));
86 if (!obj.m_attributes.GetFont().Ok())
87 wxLogDebug(wxT("Parent has no font!"));
88 }
89
90 void wxRichTextObject::SetMargins(int margin)
91 {
92 m_leftMargin = m_rightMargin = m_topMargin = m_bottomMargin = margin;
93 }
94
95 void wxRichTextObject::SetMargins(int leftMargin, int rightMargin, int topMargin, int bottomMargin)
96 {
97 m_leftMargin = leftMargin;
98 m_rightMargin = rightMargin;
99 m_topMargin = topMargin;
100 m_bottomMargin = bottomMargin;
101 }
102
103 // Convert units in tends of a millimetre to device units
104 int wxRichTextObject::ConvertTenthsMMToPixels(wxDC& dc, int units)
105 {
106 int ppi = dc.GetPPI().x;
107
108 // There are ppi pixels in 254.1 "1/10 mm"
109
110 double pixels = ((double) units * (double)ppi) / 254.1;
111
112 return (int) pixels;
113 }
114
115 /// Dump to output stream for debugging
116 void wxRichTextObject::Dump(wxTextOutputStream& stream)
117 {
118 stream << GetClassInfo()->GetClassName() << wxT("\n");
119 stream << wxString::Format(wxT("Size: %d,%d. Position: %d,%d, Range: %ld,%ld"), m_size.x, m_size.y, m_pos.x, m_pos.y, m_range.GetStart(), m_range.GetEnd()) << wxT("\n");
120 stream << wxString::Format(wxT("Text colour: %d,%d,%d."), (int) m_attributes.GetTextColour().Red(), (int) m_attributes.GetTextColour().Green(), (int) m_attributes.GetTextColour().Blue()) << wxT("\n");
121 }
122
123
124 /*!
125 * wxRichTextCompositeObject
126 * This is the base for drawable objects.
127 */
128
129 IMPLEMENT_CLASS(wxRichTextCompositeObject, wxRichTextObject)
130
131 wxRichTextCompositeObject::wxRichTextCompositeObject(wxRichTextObject* parent):
132 wxRichTextObject(parent)
133 {
134 }
135
136 wxRichTextCompositeObject::~wxRichTextCompositeObject()
137 {
138 DeleteChildren();
139 }
140
141 /// Get the nth child
142 wxRichTextObject* wxRichTextCompositeObject::GetChild(size_t n) const
143 {
144 wxASSERT ( n < m_children.GetCount() );
145
146 return m_children.Item(n)->GetData();
147 }
148
149 /// Append a child, returning the position
150 size_t wxRichTextCompositeObject::AppendChild(wxRichTextObject* child)
151 {
152 m_children.Append(child);
153 child->SetParent(this);
154 return m_children.GetCount() - 1;
155 }
156
157 /// Insert the child in front of the given object, or at the beginning
158 bool wxRichTextCompositeObject::InsertChild(wxRichTextObject* child, wxRichTextObject* inFrontOf)
159 {
160 if (inFrontOf)
161 {
162 wxRichTextObjectList::compatibility_iterator node = m_children.Find(inFrontOf);
163 m_children.Insert(node, child);
164 }
165 else
166 m_children.Insert(child);
167 child->SetParent(this);
168
169 return true;
170 }
171
172 /// Delete the child
173 bool wxRichTextCompositeObject::RemoveChild(wxRichTextObject* child, bool deleteChild)
174 {
175 wxRichTextObjectList::compatibility_iterator node = m_children.Find(child);
176 if (node)
177 {
178 wxRichTextObject* obj = node->GetData();
179 m_children.Erase(node);
180 if (deleteChild)
181 delete obj;
182
183 return true;
184 }
185 return false;
186 }
187
188 /// Delete all children
189 bool wxRichTextCompositeObject::DeleteChildren()
190 {
191 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
192 while (node)
193 {
194 wxRichTextObjectList::compatibility_iterator oldNode = node;
195
196 wxRichTextObject* child = node->GetData();
197 child->Dereference(); // Only delete if reference count is zero
198
199 node = node->GetNext();
200 m_children.Erase(oldNode);
201 }
202
203 return true;
204 }
205
206 /// Get the child count
207 size_t wxRichTextCompositeObject::GetChildCount() const
208 {
209 return m_children.GetCount();
210 }
211
212 /// Copy
213 void wxRichTextCompositeObject::Copy(const wxRichTextCompositeObject& obj)
214 {
215 wxRichTextObject::Copy(obj);
216
217 DeleteChildren();
218
219 wxRichTextObjectList::compatibility_iterator node = obj.m_children.GetFirst();
220 while (node)
221 {
222 wxRichTextObject* child = node->GetData();
223 m_children.Append(child->Clone());
224
225 node = node->GetNext();
226 }
227 }
228
229 /// Hit-testing: returns a flag indicating hit test details, plus
230 /// information about position
231 int wxRichTextCompositeObject::HitTest(wxDC& dc, const wxPoint& pt, long& textPosition)
232 {
233 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
234 while (node)
235 {
236 wxRichTextObject* child = node->GetData();
237
238 int ret = child->HitTest(dc, pt, textPosition);
239 if (ret != wxRICHTEXT_HITTEST_NONE)
240 return ret;
241
242 node = node->GetNext();
243 }
244
245 return wxRICHTEXT_HITTEST_NONE;
246 }
247
248 /// Finds the absolute position and row height for the given character position
249 bool wxRichTextCompositeObject::FindPosition(wxDC& dc, long index, wxPoint& pt, int* height, bool forceLineStart)
250 {
251 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
252 while (node)
253 {
254 wxRichTextObject* child = node->GetData();
255
256 if (child->FindPosition(dc, index, pt, height, forceLineStart))
257 return true;
258
259 node = node->GetNext();
260 }
261
262 return false;
263 }
264
265 /// Calculate range
266 void wxRichTextCompositeObject::CalculateRange(long start, long& end)
267 {
268 long current = start;
269 long lastEnd = current;
270
271 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
272 while (node)
273 {
274 wxRichTextObject* child = node->GetData();
275 long childEnd = 0;
276
277 child->CalculateRange(current, childEnd);
278 lastEnd = childEnd;
279
280 current = childEnd + 1;
281
282 node = node->GetNext();
283 }
284
285 end = lastEnd;
286
287 // An object with no children has zero length
288 if (m_children.GetCount() == 0)
289 end --;
290
291 m_range.SetRange(start, end);
292 }
293
294 /// Delete range from layout.
295 bool wxRichTextCompositeObject::DeleteRange(const wxRichTextRange& range)
296 {
297 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
298
299 while (node)
300 {
301 wxRichTextObject* obj = (wxRichTextObject*) node->GetData();
302 wxRichTextObjectList::compatibility_iterator next = node->GetNext();
303
304 // Delete the range in each paragraph
305
306 // When a chunk has been deleted, internally the content does not
307 // now match the ranges.
308 // However, so long as deletion is not done on the same object twice this is OK.
309 // If you may delete content from the same object twice, recalculate
310 // the ranges inbetween DeleteRange calls by calling CalculateRanges, and
311 // adjust the range you're deleting accordingly.
312
313 if (!obj->GetRange().IsOutside(range))
314 {
315 obj->DeleteRange(range);
316
317 // Delete an empty object, or paragraph within this range.
318 if (obj->IsEmpty() ||
319 (range.GetStart() <= obj->GetRange().GetStart() && range.GetEnd() >= obj->GetRange().GetEnd()))
320 {
321 // An empty paragraph has length 1, so won't be deleted unless the
322 // whole range is deleted.
323 RemoveChild(obj, true);
324 }
325 }
326
327 node = next;
328 }
329
330 return true;
331 }
332
333 /// Get any text in this object for the given range
334 wxString wxRichTextCompositeObject::GetTextForRange(const wxRichTextRange& range) const
335 {
336 wxString text;
337 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
338 while (node)
339 {
340 wxRichTextObject* child = node->GetData();
341 wxRichTextRange childRange = range;
342 if (!child->GetRange().IsOutside(range))
343 {
344 childRange.LimitTo(child->GetRange());
345
346 wxString childText = child->GetTextForRange(childRange);
347
348 text += childText;
349 }
350 node = node->GetNext();
351 }
352
353 return text;
354 }
355
356 /// Recursively merge all pieces that can be merged.
357 bool wxRichTextCompositeObject::Defragment()
358 {
359 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
360 while (node)
361 {
362 wxRichTextObject* child = node->GetData();
363 wxRichTextCompositeObject* composite = wxDynamicCast(child, wxRichTextCompositeObject);
364 if (composite)
365 composite->Defragment();
366
367 if (node->GetNext())
368 {
369 wxRichTextObject* nextChild = node->GetNext()->GetData();
370 if (child->CanMerge(nextChild) && child->Merge(nextChild))
371 {
372 nextChild->Dereference();
373 m_children.Erase(node->GetNext());
374
375 // Don't set node -- we'll see if we can merge again with the next
376 // child.
377 }
378 else
379 node = node->GetNext();
380 }
381 else
382 node = node->GetNext();
383 }
384
385 return true;
386 }
387
388 /// Dump to output stream for debugging
389 void wxRichTextCompositeObject::Dump(wxTextOutputStream& stream)
390 {
391 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
392 while (node)
393 {
394 wxRichTextObject* child = node->GetData();
395 child->Dump(stream);
396 node = node->GetNext();
397 }
398 }
399
400
401 /*!
402 * wxRichTextBox
403 * This defines a 2D space to lay out objects
404 */
405
406 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBox, wxRichTextCompositeObject)
407
408 wxRichTextBox::wxRichTextBox(wxRichTextObject* parent):
409 wxRichTextCompositeObject(parent)
410 {
411 }
412
413 /// Draw the item
414 bool wxRichTextBox::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextRange& selectionRange, const wxRect& WXUNUSED(rect), int descent, int style)
415 {
416 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
417 while (node)
418 {
419 wxRichTextObject* child = node->GetData();
420
421 wxRect childRect = wxRect(child->GetPosition(), child->GetCachedSize());
422 child->Draw(dc, range, selectionRange, childRect, descent, style);
423
424 node = node->GetNext();
425 }
426 return true;
427 }
428
429 /// Lay the item out
430 bool wxRichTextBox::Layout(wxDC& dc, const wxRect& rect, int style)
431 {
432 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
433 while (node)
434 {
435 wxRichTextObject* child = node->GetData();
436 child->Layout(dc, rect, style);
437
438 node = node->GetNext();
439 }
440 m_dirty = false;
441 return true;
442 }
443
444 /// Get/set the size for the given range. Assume only has one child.
445 bool wxRichTextBox::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, int flags) const
446 {
447 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
448 if (node)
449 {
450 wxRichTextObject* child = node->GetData();
451 return child->GetRangeSize(range, size, descent, dc, flags);
452 }
453 else
454 return false;
455 }
456
457 /// Copy
458 void wxRichTextBox::Copy(const wxRichTextBox& obj)
459 {
460 wxRichTextCompositeObject::Copy(obj);
461 }
462
463
464 /*!
465 * wxRichTextParagraphLayoutBox
466 * This box knows how to lay out paragraphs.
467 */
468
469 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraphLayoutBox, wxRichTextBox)
470
471 wxRichTextParagraphLayoutBox::wxRichTextParagraphLayoutBox(wxRichTextObject* parent):
472 wxRichTextBox(parent)
473 {
474 Init();
475 }
476
477 /// Initialize the object.
478 void wxRichTextParagraphLayoutBox::Init()
479 {
480 m_ctrl = NULL;
481
482 // For now, assume is the only box and has no initial size.
483 m_range = wxRichTextRange(0, -1);
484
485 m_invalidRange.SetRange(-1, -1);
486 m_leftMargin = 4;
487 m_rightMargin = 4;
488 m_topMargin = 4;
489 m_bottomMargin = 4;
490 }
491
492 /// Draw the item
493 bool wxRichTextParagraphLayoutBox::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextRange& selectionRange, const wxRect& rect, int descent, int style)
494 {
495 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
496 while (node)
497 {
498 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
499 wxASSERT (child != NULL);
500
501 if (child && !child->GetRange().IsOutside(range))
502 {
503 wxRect childRect(child->GetPosition(), child->GetCachedSize());
504
505 if (childRect.GetTop() > rect.GetBottom() || childRect.GetBottom() < rect.GetTop())
506 {
507 // Skip
508 }
509 else
510 child->Draw(dc, child->GetRange(), selectionRange, childRect, descent, style);
511 }
512
513 node = node->GetNext();
514 }
515 return true;
516 }
517
518 /// Lay the item out
519 bool wxRichTextParagraphLayoutBox::Layout(wxDC& dc, const wxRect& rect, int style)
520 {
521 wxRect availableSpace;
522 bool formatRect = (style & wxRICHTEXT_LAYOUT_SPECIFIED_RECT) == wxRICHTEXT_LAYOUT_SPECIFIED_RECT;
523
524 // If only laying out a specific area, the passed rect has a different meaning:
525 // the visible part of the buffer.
526 if (formatRect)
527 {
528 availableSpace = wxRect(0 + m_leftMargin,
529 0 + m_topMargin,
530 rect.width - m_leftMargin - m_rightMargin,
531 rect.height);
532
533 // Invalidate the part of the buffer from the first visible line
534 // to the end. If other parts of the buffer are currently invalid,
535 // then they too will be taken into account if they are above
536 // the visible point.
537 long startPos = 0;
538 wxRichTextLine* line = GetLineAtYPosition(rect.y);
539 if (line)
540 startPos = line->GetAbsoluteRange().GetStart();
541
542 Invalidate(wxRichTextRange(startPos, GetRange().GetEnd()));
543 }
544 else
545 availableSpace = wxRect(rect.x + m_leftMargin,
546 rect.y + m_topMargin,
547 rect.width - m_leftMargin - m_rightMargin,
548 rect.height - m_topMargin - m_bottomMargin);
549
550 int maxWidth = 0;
551
552 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
553
554 bool layoutAll = true;
555
556 // Get invalid range, rounding to paragraph start/end.
557 wxRichTextRange invalidRange = GetInvalidRange(true);
558
559 if (invalidRange == wxRICHTEXT_NONE && !formatRect)
560 return true;
561
562 if (invalidRange == wxRICHTEXT_ALL)
563 layoutAll = true;
564 else // If we know what range is affected, start laying out from that point on.
565 if (invalidRange.GetStart() > GetRange().GetStart())
566 {
567 wxRichTextParagraph* firstParagraph = GetParagraphAtPosition(invalidRange.GetStart());
568 if (firstParagraph)
569 {
570 wxRichTextObjectList::compatibility_iterator firstNode = m_children.Find(firstParagraph);
571 wxRichTextObjectList::compatibility_iterator previousNode = firstNode ? firstNode->GetPrevious() : wxRichTextObjectList::compatibility_iterator();
572 if (firstNode && previousNode)
573 {
574 wxRichTextParagraph* previousParagraph = wxDynamicCast(previousNode->GetData(), wxRichTextParagraph);
575 availableSpace.y = previousParagraph->GetPosition().y + previousParagraph->GetCachedSize().y;
576
577 // Now we're going to start iterating from the first affected paragraph.
578 node = firstNode;
579
580 layoutAll = false;
581 }
582 }
583 }
584
585 // A way to force speedy rest-of-buffer layout (the 'else' below)
586 bool forceQuickLayout = false;
587
588 while (node)
589 {
590 // Assume this box only contains paragraphs
591
592 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
593 wxASSERT (child != NULL);
594
595 // TODO: what if the child hasn't been laid out (e.g. involved in Undo) but still has 'old' lines
596 if (child && !forceQuickLayout && (layoutAll || child->GetLines().GetCount() == 0 || !child->GetRange().IsOutside(invalidRange)))
597 {
598 child->Layout(dc, availableSpace, style);
599
600 // Layout must set the cached size
601 availableSpace.y += child->GetCachedSize().y;
602 maxWidth = wxMax(maxWidth, child->GetCachedSize().x);
603
604 // If we're just formatting the visible part of the buffer,
605 // and we're now past the bottom of the window, start quick
606 // layout.
607 if (formatRect && child->GetPosition().y > rect.GetBottom())
608 forceQuickLayout = true;
609 }
610 else
611 {
612 // We're outside the immediately affected range, so now let's just
613 // move everything up or down. This assumes that all the children have previously
614 // been laid out and have wrapped line lists associated with them.
615 // TODO: check all paragraphs before the affected range.
616
617 int inc = availableSpace.y - child->GetPosition().y;
618
619 while (node)
620 {
621 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
622 if (child)
623 {
624 if (child->GetLines().GetCount() == 0)
625 child->Layout(dc, availableSpace, style);
626 else
627 child->SetPosition(wxPoint(child->GetPosition().x, child->GetPosition().y + inc));
628
629 availableSpace.y += child->GetCachedSize().y;
630 maxWidth = wxMax(maxWidth, child->GetCachedSize().x);
631 }
632
633 node = node->GetNext();
634 }
635 break;
636 }
637
638 node = node->GetNext();
639 }
640
641 SetCachedSize(wxSize(maxWidth, availableSpace.y));
642
643 m_dirty = false;
644 m_invalidRange = wxRICHTEXT_NONE;
645
646 return true;
647 }
648
649 /// Copy
650 void wxRichTextParagraphLayoutBox::Copy(const wxRichTextParagraphLayoutBox& obj)
651 {
652 wxRichTextBox::Copy(obj);
653 }
654
655 /// Get/set the size for the given range.
656 bool wxRichTextParagraphLayoutBox::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, int flags) const
657 {
658 wxSize sz;
659
660 wxRichTextObjectList::compatibility_iterator startPara = wxRichTextObjectList::compatibility_iterator();
661 wxRichTextObjectList::compatibility_iterator endPara = wxRichTextObjectList::compatibility_iterator();
662
663 // First find the first paragraph whose starting position is within the range.
664 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
665 while (node)
666 {
667 // child is a paragraph
668 wxRichTextObject* child = node->GetData();
669 const wxRichTextRange& r = child->GetRange();
670
671 if (r.GetStart() <= range.GetStart() && r.GetEnd() >= range.GetStart())
672 {
673 startPara = node;
674 break;
675 }
676
677 node = node->GetNext();
678 }
679
680 // Next find the last paragraph containing part of the range
681 node = m_children.GetFirst();
682 while (node)
683 {
684 // child is a paragraph
685 wxRichTextObject* child = node->GetData();
686 const wxRichTextRange& r = child->GetRange();
687
688 if (r.GetStart() <= range.GetEnd() && r.GetEnd() >= range.GetEnd())
689 {
690 endPara = node;
691 break;
692 }
693
694 node = node->GetNext();
695 }
696
697 if (!startPara || !endPara)
698 return false;
699
700 // Now we can add up the sizes
701 for (node = startPara; node ; node = node->GetNext())
702 {
703 // child is a paragraph
704 wxRichTextObject* child = node->GetData();
705 const wxRichTextRange& childRange = child->GetRange();
706 wxRichTextRange rangeToFind = range;
707 rangeToFind.LimitTo(childRange);
708
709 wxSize childSize;
710
711 int childDescent = 0;
712 child->GetRangeSize(rangeToFind, childSize, childDescent, dc, flags);
713
714 descent = wxMax(childDescent, descent);
715
716 sz.x = wxMax(sz.x, childSize.x);
717 sz.y += childSize.y;
718
719 if (node == endPara)
720 break;
721 }
722
723 size = sz;
724
725 return true;
726 }
727
728 /// Get the paragraph at the given position
729 wxRichTextParagraph* wxRichTextParagraphLayoutBox::GetParagraphAtPosition(long pos, bool caretPosition) const
730 {
731 if (caretPosition)
732 pos ++;
733
734 // First find the first paragraph whose starting position is within the range.
735 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
736 while (node)
737 {
738 // child is a paragraph
739 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
740 wxASSERT (child != NULL);
741
742 // Return first child in buffer if position is -1
743 // if (pos == -1)
744 // return child;
745
746 if (child->GetRange().Contains(pos))
747 return child;
748
749 node = node->GetNext();
750 }
751 return NULL;
752 }
753
754 /// Get the line at the given position
755 wxRichTextLine* wxRichTextParagraphLayoutBox::GetLineAtPosition(long pos, bool caretPosition) const
756 {
757 if (caretPosition)
758 pos ++;
759
760 // First find the first paragraph whose starting position is within the range.
761 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
762 while (node)
763 {
764 // child is a paragraph
765 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
766 wxASSERT (child != NULL);
767
768 wxRichTextLineList::compatibility_iterator node2 = child->GetLines().GetFirst();
769 while (node2)
770 {
771 wxRichTextLine* line = node2->GetData();
772
773 wxRichTextRange range = line->GetAbsoluteRange();
774
775 if (range.Contains(pos) ||
776
777 // If the position is end-of-paragraph, then return the last line of
778 // of the paragraph.
779 (range.GetEnd() == child->GetRange().GetEnd()-1) && (pos == child->GetRange().GetEnd()))
780 return line;
781
782 node2 = node2->GetNext();
783 }
784
785 node = node->GetNext();
786 }
787
788 int lineCount = GetLineCount();
789 if (lineCount > 0)
790 return GetLineForVisibleLineNumber(lineCount-1);
791 else
792 return NULL;
793 }
794
795 /// Get the line at the given y pixel position, or the last line.
796 wxRichTextLine* wxRichTextParagraphLayoutBox::GetLineAtYPosition(int y) const
797 {
798 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
799 while (node)
800 {
801 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
802 wxASSERT (child != NULL);
803
804 wxRichTextLineList::compatibility_iterator node2 = child->GetLines().GetFirst();
805 while (node2)
806 {
807 wxRichTextLine* line = node2->GetData();
808
809 wxRect rect(line->GetRect());
810
811 if (y <= rect.GetBottom())
812 return line;
813
814 node2 = node2->GetNext();
815 }
816
817 node = node->GetNext();
818 }
819
820 // Return last line
821 int lineCount = GetLineCount();
822 if (lineCount > 0)
823 return GetLineForVisibleLineNumber(lineCount-1);
824 else
825 return NULL;
826 }
827
828 /// Get the number of visible lines
829 int wxRichTextParagraphLayoutBox::GetLineCount() const
830 {
831 int count = 0;
832
833 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
834 while (node)
835 {
836 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
837 wxASSERT (child != NULL);
838
839 count += child->GetLines().GetCount();
840 node = node->GetNext();
841 }
842 return count;
843 }
844
845
846 /// Get the paragraph for a given line
847 wxRichTextParagraph* wxRichTextParagraphLayoutBox::GetParagraphForLine(wxRichTextLine* line) const
848 {
849 return GetParagraphAtPosition(line->GetAbsoluteRange().GetStart());
850 }
851
852 /// Get the line size at the given position
853 wxSize wxRichTextParagraphLayoutBox::GetLineSizeAtPosition(long pos, bool caretPosition) const
854 {
855 wxRichTextLine* line = GetLineAtPosition(pos, caretPosition);
856 if (line)
857 {
858 return line->GetSize();
859 }
860 else
861 return wxSize(0, 0);
862 }
863
864
865 /// Convenience function to add a paragraph of text
866 wxRichTextRange wxRichTextParagraphLayoutBox::AddParagraph(const wxString& text)
867 {
868 wxTextAttrEx style(GetAttributes());
869
870 // Apply default style. If the style has no attributes set,
871 // then the attributes will remain the 'basic style' (i.e. the
872 // layout box's style).
873 wxRichTextApplyStyle(style, GetDefaultStyle());
874
875 wxRichTextParagraph* para = new wxRichTextParagraph(text, this, & style);
876
877 AppendChild(para);
878
879 UpdateRanges();
880 SetDirty(true);
881
882 return para->GetRange();
883 }
884
885 /// Adds multiple paragraphs, based on newlines.
886 wxRichTextRange wxRichTextParagraphLayoutBox::AddParagraphs(const wxString& text)
887 {
888 wxTextAttrEx style(GetAttributes());
889 //wxLogDebug("Initial style = %s", style.GetFont().GetFaceName());
890 //wxLogDebug("Initial size = %d", style.GetFont().GetPointSize());
891
892 // Apply default style. If the style has no attributes set,
893 // then the attributes will remain the 'basic style' (i.e. the
894 // layout box's style).
895 wxRichTextApplyStyle(style, GetDefaultStyle());
896
897 //wxLogDebug("Style after applying default style = %s", style.GetFont().GetFaceName());
898 //wxLogDebug("Size after applying default style = %d", style.GetFont().GetPointSize());
899
900 wxRichTextParagraph* firstPara = NULL;
901 wxRichTextParagraph* lastPara = NULL;
902
903 wxRichTextRange range(-1, -1);
904 size_t i = 0;
905 size_t len = text.Length();
906 wxString line;
907 while (i < len)
908 {
909 wxChar ch = text[i];
910 if (ch == wxT('\n') || ch == wxT('\r'))
911 {
912 wxRichTextParagraph* para = new wxRichTextParagraph(line, this, & style);
913
914 AppendChild(para);
915 if (!firstPara)
916 firstPara = para;
917 lastPara = para;
918 line = wxEmptyString;
919 }
920 else
921 line += ch;
922
923 i ++;
924 }
925 if (!line.empty())
926 {
927 lastPara = new wxRichTextParagraph(line, this, & style);
928 //wxLogDebug("Para Face = %s", lastPara->GetAttributes().GetFont().GetFaceName());
929 AppendChild(lastPara);
930 }
931
932 if (firstPara)
933 range.SetStart(firstPara->GetRange().GetStart());
934 else if (lastPara)
935 range.SetStart(lastPara->GetRange().GetStart());
936
937 if (lastPara)
938 range.SetEnd(lastPara->GetRange().GetEnd());
939 else if (firstPara)
940 range.SetEnd(firstPara->GetRange().GetEnd());
941
942 UpdateRanges();
943 SetDirty(false);
944
945 return GetRange();
946 }
947
948 /// Convenience function to add an image
949 wxRichTextRange wxRichTextParagraphLayoutBox::AddImage(const wxImage& image)
950 {
951 wxTextAttrEx style(GetAttributes());
952
953 // Apply default style. If the style has no attributes set,
954 // then the attributes will remain the 'basic style' (i.e. the
955 // layout box's style).
956 wxRichTextApplyStyle(style, GetDefaultStyle());
957
958 wxRichTextParagraph* para = new wxRichTextParagraph(this, & style);
959 AppendChild(para);
960 para->AppendChild(new wxRichTextImage(image, this));
961
962 UpdateRanges();
963 SetDirty(true);
964
965 return para->GetRange();
966 }
967
968
969 /// Insert fragment into this box at the given position. If partialParagraph is true,
970 /// it is assumed that the last (or only) paragraph is just a piece of data with no paragraph
971 /// marker.
972 /// TODO: if fragment is inserted inside styled fragment, must apply that style to
973 /// to the data (if it has a default style, anyway).
974
975 bool wxRichTextParagraphLayoutBox::InsertFragment(long position, wxRichTextFragment& fragment)
976 {
977 SetDirty(true);
978
979 // First, find the first paragraph whose starting position is within the range.
980 wxRichTextParagraph* para = GetParagraphAtPosition(position);
981 if (para)
982 {
983 wxRichTextObjectList::compatibility_iterator node = m_children.Find(para);
984
985 // Now split at this position, returning the object to insert the new
986 // ones in front of.
987 wxRichTextObject* nextObject = para->SplitAt(position);
988
989 // Special case: partial paragraph, just one paragraph. Might be a small amount of
990 // text, for example, so let's optimize.
991
992 if (fragment.GetPartialParagraph() && fragment.GetChildren().GetCount() == 1)
993 {
994 // Add the first para to this para...
995 wxRichTextObjectList::compatibility_iterator firstParaNode = fragment.GetChildren().GetFirst();
996 if (!firstParaNode)
997 return false;
998
999 // Iterate through the fragment paragraph inserting the content into this paragraph.
1000 wxRichTextParagraph* firstPara = wxDynamicCast(firstParaNode->GetData(), wxRichTextParagraph);
1001 wxASSERT (firstPara != NULL);
1002
1003 wxRichTextObjectList::compatibility_iterator objectNode = firstPara->GetChildren().GetFirst();
1004 while (objectNode)
1005 {
1006 wxRichTextObject* newObj = objectNode->GetData()->Clone();
1007
1008 if (!nextObject)
1009 {
1010 // Append
1011 para->AppendChild(newObj);
1012 }
1013 else
1014 {
1015 // Insert before nextObject
1016 para->InsertChild(newObj, nextObject);
1017 }
1018
1019 objectNode = objectNode->GetNext();
1020 }
1021
1022 return true;
1023 }
1024 else
1025 {
1026 // Procedure for inserting a fragment consisting of a number of
1027 // paragraphs:
1028 //
1029 // 1. Remove and save the content that's after the insertion point, for adding
1030 // back once we've added the fragment.
1031 // 2. Add the content from the first fragment paragraph to the current
1032 // paragraph.
1033 // 3. Add remaining fragment paragraphs after the current paragraph.
1034 // 4. Add back the saved content from the first paragraph. If partialParagraph
1035 // is true, add it to the last paragraph added and not a new one.
1036
1037 // 1. Remove and save objects after split point.
1038 wxList savedObjects;
1039 if (nextObject)
1040 para->MoveToList(nextObject, savedObjects);
1041
1042 // 2. Add the content from the 1st fragment paragraph.
1043 wxRichTextObjectList::compatibility_iterator firstParaNode = fragment.GetChildren().GetFirst();
1044 if (!firstParaNode)
1045 return false;
1046
1047 wxRichTextParagraph* firstPara = wxDynamicCast(firstParaNode->GetData(), wxRichTextParagraph);
1048 wxASSERT(firstPara != NULL);
1049
1050 wxRichTextObjectList::compatibility_iterator objectNode = firstPara->GetChildren().GetFirst();
1051 while (objectNode)
1052 {
1053 wxRichTextObject* newObj = objectNode->GetData()->Clone();
1054
1055 // Append
1056 para->AppendChild(newObj);
1057
1058 objectNode = objectNode->GetNext();
1059 }
1060
1061 // 3. Add remaining fragment paragraphs after the current paragraph.
1062 wxRichTextObjectList::compatibility_iterator nextParagraphNode = node->GetNext();
1063 wxRichTextObject* nextParagraph = NULL;
1064 if (nextParagraphNode)
1065 nextParagraph = nextParagraphNode->GetData();
1066
1067 wxRichTextObjectList::compatibility_iterator i = fragment.GetChildren().GetFirst()->GetNext();
1068 wxRichTextParagraph* finalPara = para;
1069
1070 // If there was only one paragraph, we need to insert a new one.
1071 if (!i)
1072 {
1073 finalPara = new wxRichTextParagraph;
1074
1075 // TODO: These attributes should come from the subsequent paragraph
1076 // when originally deleted, since the subsequent para takes on
1077 // the previous para's attributes.
1078 finalPara->SetAttributes(firstPara->GetAttributes());
1079
1080 if (nextParagraph)
1081 InsertChild(finalPara, nextParagraph);
1082 else
1083 AppendChild(finalPara);
1084 }
1085 else while (i)
1086 {
1087 wxRichTextParagraph* para = wxDynamicCast(i->GetData(), wxRichTextParagraph);
1088 wxASSERT( para != NULL );
1089
1090 finalPara = (wxRichTextParagraph*) para->Clone();
1091
1092 if (nextParagraph)
1093 InsertChild(finalPara, nextParagraph);
1094 else
1095 AppendChild(finalPara);
1096
1097 i = i->GetNext();
1098 }
1099
1100 // 4. Add back the remaining content.
1101 if (finalPara)
1102 {
1103 finalPara->MoveFromList(savedObjects);
1104
1105 // Ensure there's at least one object
1106 if (finalPara->GetChildCount() == 0)
1107 {
1108 wxRichTextPlainText* text = new wxRichTextPlainText(wxEmptyString);
1109 text->SetAttributes(finalPara->GetAttributes());
1110
1111 finalPara->AppendChild(text);
1112 }
1113 }
1114
1115 return true;
1116 }
1117 }
1118 else
1119 {
1120 // Append
1121 wxRichTextObjectList::compatibility_iterator i = fragment.GetChildren().GetFirst();
1122 while (i)
1123 {
1124 wxRichTextParagraph* para = wxDynamicCast(i->GetData(), wxRichTextParagraph);
1125 wxASSERT( para != NULL );
1126
1127 AppendChild(para->Clone());
1128
1129 i = i->GetNext();
1130 }
1131
1132 return true;
1133 }
1134
1135 return false;
1136 }
1137
1138 /// Make a copy of the fragment corresponding to the given range, putting it in 'fragment'.
1139 /// If there was an incomplete paragraph at the end, partialParagraph is set to true.
1140 bool wxRichTextParagraphLayoutBox::CopyFragment(const wxRichTextRange& range, wxRichTextFragment& fragment)
1141 {
1142 wxRichTextObjectList::compatibility_iterator i = GetChildren().GetFirst();
1143 while (i)
1144 {
1145 wxRichTextParagraph* para = wxDynamicCast(i->GetData(), wxRichTextParagraph);
1146 wxASSERT( para != NULL );
1147
1148 if (!para->GetRange().IsOutside(range))
1149 {
1150 fragment.AppendChild(para->Clone());
1151 }
1152 i = i->GetNext();
1153 }
1154
1155 // Now top and tail the first and last paragraphs in our new fragment (which might be the same).
1156 if (!fragment.IsEmpty())
1157 {
1158 wxRichTextRange topTailRange(range);
1159
1160 wxRichTextParagraph* firstPara = wxDynamicCast(fragment.GetChildren().GetFirst()->GetData(), wxRichTextParagraph);
1161 wxASSERT( firstPara != NULL );
1162
1163 // Chop off the start of the paragraph
1164 if (topTailRange.GetStart() > firstPara->GetRange().GetStart())
1165 {
1166 wxRichTextRange r(firstPara->GetRange().GetStart(), topTailRange.GetStart()-1);
1167 firstPara->DeleteRange(r);
1168
1169 // Make sure the numbering is correct
1170 long end;
1171 fragment.CalculateRange(firstPara->GetRange().GetStart(), end);
1172
1173 // Now, we've deleted some positions, so adjust the range
1174 // accordingly.
1175 topTailRange.SetEnd(topTailRange.GetEnd() - r.GetLength());
1176 }
1177
1178 wxRichTextParagraph* lastPara = wxDynamicCast(fragment.GetChildren().GetLast()->GetData(), wxRichTextParagraph);
1179 wxASSERT( lastPara != NULL );
1180
1181 if (topTailRange.GetEnd() < (lastPara->GetRange().GetEnd()-1))
1182 {
1183 wxRichTextRange r(topTailRange.GetEnd()+1, lastPara->GetRange().GetEnd()-1); /* -1 since actual text ends 1 position before end of para marker */
1184 lastPara->DeleteRange(r);
1185
1186 // Make sure the numbering is correct
1187 long end;
1188 fragment.CalculateRange(firstPara->GetRange().GetStart(), end);
1189
1190 // We only have part of a paragraph at the end
1191 fragment.SetPartialParagraph(true);
1192 }
1193 else
1194 {
1195 if (topTailRange.GetEnd() == (lastPara->GetRange().GetEnd() - 1))
1196 // We have a partial paragraph (don't save last new paragraph marker)
1197 fragment.SetPartialParagraph(true);
1198 else
1199 // We have a complete paragraph
1200 fragment.SetPartialParagraph(false);
1201 }
1202 }
1203
1204 return true;
1205 }
1206
1207 /// Given a position, get the number of the visible line (potentially many to a paragraph),
1208 /// starting from zero at the start of the buffer.
1209 long wxRichTextParagraphLayoutBox::GetVisibleLineNumber(long pos, bool caretPosition, bool startOfLine) const
1210 {
1211 if (caretPosition)
1212 pos ++;
1213
1214 int lineCount = 0;
1215
1216 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
1217 while (node)
1218 {
1219 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
1220 wxASSERT( child != NULL );
1221
1222 if (child->GetRange().Contains(pos))
1223 {
1224 wxRichTextLineList::compatibility_iterator node2 = child->GetLines().GetFirst();
1225 while (node2)
1226 {
1227 wxRichTextLine* line = node2->GetData();
1228 wxRichTextRange lineRange = line->GetAbsoluteRange();
1229
1230 if (lineRange.Contains(pos))
1231 {
1232 // If the caret is displayed at the end of the previous wrapped line,
1233 // we want to return the line it's _displayed_ at (not the actual line
1234 // containing the position).
1235 if (lineRange.GetStart() == pos && !startOfLine && child->GetRange().GetStart() != pos)
1236 return lineCount - 1;
1237 else
1238 return lineCount;
1239 }
1240
1241 lineCount ++;
1242
1243 node2 = node2->GetNext();
1244 }
1245 // If we didn't find it in the lines, it must be
1246 // the last position of the paragraph. So return the last line.
1247 return lineCount-1;
1248 }
1249 else
1250 lineCount += child->GetLines().GetCount();
1251
1252 node = node->GetNext();
1253 }
1254
1255 // Not found
1256 return -1;
1257 }
1258
1259 /// Given a line number, get the corresponding wxRichTextLine object.
1260 wxRichTextLine* wxRichTextParagraphLayoutBox::GetLineForVisibleLineNumber(long lineNumber) const
1261 {
1262 int lineCount = 0;
1263
1264 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
1265 while (node)
1266 {
1267 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
1268 wxASSERT(child != NULL);
1269
1270 if (lineNumber < (int) (child->GetLines().GetCount() + lineCount))
1271 {
1272 wxRichTextLineList::compatibility_iterator node2 = child->GetLines().GetFirst();
1273 while (node2)
1274 {
1275 wxRichTextLine* line = node2->GetData();
1276
1277 if (lineCount == lineNumber)
1278 return line;
1279
1280 lineCount ++;
1281
1282 node2 = node2->GetNext();
1283 }
1284 }
1285 else
1286 lineCount += child->GetLines().GetCount();
1287
1288 node = node->GetNext();
1289 }
1290
1291 // Didn't find it
1292 return NULL;
1293 }
1294
1295 /// Delete range from layout.
1296 bool wxRichTextParagraphLayoutBox::DeleteRange(const wxRichTextRange& range)
1297 {
1298 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
1299
1300 while (node)
1301 {
1302 wxRichTextParagraph* obj = wxDynamicCast(node->GetData(), wxRichTextParagraph);
1303 wxASSERT (obj != NULL);
1304
1305 wxRichTextObjectList::compatibility_iterator next = node->GetNext();
1306
1307 // Delete the range in each paragraph
1308
1309 if (!obj->GetRange().IsOutside(range))
1310 {
1311 // Deletes the content of this object within the given range
1312 obj->DeleteRange(range);
1313
1314 // If the whole paragraph is within the range to delete,
1315 // delete the whole thing.
1316 if (range.GetStart() <= obj->GetRange().GetStart() && range.GetEnd() >= obj->GetRange().GetEnd())
1317 {
1318 // Delete the whole object
1319 RemoveChild(obj, true);
1320 }
1321 // If the range includes the paragraph end, we need to join this
1322 // and the next paragraph.
1323 else if (range.Contains(obj->GetRange().GetEnd()))
1324 {
1325 // We need to move the objects from the next paragraph
1326 // to this paragraph
1327
1328 if (next)
1329 {
1330 wxRichTextParagraph* nextParagraph = wxDynamicCast(next->GetData(), wxRichTextParagraph);
1331 next = next->GetNext();
1332 if (nextParagraph)
1333 {
1334 // Delete the stuff we need to delete
1335 nextParagraph->DeleteRange(range);
1336
1337 // Move the objects to the previous para
1338 wxRichTextObjectList::compatibility_iterator node1 = nextParagraph->GetChildren().GetFirst();
1339
1340 while (node1)
1341 {
1342 wxRichTextObject* obj1 = node1->GetData();
1343
1344 // If the object is empty, optimise it out
1345 if (obj1->IsEmpty())
1346 {
1347 delete obj1;
1348 }
1349 else
1350 {
1351 obj->AppendChild(obj1);
1352 }
1353
1354 wxRichTextObjectList::compatibility_iterator next1 = node1->GetNext();
1355 nextParagraph->GetChildren().Erase(node1);
1356
1357 node1 = next1;
1358 }
1359
1360 // Delete the paragraph
1361 RemoveChild(nextParagraph, true);
1362
1363 }
1364 }
1365
1366 }
1367 }
1368
1369 node = next;
1370 }
1371
1372 return true;
1373 }
1374
1375 /// Get any text in this object for the given range
1376 wxString wxRichTextParagraphLayoutBox::GetTextForRange(const wxRichTextRange& range) const
1377 {
1378 int lineCount = 0;
1379 wxString text;
1380 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
1381 while (node)
1382 {
1383 wxRichTextObject* child = node->GetData();
1384 if (!child->GetRange().IsOutside(range))
1385 {
1386 if (lineCount > 0)
1387 text += wxT("\n");
1388 wxRichTextRange childRange = range;
1389 childRange.LimitTo(child->GetRange());
1390
1391 wxString childText = child->GetTextForRange(childRange);
1392
1393 text += childText;
1394
1395 lineCount ++;
1396 }
1397 node = node->GetNext();
1398 }
1399
1400 return text;
1401 }
1402
1403 /// Get all the text
1404 wxString wxRichTextParagraphLayoutBox::GetText() const
1405 {
1406 return GetTextForRange(GetRange());
1407 }
1408
1409 /// Get the paragraph by number
1410 wxRichTextParagraph* wxRichTextParagraphLayoutBox::GetParagraphAtLine(long paragraphNumber) const
1411 {
1412 if ((size_t) paragraphNumber <= GetChildCount())
1413 return NULL;
1414
1415 return (wxRichTextParagraph*) GetChild((size_t) paragraphNumber);
1416 }
1417
1418 /// Get the length of the paragraph
1419 int wxRichTextParagraphLayoutBox::GetParagraphLength(long paragraphNumber) const
1420 {
1421 wxRichTextParagraph* para = GetParagraphAtLine(paragraphNumber);
1422 if (para)
1423 return para->GetRange().GetLength() - 1; // don't include newline
1424 else
1425 return 0;
1426 }
1427
1428 /// Get the text of the paragraph
1429 wxString wxRichTextParagraphLayoutBox::GetParagraphText(long paragraphNumber) const
1430 {
1431 wxRichTextParagraph* para = GetParagraphAtLine(paragraphNumber);
1432 if (para)
1433 return para->GetTextForRange(para->GetRange());
1434 else
1435 return wxEmptyString;
1436 }
1437
1438 /// Convert zero-based line column and paragraph number to a position.
1439 long wxRichTextParagraphLayoutBox::XYToPosition(long x, long y) const
1440 {
1441 wxRichTextParagraph* para = GetParagraphAtLine(y);
1442 if (para)
1443 {
1444 return para->GetRange().GetStart() + x;
1445 }
1446 else
1447 return -1;
1448 }
1449
1450 /// Convert zero-based position to line column and paragraph number
1451 bool wxRichTextParagraphLayoutBox::PositionToXY(long pos, long* x, long* y) const
1452 {
1453 wxRichTextParagraph* para = GetParagraphAtPosition(pos);
1454 if (para)
1455 {
1456 int count = 0;
1457 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
1458 while (node)
1459 {
1460 wxRichTextObject* child = node->GetData();
1461 if (child == para)
1462 break;
1463 count ++;
1464 node = node->GetNext();
1465 }
1466
1467 *y = count;
1468 *x = pos - para->GetRange().GetStart();
1469
1470 return true;
1471 }
1472 else
1473 return false;
1474 }
1475
1476 /// Get the leaf object in a paragraph at this position.
1477 /// Given a line number, get the corresponding wxRichTextLine object.
1478 wxRichTextObject* wxRichTextParagraphLayoutBox::GetLeafObjectAtPosition(long position) const
1479 {
1480 wxRichTextParagraph* para = GetParagraphAtPosition(position);
1481 if (para)
1482 {
1483 wxRichTextObjectList::compatibility_iterator node = para->GetChildren().GetFirst();
1484
1485 while (node)
1486 {
1487 wxRichTextObject* child = node->GetData();
1488 if (child->GetRange().Contains(position))
1489 return child;
1490
1491 node = node->GetNext();
1492 }
1493 if (position == para->GetRange().GetEnd() && para->GetChildCount() > 0)
1494 return para->GetChildren().GetLast()->GetData();
1495 }
1496 return NULL;
1497 }
1498
1499 /// Set character or paragraph text attributes: apply character styles only to immediate text nodes
1500 bool wxRichTextParagraphLayoutBox::SetStyle(const wxRichTextRange& range, const wxRichTextAttr& style, bool withUndo)
1501 {
1502 bool characterStyle = false;
1503 bool paragraphStyle = false;
1504
1505 if (style.IsCharacterStyle())
1506 characterStyle = true;
1507 if (style.IsParagraphStyle())
1508 paragraphStyle = true;
1509
1510 // If we are associated with a control, make undoable; otherwise, apply immediately
1511 // to the data.
1512
1513 bool haveControl = (GetRichTextCtrl() != NULL);
1514
1515 wxRichTextAction* action = NULL;
1516
1517 if (haveControl && withUndo)
1518 {
1519 action = new wxRichTextAction(NULL, _("Change Style"), wxRICHTEXT_CHANGE_STYLE, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
1520 action->SetRange(range);
1521 action->SetPosition(GetRichTextCtrl()->GetCaretPosition());
1522 }
1523
1524 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
1525 while (node)
1526 {
1527 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
1528 wxASSERT (para != NULL);
1529
1530 if (para && para->GetChildCount() > 0)
1531 {
1532 // Stop searching if we're beyond the range of interest
1533 if (para->GetRange().GetStart() > range.GetEnd())
1534 break;
1535
1536 if (!para->GetRange().IsOutside(range))
1537 {
1538 // We'll be using a copy of the paragraph to make style changes,
1539 // not updating the buffer directly.
1540 wxRichTextParagraph* newPara wxDUMMY_INITIALIZE(NULL);
1541
1542 if (haveControl && withUndo)
1543 {
1544 newPara = new wxRichTextParagraph(*para);
1545 action->GetNewParagraphs().AppendChild(newPara);
1546
1547 // Also store the old ones for Undo
1548 action->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para));
1549 }
1550 else
1551 newPara = para;
1552
1553 if (paragraphStyle)
1554 wxRichTextApplyStyle(newPara->GetAttributes(), style);
1555
1556 if (characterStyle && range.GetStart() != newPara->GetRange().GetEnd())
1557 {
1558 wxRichTextRange childRange(range);
1559 childRange.LimitTo(newPara->GetRange());
1560
1561 // Find the starting position and if necessary split it so
1562 // we can start applying a different style.
1563 // TODO: check that the style actually changes or is different
1564 // from style outside of range
1565 wxRichTextObject* firstObject wxDUMMY_INITIALIZE(NULL);
1566 wxRichTextObject* lastObject wxDUMMY_INITIALIZE(NULL);
1567
1568 if (childRange.GetStart() == newPara->GetRange().GetStart())
1569 firstObject = newPara->GetChildren().GetFirst()->GetData();
1570 else
1571 firstObject = newPara->SplitAt(range.GetStart());
1572
1573 // Increment by 1 because we're apply the style one _after_ the split point
1574 long splitPoint = childRange.GetEnd();
1575 if (splitPoint != newPara->GetRange().GetEnd())
1576 splitPoint ++;
1577
1578 // Find last object
1579 if (splitPoint == newPara->GetRange().GetEnd() || splitPoint == (newPara->GetRange().GetEnd() - 1))
1580 lastObject = newPara->GetChildren().GetLast()->GetData();
1581 else
1582 // lastObject is set as a side-effect of splitting. It's
1583 // returned as the object before the new object.
1584 (void) newPara->SplitAt(splitPoint, & lastObject);
1585
1586 wxASSERT(firstObject != NULL);
1587 wxASSERT(lastObject != NULL);
1588
1589 if (!firstObject || !lastObject)
1590 continue;
1591
1592 wxRichTextObjectList::compatibility_iterator firstNode = newPara->GetChildren().Find(firstObject);
1593 wxRichTextObjectList::compatibility_iterator lastNode = newPara->GetChildren().Find(lastObject);
1594
1595 wxASSERT(firstNode != NULL);
1596 wxASSERT(lastNode != NULL);
1597
1598 wxRichTextObjectList::compatibility_iterator node2 = firstNode;
1599
1600 while (node2)
1601 {
1602 wxRichTextObject* child = node2->GetData();
1603
1604 wxRichTextApplyStyle(child->GetAttributes(), style);
1605 if (node2 == lastNode)
1606 break;
1607
1608 node2 = node2->GetNext();
1609 }
1610 }
1611 }
1612 }
1613
1614 node = node->GetNext();
1615 }
1616
1617 // Do action, or delay it until end of batch.
1618 if (haveControl && withUndo)
1619 GetRichTextCtrl()->GetBuffer().SubmitAction(action);
1620
1621 return true;
1622 }
1623
1624 /// Set text attributes
1625 bool wxRichTextParagraphLayoutBox::SetStyle(const wxRichTextRange& range, const wxTextAttrEx& style, bool withUndo)
1626 {
1627 wxRichTextAttr richStyle = style;
1628 return SetStyle(range, richStyle, withUndo);
1629 }
1630
1631 /// Get the text attributes for this position.
1632 bool wxRichTextParagraphLayoutBox::GetStyle(long position, wxTextAttrEx& style) const
1633 {
1634 wxRichTextObject* obj wxDUMMY_INITIALIZE(NULL);
1635
1636 if (style.IsParagraphStyle())
1637 obj = GetParagraphAtPosition(position);
1638 else
1639 obj = GetLeafObjectAtPosition(position);
1640
1641 if (obj)
1642 {
1643 style = obj->GetAttributes();
1644 return true;
1645 }
1646 else
1647 return false;
1648 }
1649
1650 /// Get the text attributes for this position.
1651 bool wxRichTextParagraphLayoutBox::GetStyle(long position, wxRichTextAttr& style) const
1652 {
1653 wxRichTextObject* obj wxDUMMY_INITIALIZE(NULL);
1654
1655 if (style.IsParagraphStyle())
1656 obj = GetParagraphAtPosition(position);
1657 else
1658 obj = GetLeafObjectAtPosition(position);
1659
1660 if (obj)
1661 {
1662 style = obj->GetAttributes();
1663 return true;
1664 }
1665 else
1666 return false;
1667 }
1668
1669 /// Set default style
1670 bool wxRichTextParagraphLayoutBox::SetDefaultStyle(const wxTextAttrEx& style)
1671 {
1672 m_defaultAttributes = style;
1673
1674 return true;
1675 }
1676
1677 /// Test if this whole range has character attributes of the specified kind. If any
1678 /// of the attributes are different within the range, the test fails. You
1679 /// can use this to implement, for example, bold button updating. style must have
1680 /// flags indicating which attributes are of interest.
1681 bool wxRichTextParagraphLayoutBox::HasCharacterAttributes(const wxRichTextRange& range, const wxRichTextAttr& style) const
1682 {
1683 int foundCount = 0;
1684 int matchingCount = 0;
1685
1686 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
1687 while (node)
1688 {
1689 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
1690 wxASSERT (para != NULL);
1691
1692 if (para)
1693 {
1694 // Stop searching if we're beyond the range of interest
1695 if (para->GetRange().GetStart() > range.GetEnd())
1696 return foundCount == matchingCount;
1697
1698 if (!para->GetRange().IsOutside(range))
1699 {
1700 wxRichTextObjectList::compatibility_iterator node2 = para->GetChildren().GetFirst();
1701
1702 while (node2)
1703 {
1704 wxRichTextObject* child = node2->GetData();
1705 if (!child->GetRange().IsOutside(range) && child->IsKindOf(CLASSINFO(wxRichTextPlainText)))
1706 {
1707 foundCount ++;
1708 if (wxTextAttrEqPartial(child->GetAttributes(), style, style.GetFlags()))
1709 matchingCount ++;
1710 }
1711
1712 node2 = node2->GetNext();
1713 }
1714 }
1715 }
1716
1717 node = node->GetNext();
1718 }
1719
1720 return foundCount == matchingCount;
1721 }
1722
1723 bool wxRichTextParagraphLayoutBox::HasCharacterAttributes(const wxRichTextRange& range, const wxTextAttrEx& style) const
1724 {
1725 wxRichTextAttr richStyle = style;
1726 return HasCharacterAttributes(range, richStyle);
1727 }
1728
1729 /// Test if this whole range has paragraph attributes of the specified kind. If any
1730 /// of the attributes are different within the range, the test fails. You
1731 /// can use this to implement, for example, centering button updating. style must have
1732 /// flags indicating which attributes are of interest.
1733 bool wxRichTextParagraphLayoutBox::HasParagraphAttributes(const wxRichTextRange& range, const wxRichTextAttr& style) const
1734 {
1735 int foundCount = 0;
1736 int matchingCount = 0;
1737
1738 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
1739 while (node)
1740 {
1741 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
1742 wxASSERT (para != NULL);
1743
1744 if (para)
1745 {
1746 // Stop searching if we're beyond the range of interest
1747 if (para->GetRange().GetStart() > range.GetEnd())
1748 return foundCount == matchingCount;
1749
1750 if (!para->GetRange().IsOutside(range))
1751 {
1752 foundCount ++;
1753 if (wxTextAttrEqPartial(para->GetAttributes(), style, style.GetFlags()))
1754 matchingCount ++;
1755 }
1756 }
1757
1758 node = node->GetNext();
1759 }
1760 return foundCount == matchingCount;
1761 }
1762
1763 bool wxRichTextParagraphLayoutBox::HasParagraphAttributes(const wxRichTextRange& range, const wxTextAttrEx& style) const
1764 {
1765 wxRichTextAttr richStyle = style;
1766 return HasParagraphAttributes(range, richStyle);
1767 }
1768
1769 void wxRichTextParagraphLayoutBox::Clear()
1770 {
1771 DeleteChildren();
1772 }
1773
1774 void wxRichTextParagraphLayoutBox::Reset()
1775 {
1776 Clear();
1777
1778 AddParagraph(wxEmptyString);
1779 }
1780
1781 /// Invalidate the buffer. With no argument, invalidates whole buffer.
1782 void wxRichTextParagraphLayoutBox::Invalidate(const wxRichTextRange& invalidRange)
1783 {
1784 SetDirty(true);
1785
1786 if (invalidRange == wxRICHTEXT_ALL)
1787 {
1788 m_invalidRange = wxRICHTEXT_ALL;
1789 return;
1790 }
1791
1792 // Already invalidating everything
1793 if (m_invalidRange == wxRICHTEXT_ALL)
1794 return;
1795
1796 if ((invalidRange.GetStart() < m_invalidRange.GetStart()) || m_invalidRange.GetStart() == -1)
1797 m_invalidRange.SetStart(invalidRange.GetStart());
1798 if (invalidRange.GetEnd() > m_invalidRange.GetEnd())
1799 m_invalidRange.SetEnd(invalidRange.GetEnd());
1800 }
1801
1802 /// Get invalid range, rounding to entire paragraphs if argument is true.
1803 wxRichTextRange wxRichTextParagraphLayoutBox::GetInvalidRange(bool wholeParagraphs) const
1804 {
1805 if (m_invalidRange == wxRICHTEXT_ALL || m_invalidRange == wxRICHTEXT_NONE)
1806 return m_invalidRange;
1807
1808 wxRichTextRange range = m_invalidRange;
1809
1810 if (wholeParagraphs)
1811 {
1812 wxRichTextParagraph* para1 = GetParagraphAtPosition(range.GetStart());
1813 wxRichTextParagraph* para2 = GetParagraphAtPosition(range.GetEnd());
1814 if (para1)
1815 range.SetStart(para1->GetRange().GetStart());
1816 if (para2)
1817 range.SetEnd(para2->GetRange().GetEnd());
1818 }
1819 return range;
1820 }
1821
1822 /*!
1823 * wxRichTextFragment class declaration
1824 * This is a lind of paragraph layout box used for storing
1825 * paragraphs for Undo/Redo, for example.
1826 */
1827
1828 IMPLEMENT_DYNAMIC_CLASS(wxRichTextFragment, wxRichTextParagraphLayoutBox)
1829
1830 /// Initialise
1831 void wxRichTextFragment::Init()
1832 {
1833 m_partialParagraph = false;
1834 }
1835
1836 /// Copy
1837 void wxRichTextFragment::Copy(const wxRichTextFragment& obj)
1838 {
1839 wxRichTextParagraphLayoutBox::Copy(obj);
1840
1841 m_partialParagraph = obj.m_partialParagraph;
1842 }
1843
1844 /*!
1845 * wxRichTextParagraph
1846 * This object represents a single paragraph (or in a straight text editor, a line).
1847 */
1848
1849 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraph, wxRichTextBox)
1850
1851 wxRichTextParagraph::wxRichTextParagraph(wxRichTextObject* parent, wxTextAttrEx* style):
1852 wxRichTextBox(parent)
1853 {
1854 if (parent && !style)
1855 SetAttributes(parent->GetAttributes());
1856 if (style)
1857 SetAttributes(*style);
1858 }
1859
1860 wxRichTextParagraph::wxRichTextParagraph(const wxString& text, wxRichTextObject* parent, wxTextAttrEx* style):
1861 wxRichTextBox(parent)
1862 {
1863 if (parent && !style)
1864 SetAttributes(parent->GetAttributes());
1865 if (style)
1866 SetAttributes(*style);
1867
1868 AppendChild(new wxRichTextPlainText(text, this));
1869 }
1870
1871 wxRichTextParagraph::~wxRichTextParagraph()
1872 {
1873 ClearLines();
1874 }
1875
1876 /// Draw the item
1877 bool wxRichTextParagraph::Draw(wxDC& dc, const wxRichTextRange& WXUNUSED(range), const wxRichTextRange& selectionRange, const wxRect& WXUNUSED(rect), int WXUNUSED(descent), int style)
1878 {
1879 // Draw the bullet, if any
1880 if (GetAttributes().GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE)
1881 {
1882 if (GetAttributes().GetLeftSubIndent() != 0)
1883 {
1884 int spaceBeforePara = ConvertTenthsMMToPixels(dc, GetAttributes().GetParagraphSpacingBefore());
1885 // int spaceAfterPara = ConvertTenthsMMToPixels(dc, GetAttributes().GetParagraphSpacingAfter());
1886 int leftIndent = ConvertTenthsMMToPixels(dc, GetAttributes().GetLeftIndent());
1887 // int leftSubIndent = ConvertTenthsMMToPixels(dc, GetAttributes().GetLeftSubIndent());
1888 // int rightIndent = ConvertTenthsMMToPixels(dc, GetAttributes().GetRightIndent());
1889
1890 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP)
1891 {
1892 // TODO
1893 }
1894 else
1895 {
1896 wxString bulletText = GetBulletText();
1897 if (!bulletText.empty())
1898 {
1899 if (GetAttributes().GetFont().Ok())
1900 dc.SetFont(GetAttributes().GetFont());
1901
1902 if (GetAttributes().GetTextColour().Ok())
1903 dc.SetTextForeground(GetAttributes().GetTextColour());
1904
1905 dc.SetBackgroundMode(wxTRANSPARENT);
1906
1907 // Get line height from first line, if any
1908 wxRichTextLine* line = m_cachedLines.GetFirst() ? (wxRichTextLine* ) m_cachedLines.GetFirst()->GetData() : (wxRichTextLine*) NULL;
1909
1910 wxPoint linePos;
1911 int lineHeight wxDUMMY_INITIALIZE(0);
1912 if (line)
1913 {
1914 lineHeight = line->GetSize().y;
1915 linePos = line->GetPosition() + GetPosition();
1916 }
1917 else
1918 {
1919 lineHeight = dc.GetCharHeight();
1920 linePos = GetPosition();
1921 linePos.y += spaceBeforePara;
1922 }
1923
1924 int charHeight = dc.GetCharHeight();
1925
1926 int x = GetPosition().x + leftIndent;
1927 int y = linePos.y + (lineHeight - charHeight);
1928
1929 dc.DrawText(bulletText, x, y);
1930 }
1931 }
1932 }
1933 }
1934
1935 // Draw the range for each line, one object at a time.
1936
1937 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetFirst();
1938 while (node)
1939 {
1940 wxRichTextLine* line = node->GetData();
1941 wxRichTextRange lineRange = line->GetAbsoluteRange();
1942
1943 int maxDescent = line->GetDescent();
1944
1945 // Lines are specified relative to the paragraph
1946
1947 wxPoint linePosition = line->GetPosition() + GetPosition();
1948 wxPoint objectPosition = linePosition;
1949
1950 // Loop through objects until we get to the one within range
1951 wxRichTextObjectList::compatibility_iterator node2 = m_children.GetFirst();
1952 while (node2)
1953 {
1954 wxRichTextObject* child = node2->GetData();
1955 if (!child->GetRange().IsOutside(lineRange))
1956 {
1957 // Draw this part of the line at the correct position
1958 wxRichTextRange objectRange(child->GetRange());
1959 objectRange.LimitTo(lineRange);
1960
1961 wxSize objectSize;
1962 int descent = 0;
1963 child->GetRangeSize(objectRange, objectSize, descent, dc, wxRICHTEXT_UNFORMATTED);
1964
1965 // Use the child object's width, but the whole line's height
1966 wxRect childRect(objectPosition, wxSize(objectSize.x, line->GetSize().y));
1967 child->Draw(dc, objectRange, selectionRange, childRect, maxDescent, style);
1968
1969 objectPosition.x += objectSize.x;
1970 }
1971 else if (child->GetRange().GetStart() > lineRange.GetEnd())
1972 // Can break out of inner loop now since we've passed this line's range
1973 break;
1974
1975 node2 = node2->GetNext();
1976 }
1977
1978 node = node->GetNext();
1979 }
1980
1981 return true;
1982 }
1983
1984 /// Lay the item out
1985 bool wxRichTextParagraph::Layout(wxDC& dc, const wxRect& rect, int style)
1986 {
1987 // ClearLines();
1988
1989 // Increase the size of the paragraph due to spacing
1990 int spaceBeforePara = ConvertTenthsMMToPixels(dc, GetAttributes().GetParagraphSpacingBefore());
1991 int spaceAfterPara = ConvertTenthsMMToPixels(dc, GetAttributes().GetParagraphSpacingAfter());
1992 int leftIndent = ConvertTenthsMMToPixels(dc, GetAttributes().GetLeftIndent());
1993 int leftSubIndent = ConvertTenthsMMToPixels(dc, GetAttributes().GetLeftSubIndent());
1994 int rightIndent = ConvertTenthsMMToPixels(dc, GetAttributes().GetRightIndent());
1995
1996 int lineSpacing = 0;
1997
1998 // Let's assume line spacing of 10 is normal, 15 is 1.5, 20 is 2, etc.
1999 if (GetAttributes().GetLineSpacing() > 10 && GetAttributes().GetFont().Ok())
2000 {
2001 dc.SetFont(GetAttributes().GetFont());
2002 lineSpacing = (ConvertTenthsMMToPixels(dc, dc.GetCharHeight()) * GetAttributes().GetLineSpacing())/10;
2003 }
2004
2005 // Available space for text on each line differs.
2006 int availableTextSpaceFirstLine = rect.GetWidth() - leftIndent - rightIndent;
2007
2008 // Bullets start the text at the same position as subsequent lines
2009 if (GetAttributes().GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE)
2010 availableTextSpaceFirstLine -= leftSubIndent;
2011
2012 int availableTextSpaceSubsequentLines = rect.GetWidth() - leftIndent - rightIndent - leftSubIndent;
2013
2014 // Start position for each line relative to the paragraph
2015 int startPositionFirstLine = leftIndent;
2016 int startPositionSubsequentLines = leftIndent + leftSubIndent;
2017
2018 // If we have a bullet in this paragraph, the start position for the first line's text
2019 // is actually leftIndent + leftSubIndent.
2020 if (GetAttributes().GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE)
2021 startPositionFirstLine = startPositionSubsequentLines;
2022
2023 //bool restrictWidth = wxRichTextHasStyle(style, wxRICHTEXT_FIXED_WIDTH);
2024 //bool restrictHeight = wxRichTextHasStyle(style, wxRICHTEXT_FIXED_HEIGHT);
2025
2026 long lastEndPos = GetRange().GetStart()-1;
2027 long lastCompletedEndPos = lastEndPos;
2028
2029 int currentWidth = 0;
2030 SetPosition(rect.GetPosition());
2031
2032 wxPoint currentPosition(0, spaceBeforePara); // We will calculate lines relative to paragraph
2033 int lineHeight = 0;
2034 int maxWidth = 0;
2035 int maxDescent = 0;
2036
2037 int lineCount = 0;
2038
2039 // Split up lines
2040
2041 // We may need to go back to a previous child, in which case create the new line,
2042 // find the child corresponding to the start position of the string, and
2043 // continue.
2044
2045 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
2046 while (node)
2047 {
2048 wxRichTextObject* child = node->GetData();
2049
2050 // If this is e.g. a composite text box, it will need to be laid out itself.
2051 // But if just a text fragment or image, for example, this will
2052 // do nothing. NB: won't we need to set the position after layout?
2053 // since for example if position is dependent on vertical line size, we
2054 // can't tell the position until the size is determined. So possibly introduce
2055 // another layout phase.
2056
2057 child->Layout(dc, rect, style);
2058
2059 // Available width depends on whether we're on the first or subsequent lines
2060 int availableSpaceForText = (lineCount == 0 ? availableTextSpaceFirstLine : availableTextSpaceSubsequentLines);
2061
2062 currentPosition.x = (lineCount == 0 ? startPositionFirstLine : startPositionSubsequentLines);
2063
2064 // We may only be looking at part of a child, if we searched back for wrapping
2065 // and found a suitable point some way into the child. So get the size for the fragment
2066 // if necessary.
2067
2068 wxSize childSize;
2069 int childDescent = 0;
2070 if (lastEndPos == child->GetRange().GetStart() - 1)
2071 {
2072 childSize = child->GetCachedSize();
2073 childDescent = child->GetDescent();
2074 }
2075 else
2076 GetRangeSize(wxRichTextRange(lastEndPos+1, child->GetRange().GetEnd()), childSize, childDescent, dc, wxRICHTEXT_UNFORMATTED);
2077
2078 if (childSize.x + currentWidth > availableSpaceForText)
2079 {
2080 long wrapPosition = 0;
2081
2082 // Find a place to wrap. This may walk back to previous children,
2083 // for example if a word spans several objects.
2084 if (!FindWrapPosition(wxRichTextRange(lastCompletedEndPos+1, child->GetRange().GetEnd()), dc, availableSpaceForText, wrapPosition))
2085 {
2086 // If the function failed, just cut it off at the end of this child.
2087 wrapPosition = child->GetRange().GetEnd();
2088 }
2089
2090 // FindWrapPosition can still return a value that will put us in an endless wrapping loop
2091 if (wrapPosition <= lastCompletedEndPos)
2092 wrapPosition = wxMax(lastCompletedEndPos+1,child->GetRange().GetEnd());
2093
2094 // wxLogDebug(wxT("Split at %ld"), wrapPosition);
2095
2096 // Let's find the actual size of the current line now
2097 wxSize actualSize;
2098 wxRichTextRange actualRange(lastCompletedEndPos+1, wrapPosition);
2099 GetRangeSize(actualRange, actualSize, childDescent, dc, wxRICHTEXT_UNFORMATTED);
2100 currentWidth = actualSize.x;
2101 lineHeight = wxMax(lineHeight, actualSize.y);
2102 maxDescent = wxMax(childDescent, maxDescent);
2103
2104 // Add a new line
2105 wxRichTextLine* line = AllocateLine(lineCount);
2106
2107 // Set relative range so we won't have to change line ranges when paragraphs are moved
2108 line->SetRange(wxRichTextRange(actualRange.GetStart() - GetRange().GetStart(), actualRange.GetEnd() - GetRange().GetStart()));
2109 line->SetPosition(currentPosition);
2110 line->SetSize(wxSize(currentWidth, lineHeight));
2111 line->SetDescent(maxDescent);
2112
2113 // Now move down a line. TODO: add margins, spacing
2114 currentPosition.y += lineHeight;
2115 currentPosition.y += lineSpacing;
2116 currentWidth = 0;
2117 maxDescent = 0;
2118 maxWidth = wxMax(maxWidth, currentWidth);
2119
2120 lineCount ++;
2121
2122 // TODO: account for zero-length objects, such as fields
2123 wxASSERT(wrapPosition > lastCompletedEndPos);
2124
2125 lastEndPos = wrapPosition;
2126 lastCompletedEndPos = lastEndPos;
2127
2128 lineHeight = 0;
2129
2130 // May need to set the node back to a previous one, due to searching back in wrapping
2131 wxRichTextObject* childAfterWrapPosition = FindObjectAtPosition(wrapPosition+1);
2132 if (childAfterWrapPosition)
2133 node = m_children.Find(childAfterWrapPosition);
2134 else
2135 node = node->GetNext();
2136 }
2137 else
2138 {
2139 // We still fit, so don't add a line, and keep going
2140 currentWidth += childSize.x;
2141 lineHeight = wxMax(lineHeight, childSize.y);
2142 maxDescent = wxMax(childDescent, maxDescent);
2143
2144 maxWidth = wxMax(maxWidth, currentWidth);
2145 lastEndPos = child->GetRange().GetEnd();
2146
2147 node = node->GetNext();
2148 }
2149 }
2150
2151 // Add the last line - it's the current pos -> last para pos
2152 // Substract -1 because the last position is always the end-paragraph position.
2153 if (lastCompletedEndPos <= GetRange().GetEnd()-1)
2154 {
2155 currentPosition.x = (lineCount == 0 ? startPositionFirstLine : startPositionSubsequentLines);
2156
2157 wxRichTextLine* line = AllocateLine(lineCount);
2158
2159 wxRichTextRange actualRange(lastCompletedEndPos+1, GetRange().GetEnd()-1);
2160
2161 // Set relative range so we won't have to change line ranges when paragraphs are moved
2162 line->SetRange(wxRichTextRange(actualRange.GetStart() - GetRange().GetStart(), actualRange.GetEnd() - GetRange().GetStart()));
2163
2164 line->SetPosition(currentPosition);
2165
2166 if (lineHeight == 0)
2167 {
2168 if (GetAttributes().GetFont().Ok())
2169 dc.SetFont(GetAttributes().GetFont());
2170 lineHeight = dc.GetCharHeight();
2171 }
2172 if (maxDescent == 0)
2173 {
2174 int w, h;
2175 dc.GetTextExtent(wxT("X"), & w, &h, & maxDescent);
2176 }
2177
2178 line->SetSize(wxSize(currentWidth, lineHeight));
2179 line->SetDescent(maxDescent);
2180 currentPosition.y += lineHeight;
2181 currentPosition.y += lineSpacing;
2182 lineCount ++;
2183 }
2184
2185 // Remove remaining unused line objects, if any
2186 ClearUnusedLines(lineCount);
2187
2188 // Apply styles to wrapped lines
2189 ApplyParagraphStyle(rect);
2190
2191 SetCachedSize(wxSize(maxWidth, currentPosition.y + spaceBeforePara + spaceAfterPara));
2192
2193 m_dirty = false;
2194
2195 return true;
2196 }
2197
2198 /// Apply paragraph styles, such as centering, to wrapped lines
2199 void wxRichTextParagraph::ApplyParagraphStyle(const wxRect& rect)
2200 {
2201 if (!GetAttributes().HasAlignment())
2202 return;
2203
2204 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetFirst();
2205 while (node)
2206 {
2207 wxRichTextLine* line = node->GetData();
2208
2209 wxPoint pos = line->GetPosition();
2210 wxSize size = line->GetSize();
2211
2212 // centering, right-justification
2213 if (GetAttributes().HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_CENTRE)
2214 {
2215 pos.x = (rect.GetWidth() - size.x)/2 + pos.x;
2216 line->SetPosition(pos);
2217 }
2218 else if (GetAttributes().HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_RIGHT)
2219 {
2220 pos.x = rect.GetRight() - size.x;
2221 line->SetPosition(pos);
2222 }
2223
2224 node = node->GetNext();
2225 }
2226 }
2227
2228 /// Insert text at the given position
2229 bool wxRichTextParagraph::InsertText(long pos, const wxString& text)
2230 {
2231 wxRichTextObject* childToUse = NULL;
2232 wxRichTextObjectList::compatibility_iterator nodeToUse = wxRichTextObjectList::compatibility_iterator();
2233
2234 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
2235 while (node)
2236 {
2237 wxRichTextObject* child = node->GetData();
2238 if (child->GetRange().Contains(pos) && child->GetRange().GetLength() > 0)
2239 {
2240 childToUse = child;
2241 nodeToUse = node;
2242 break;
2243 }
2244
2245 node = node->GetNext();
2246 }
2247
2248 if (childToUse)
2249 {
2250 wxRichTextPlainText* textObject = wxDynamicCast(childToUse, wxRichTextPlainText);
2251 if (textObject)
2252 {
2253 int posInString = pos - textObject->GetRange().GetStart();
2254
2255 wxString newText = textObject->GetText().Mid(0, posInString) +
2256 text + textObject->GetText().Mid(posInString);
2257 textObject->SetText(newText);
2258
2259 int textLength = text.Length();
2260
2261 textObject->SetRange(wxRichTextRange(textObject->GetRange().GetStart(),
2262 textObject->GetRange().GetEnd() + textLength));
2263
2264 // Increment the end range of subsequent fragments in this paragraph.
2265 // We'll set the paragraph range itself at a higher level.
2266
2267 wxRichTextObjectList::compatibility_iterator node = nodeToUse->GetNext();
2268 while (node)
2269 {
2270 wxRichTextObject* child = node->GetData();
2271 child->SetRange(wxRichTextRange(textObject->GetRange().GetStart() + textLength,
2272 textObject->GetRange().GetEnd() + textLength));
2273
2274 node = node->GetNext();
2275 }
2276
2277 return true;
2278 }
2279 else
2280 {
2281 // TODO: if not a text object, insert at closest position, e.g. in front of it
2282 }
2283 }
2284 else
2285 {
2286 // Add at end.
2287 // Don't pass parent initially to suppress auto-setting of parent range.
2288 // We'll do that at a higher level.
2289 wxRichTextPlainText* textObject = new wxRichTextPlainText(text, this);
2290
2291 AppendChild(textObject);
2292 return true;
2293 }
2294
2295 return false;
2296 }
2297
2298 void wxRichTextParagraph::Copy(const wxRichTextParagraph& obj)
2299 {
2300 wxRichTextBox::Copy(obj);
2301 }
2302
2303 /// Clear the cached lines
2304 void wxRichTextParagraph::ClearLines()
2305 {
2306 WX_CLEAR_LIST(wxRichTextLineList, m_cachedLines);
2307 }
2308
2309 /// Get/set the object size for the given range. Returns false if the range
2310 /// is invalid for this object.
2311 bool wxRichTextParagraph::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, int flags) const
2312 {
2313 if (!range.IsWithin(GetRange()))
2314 return false;
2315
2316 if (flags & wxRICHTEXT_UNFORMATTED)
2317 {
2318 // Just use unformatted data, assume no line breaks
2319 // TODO: take into account line breaks
2320
2321 wxSize sz;
2322
2323 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
2324 while (node)
2325 {
2326 wxRichTextObject* child = node->GetData();
2327 if (!child->GetRange().IsOutside(range))
2328 {
2329 wxSize childSize;
2330
2331 wxRichTextRange rangeToUse = range;
2332 rangeToUse.LimitTo(child->GetRange());
2333 int childDescent = 0;
2334
2335 if (child->GetRangeSize(rangeToUse, childSize, childDescent, dc, flags))
2336 {
2337 sz.y = wxMax(sz.y, childSize.y);
2338 sz.x += childSize.x;
2339 descent = wxMax(descent, childDescent);
2340 }
2341 }
2342
2343 node = node->GetNext();
2344 }
2345 size = sz;
2346 }
2347 else
2348 {
2349 // Use formatted data, with line breaks
2350 wxSize sz;
2351
2352 // We're going to loop through each line, and then for each line,
2353 // call GetRangeSize for the fragment that comprises that line.
2354 // Only we have to do that multiple times within the line, because
2355 // the line may be broken into pieces. For now ignore line break commands
2356 // (so we can assume that getting the unformatted size for a fragment
2357 // within a line is the actual size)
2358
2359 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetFirst();
2360 while (node)
2361 {
2362 wxRichTextLine* line = node->GetData();
2363 wxRichTextRange lineRange = line->GetAbsoluteRange();
2364 if (!lineRange.IsOutside(range))
2365 {
2366 wxSize lineSize;
2367
2368 wxRichTextObjectList::compatibility_iterator node2 = m_children.GetFirst();
2369 while (node2)
2370 {
2371 wxRichTextObject* child = node2->GetData();
2372
2373 if (!child->GetRange().IsOutside(lineRange))
2374 {
2375 wxRichTextRange rangeToUse = lineRange;
2376 rangeToUse.LimitTo(child->GetRange());
2377
2378 wxSize childSize;
2379 int childDescent = 0;
2380 if (child->GetRangeSize(rangeToUse, childSize, childDescent, dc, flags))
2381 {
2382 lineSize.y = wxMax(lineSize.y, childSize.y);
2383 lineSize.x += childSize.x;
2384 }
2385 descent = wxMax(descent, childDescent);
2386 }
2387
2388 node2 = node2->GetNext();
2389 }
2390
2391 // Increase size by a line (TODO: paragraph spacing)
2392 sz.y += lineSize.y;
2393 sz.x = wxMax(sz.x, lineSize.x);
2394 }
2395 node = node->GetNext();
2396 }
2397 size = sz;
2398 }
2399 return true;
2400 }
2401
2402 /// Finds the absolute position and row height for the given character position
2403 bool wxRichTextParagraph::FindPosition(wxDC& dc, long index, wxPoint& pt, int* height, bool forceLineStart)
2404 {
2405 if (index == -1)
2406 {
2407 wxRichTextLine* line = ((wxRichTextParagraphLayoutBox*)GetParent())->GetLineAtPosition(0);
2408 if (line)
2409 *height = line->GetSize().y;
2410 else
2411 *height = dc.GetCharHeight();
2412
2413 // -1 means 'the start of the buffer'.
2414 pt = GetPosition();
2415 if (line)
2416 pt = pt + line->GetPosition();
2417
2418 *height = dc.GetCharHeight();
2419
2420 return true;
2421 }
2422
2423 // The final position in a paragraph is taken to mean the position
2424 // at the start of the next paragraph.
2425 if (index == GetRange().GetEnd())
2426 {
2427 wxRichTextParagraphLayoutBox* parent = wxDynamicCast(GetParent(), wxRichTextParagraphLayoutBox);
2428 wxASSERT( parent != NULL );
2429
2430 // Find the height at the next paragraph, if any
2431 wxRichTextLine* line = parent->GetLineAtPosition(index + 1);
2432 if (line)
2433 {
2434 *height = line->GetSize().y;
2435 pt = line->GetAbsolutePosition();
2436 }
2437 else
2438 {
2439 *height = dc.GetCharHeight();
2440 int indent = ConvertTenthsMMToPixels(dc, m_attributes.GetLeftIndent());
2441 pt = wxPoint(indent, GetCachedSize().y);
2442 }
2443
2444 return true;
2445 }
2446
2447 if (index < GetRange().GetStart() || index > GetRange().GetEnd())
2448 return false;
2449
2450 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetFirst();
2451 while (node)
2452 {
2453 wxRichTextLine* line = node->GetData();
2454 wxRichTextRange lineRange = line->GetAbsoluteRange();
2455 if (index >= lineRange.GetStart() && index <= lineRange.GetEnd())
2456 {
2457 // If this is the last point in the line, and we're forcing the
2458 // returned value to be the start of the next line, do the required
2459 // thing.
2460 if (index == lineRange.GetEnd() && forceLineStart)
2461 {
2462 if (node->GetNext())
2463 {
2464 wxRichTextLine* nextLine = node->GetNext()->GetData();
2465 *height = nextLine->GetSize().y;
2466 pt = nextLine->GetAbsolutePosition();
2467 return true;
2468 }
2469 }
2470
2471 pt.y = line->GetPosition().y + GetPosition().y;
2472
2473 wxRichTextRange r(lineRange.GetStart(), index);
2474 wxSize rangeSize;
2475 int descent = 0;
2476
2477 // We find the size of the line up to this point,
2478 // then we can add this size to the line start position and
2479 // paragraph start position to find the actual position.
2480
2481 if (GetRangeSize(r, rangeSize, descent, dc, wxRICHTEXT_UNFORMATTED))
2482 {
2483 pt.x = line->GetPosition().x + GetPosition().x + rangeSize.x;
2484 *height = line->GetSize().y;
2485
2486 return true;
2487 }
2488
2489 }
2490
2491 node = node->GetNext();
2492 }
2493
2494 return false;
2495 }
2496
2497 /// Hit-testing: returns a flag indicating hit test details, plus
2498 /// information about position
2499 int wxRichTextParagraph::HitTest(wxDC& dc, const wxPoint& pt, long& textPosition)
2500 {
2501 wxPoint paraPos = GetPosition();
2502
2503 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetFirst();
2504 while (node)
2505 {
2506 wxRichTextLine* line = node->GetData();
2507 wxPoint linePos = paraPos + line->GetPosition();
2508 wxSize lineSize = line->GetSize();
2509 wxRichTextRange lineRange = line->GetAbsoluteRange();
2510
2511 if (pt.y >= linePos.y && pt.y <= linePos.y + lineSize.y)
2512 {
2513 if (pt.x < linePos.x)
2514 {
2515 textPosition = lineRange.GetStart();
2516 return wxRICHTEXT_HITTEST_BEFORE;
2517 }
2518 else if (pt.x >= (linePos.x + lineSize.x))
2519 {
2520 textPosition = lineRange.GetEnd();
2521 return wxRICHTEXT_HITTEST_AFTER;
2522 }
2523 else
2524 {
2525 long i;
2526 int lastX = linePos.x;
2527 for (i = lineRange.GetStart(); i <= lineRange.GetEnd(); i++)
2528 {
2529 wxSize childSize;
2530 int descent = 0;
2531
2532 wxRichTextRange rangeToUse(lineRange.GetStart(), i);
2533
2534 GetRangeSize(rangeToUse, childSize, descent, dc, wxRICHTEXT_UNFORMATTED);
2535
2536 int nextX = childSize.x + linePos.x;
2537
2538 if (pt.x >= lastX && pt.x <= nextX)
2539 {
2540 textPosition = i;
2541
2542 // So now we know it's between i-1 and i.
2543 // Let's see if we can be more precise about
2544 // which side of the position it's on.
2545
2546 int midPoint = (nextX - lastX)/2 + lastX;
2547 if (pt.x >= midPoint)
2548 return wxRICHTEXT_HITTEST_AFTER;
2549 else
2550 return wxRICHTEXT_HITTEST_BEFORE;
2551 }
2552 else
2553 {
2554 lastX = nextX;
2555 }
2556 }
2557 }
2558 }
2559
2560 node = node->GetNext();
2561 }
2562
2563 return wxRICHTEXT_HITTEST_NONE;
2564 }
2565
2566 /// Split an object at this position if necessary, and return
2567 /// the previous object, or NULL if inserting at beginning.
2568 wxRichTextObject* wxRichTextParagraph::SplitAt(long pos, wxRichTextObject** previousObject)
2569 {
2570 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
2571 while (node)
2572 {
2573 wxRichTextObject* child = node->GetData();
2574
2575 if (pos == child->GetRange().GetStart())
2576 {
2577 if (previousObject)
2578 {
2579 if (node->GetPrevious())
2580 *previousObject = node->GetPrevious()->GetData();
2581 else
2582 *previousObject = NULL;
2583 }
2584
2585 return child;
2586 }
2587
2588 if (child->GetRange().Contains(pos))
2589 {
2590 // This should create a new object, transferring part of
2591 // the content to the old object and the rest to the new object.
2592 wxRichTextObject* newObject = child->DoSplit(pos);
2593
2594 // If we couldn't split this object, just insert in front of it.
2595 if (!newObject)
2596 {
2597 // Maybe this is an empty string, try the next one
2598 // return child;
2599 }
2600 else
2601 {
2602 // Insert the new object after 'child'
2603 if (node->GetNext())
2604 m_children.Insert(node->GetNext(), newObject);
2605 else
2606 m_children.Append(newObject);
2607 newObject->SetParent(this);
2608
2609 if (previousObject)
2610 *previousObject = child;
2611
2612 return newObject;
2613 }
2614 }
2615
2616 node = node->GetNext();
2617 }
2618 if (previousObject)
2619 *previousObject = NULL;
2620 return NULL;
2621 }
2622
2623 /// Move content to a list from obj on
2624 void wxRichTextParagraph::MoveToList(wxRichTextObject* obj, wxList& list)
2625 {
2626 wxRichTextObjectList::compatibility_iterator node = m_children.Find(obj);
2627 while (node)
2628 {
2629 wxRichTextObject* child = node->GetData();
2630 list.Append(child);
2631
2632 wxRichTextObjectList::compatibility_iterator oldNode = node;
2633
2634 node = node->GetNext();
2635
2636 m_children.DeleteNode(oldNode);
2637 }
2638 }
2639
2640 /// Add content back from list
2641 void wxRichTextParagraph::MoveFromList(wxList& list)
2642 {
2643 for (wxList::compatibility_iterator node = list.GetFirst(); node; node = node->GetNext())
2644 {
2645 AppendChild((wxRichTextObject*) node->GetData());
2646 }
2647 }
2648
2649 /// Calculate range
2650 void wxRichTextParagraph::CalculateRange(long start, long& end)
2651 {
2652 wxRichTextCompositeObject::CalculateRange(start, end);
2653
2654 // Add one for end of paragraph
2655 end ++;
2656
2657 m_range.SetRange(start, end);
2658 }
2659
2660 /// Find the object at the given position
2661 wxRichTextObject* wxRichTextParagraph::FindObjectAtPosition(long position)
2662 {
2663 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
2664 while (node)
2665 {
2666 wxRichTextObject* obj = node->GetData();
2667 if (obj->GetRange().Contains(position))
2668 return obj;
2669
2670 node = node->GetNext();
2671 }
2672 return NULL;
2673 }
2674
2675 /// Get the plain text searching from the start or end of the range.
2676 /// The resulting string may be shorter than the range given.
2677 bool wxRichTextParagraph::GetContiguousPlainText(wxString& text, const wxRichTextRange& range, bool fromStart)
2678 {
2679 text = wxEmptyString;
2680
2681 if (fromStart)
2682 {
2683 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
2684 while (node)
2685 {
2686 wxRichTextObject* obj = node->GetData();
2687 if (!obj->GetRange().IsOutside(range))
2688 {
2689 wxRichTextPlainText* textObj = wxDynamicCast(obj, wxRichTextPlainText);
2690 if (textObj)
2691 {
2692 text += textObj->GetTextForRange(range);
2693 }
2694 else
2695 return true;
2696 }
2697
2698 node = node->GetNext();
2699 }
2700 }
2701 else
2702 {
2703 wxRichTextObjectList::compatibility_iterator node = m_children.GetLast();
2704 while (node)
2705 {
2706 wxRichTextObject* obj = node->GetData();
2707 if (!obj->GetRange().IsOutside(range))
2708 {
2709 wxRichTextPlainText* textObj = wxDynamicCast(obj, wxRichTextPlainText);
2710 if (textObj)
2711 {
2712 text = textObj->GetTextForRange(range) + text;
2713 }
2714 else
2715 return true;
2716 }
2717
2718 node = node->GetPrevious();
2719 }
2720 }
2721
2722 return true;
2723 }
2724
2725 /// Find a suitable wrap position.
2726 bool wxRichTextParagraph::FindWrapPosition(const wxRichTextRange& range, wxDC& dc, int availableSpace, long& wrapPosition)
2727 {
2728 // Find the first position where the line exceeds the available space.
2729 wxSize sz;
2730 long i;
2731 long breakPosition = range.GetEnd();
2732 for (i = range.GetStart(); i <= range.GetEnd(); i++)
2733 {
2734 int descent = 0;
2735 GetRangeSize(wxRichTextRange(range.GetStart(), i), sz, descent, dc, wxRICHTEXT_UNFORMATTED);
2736
2737 if (sz.x > availableSpace)
2738 {
2739 breakPosition = i-1;
2740 break;
2741 }
2742 }
2743
2744 // Now we know the last position on the line.
2745 // Let's try to find a word break.
2746
2747 wxString plainText;
2748 if (GetContiguousPlainText(plainText, wxRichTextRange(range.GetStart(), breakPosition), false))
2749 {
2750 int spacePos = plainText.Find(wxT(' '), true);
2751 if (spacePos != wxNOT_FOUND)
2752 {
2753 int positionsFromEndOfString = plainText.Length() - spacePos - 1;
2754 breakPosition = breakPosition - positionsFromEndOfString;
2755 }
2756 }
2757
2758 wrapPosition = breakPosition;
2759
2760 return true;
2761 }
2762
2763 /// Get the bullet text for this paragraph.
2764 wxString wxRichTextParagraph::GetBulletText()
2765 {
2766 if (GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE ||
2767 (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP))
2768 return wxEmptyString;
2769
2770 int number = GetAttributes().GetBulletNumber();
2771
2772 wxString text;
2773 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ARABIC)
2774 {
2775 text.Printf(wxT("%d"), number);
2776 }
2777 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER)
2778 {
2779 // TODO: Unicode, and also check if number > 26
2780 text.Printf(wxT("%c"), (wxChar) (number+64));
2781 }
2782 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER)
2783 {
2784 // TODO: Unicode, and also check if number > 26
2785 text.Printf(wxT("%c"), (wxChar) (number+96));
2786 }
2787 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER)
2788 {
2789 // TODO: convert from number to roman numeral
2790 if (number == 1)
2791 text = wxT("I");
2792 else if (number == 2)
2793 text = wxT("II");
2794 else if (number == 3)
2795 text = wxT("III");
2796 else if (number == 4)
2797 text = wxT("IV");
2798 else
2799 text = wxT("TODO");
2800 }
2801 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER)
2802 {
2803 // TODO: convert from number to roman numeral
2804 if (number == 1)
2805 text = wxT("i");
2806 else if (number == 2)
2807 text = wxT("ii");
2808 else if (number == 3)
2809 text = wxT("iii");
2810 else if (number == 4)
2811 text = wxT("iv");
2812 else
2813 text = wxT("TODO");
2814 }
2815 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL)
2816 {
2817 text = GetAttributes().GetBulletSymbol();
2818 }
2819
2820 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PARENTHESES)
2821 {
2822 text = wxT("(") + text + wxT(")");
2823 }
2824 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PERIOD)
2825 {
2826 text += wxT(".");
2827 }
2828
2829 return text;
2830 }
2831
2832 /// Allocate or reuse a line object
2833 wxRichTextLine* wxRichTextParagraph::AllocateLine(int pos)
2834 {
2835 if (pos < (int) m_cachedLines.GetCount())
2836 {
2837 wxRichTextLine* line = m_cachedLines.Item(pos)->GetData();
2838 line->Init(this);
2839 return line;
2840 }
2841 else
2842 {
2843 wxRichTextLine* line = new wxRichTextLine(this);
2844 m_cachedLines.Append(line);
2845 return line;
2846 }
2847 }
2848
2849 /// Clear remaining unused line objects, if any
2850 bool wxRichTextParagraph::ClearUnusedLines(int lineCount)
2851 {
2852 int cachedLineCount = m_cachedLines.GetCount();
2853 if ((int) cachedLineCount > lineCount)
2854 {
2855 for (int i = 0; i < (int) (cachedLineCount - lineCount); i ++)
2856 {
2857 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetLast();
2858 wxRichTextLine* line = node->GetData();
2859 m_cachedLines.Erase(node);
2860 delete line;
2861 }
2862 }
2863 return true;
2864 }
2865
2866
2867 /*!
2868 * wxRichTextLine
2869 * This object represents a line in a paragraph, and stores
2870 * offsets from the start of the paragraph representing the
2871 * start and end positions of the line.
2872 */
2873
2874 wxRichTextLine::wxRichTextLine(wxRichTextParagraph* parent)
2875 {
2876 Init(parent);
2877 }
2878
2879 /// Initialisation
2880 void wxRichTextLine::Init(wxRichTextParagraph* parent)
2881 {
2882 m_parent = parent;
2883 m_range.SetRange(-1, -1);
2884 m_pos = wxPoint(0, 0);
2885 m_size = wxSize(0, 0);
2886 m_descent = 0;
2887 }
2888
2889 /// Copy
2890 void wxRichTextLine::Copy(const wxRichTextLine& obj)
2891 {
2892 m_range = obj.m_range;
2893 }
2894
2895 /// Get the absolute object position
2896 wxPoint wxRichTextLine::GetAbsolutePosition() const
2897 {
2898 return m_parent->GetPosition() + m_pos;
2899 }
2900
2901 /// Get the absolute range
2902 wxRichTextRange wxRichTextLine::GetAbsoluteRange() const
2903 {
2904 wxRichTextRange range(m_range.GetStart() + m_parent->GetRange().GetStart(), 0);
2905 range.SetEnd(range.GetStart() + m_range.GetLength()-1);
2906 return range;
2907 }
2908
2909 /*!
2910 * wxRichTextPlainText
2911 * This object represents a single piece of text.
2912 */
2913
2914 IMPLEMENT_DYNAMIC_CLASS(wxRichTextPlainText, wxRichTextObject)
2915
2916 wxRichTextPlainText::wxRichTextPlainText(const wxString& text, wxRichTextObject* parent, wxTextAttrEx* style):
2917 wxRichTextObject(parent)
2918 {
2919 if (parent && !style)
2920 SetAttributes(parent->GetAttributes());
2921 if (style)
2922 SetAttributes(*style);
2923
2924 m_text = text;
2925 }
2926
2927 /// Draw the item
2928 bool wxRichTextPlainText::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextRange& selectionRange, const wxRect& rect, int descent, int WXUNUSED(style))
2929 {
2930 int offset = GetRange().GetStart();
2931
2932 long len = range.GetLength();
2933 wxString stringChunk = m_text.Mid(range.GetStart() - offset, (size_t) len);
2934
2935 int charHeight = dc.GetCharHeight();
2936
2937 int x = rect.x;
2938 int y = rect.y + (rect.height - charHeight - (descent - m_descent));
2939
2940 // Test for the optimized situations where all is selected, or none
2941 // is selected.
2942
2943 if (GetAttributes().GetFont().Ok())
2944 dc.SetFont(GetAttributes().GetFont());
2945
2946 // (a) All selected.
2947 if (selectionRange.GetStart() <= range.GetStart() && selectionRange.GetEnd() >= range.GetEnd())
2948 {
2949 // Draw all selected
2950 dc.SetBrush(*wxBLACK_BRUSH);
2951 dc.SetPen(*wxBLACK_PEN);
2952 wxCoord w, h;
2953 dc.GetTextExtent(stringChunk, & w, & h);
2954 wxRect selRect(x, rect.y, w, rect.GetHeight());
2955 dc.DrawRectangle(selRect);
2956 dc.SetTextForeground(*wxWHITE);
2957 dc.SetBackgroundMode(wxTRANSPARENT);
2958 dc.DrawText(stringChunk, x, y);
2959 }
2960 // (b) None selected.
2961 else if (selectionRange.GetEnd() < range.GetStart() || selectionRange.GetStart() > range.GetEnd())
2962 {
2963 // Draw all unselected
2964 dc.SetTextForeground(GetAttributes().GetTextColour());
2965 dc.SetBackgroundMode(wxTRANSPARENT);
2966 dc.DrawText(stringChunk, x, y);
2967 }
2968 else
2969 {
2970 // (c) Part selected, part not
2971 // Let's draw unselected chunk, selected chunk, then unselected chunk.
2972
2973 dc.SetBackgroundMode(wxTRANSPARENT);
2974
2975 // 1. Initial unselected chunk, if any, up until start of selection.
2976 if (selectionRange.GetStart() > range.GetStart() && selectionRange.GetStart() <= range.GetEnd())
2977 {
2978 int r1 = range.GetStart();
2979 int s1 = selectionRange.GetStart()-1;
2980 int fragmentLen = s1 - r1 + 1;
2981 if (fragmentLen < 0)
2982 wxLogDebug(wxT("Mid(%d, %d"), (int)(r1 - offset), (int)fragmentLen);
2983 wxString stringFragment = m_text.Mid(r1 - offset, fragmentLen);
2984
2985 dc.SetTextForeground(GetAttributes().GetTextColour());
2986 dc.DrawText(stringFragment, x, y);
2987
2988 wxCoord w, h;
2989 dc.GetTextExtent(stringFragment, & w, & h);
2990 x += w;
2991 }
2992
2993 // 2. Selected chunk, if any.
2994 if (selectionRange.GetEnd() >= range.GetStart())
2995 {
2996 int s1 = wxMax(selectionRange.GetStart(), range.GetStart());
2997 int s2 = wxMin(selectionRange.GetEnd(), range.GetEnd());
2998
2999 int fragmentLen = s2 - s1 + 1;
3000 if (fragmentLen < 0)
3001 wxLogDebug(wxT("Mid(%d, %d"), (int)(s1 - offset), (int)fragmentLen);
3002 wxString stringFragment = m_text.Mid(s1 - offset, fragmentLen);
3003
3004 wxCoord w, h;
3005 dc.GetTextExtent(stringFragment, & w, & h);
3006 wxRect selRect(x, rect.y, w, rect.GetHeight());
3007
3008 dc.SetBrush(*wxBLACK_BRUSH);
3009 dc.SetPen(*wxBLACK_PEN);
3010 dc.DrawRectangle(selRect);
3011 dc.SetTextForeground(*wxWHITE);
3012 dc.DrawText(stringFragment, x, y);
3013
3014 x += w;
3015 }
3016
3017 // 3. Remaining unselected chunk, if any
3018 if (selectionRange.GetEnd() < range.GetEnd())
3019 {
3020 int s2 = wxMin(selectionRange.GetEnd()+1, range.GetEnd());
3021 int r2 = range.GetEnd();
3022
3023 int fragmentLen = r2 - s2 + 1;
3024 if (fragmentLen < 0)
3025 wxLogDebug(wxT("Mid(%d, %d"), (int)(s2 - offset), (int)fragmentLen);
3026 wxString stringFragment = m_text.Mid(s2 - offset, fragmentLen);
3027
3028 dc.SetTextForeground(GetAttributes().GetTextColour());
3029 dc.DrawText(stringFragment, x, y);
3030 }
3031 }
3032
3033 return true;
3034 }
3035
3036 /// Lay the item out
3037 bool wxRichTextPlainText::Layout(wxDC& dc, const wxRect& WXUNUSED(rect), int WXUNUSED(style))
3038 {
3039 if (GetAttributes().GetFont().Ok())
3040 dc.SetFont(GetAttributes().GetFont());
3041
3042 wxCoord w, h;
3043 dc.GetTextExtent(m_text, & w, & h, & m_descent);
3044 m_size = wxSize(w, dc.GetCharHeight());
3045
3046 return true;
3047 }
3048
3049 /// Copy
3050 void wxRichTextPlainText::Copy(const wxRichTextPlainText& obj)
3051 {
3052 wxRichTextObject::Copy(obj);
3053
3054 m_text = obj.m_text;
3055 }
3056
3057 /// Get/set the object size for the given range. Returns false if the range
3058 /// is invalid for this object.
3059 bool wxRichTextPlainText::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, int WXUNUSED(flags)) const
3060 {
3061 if (!range.IsWithin(GetRange()))
3062 return false;
3063
3064 // Always assume unformatted text, since at this level we have no knowledge
3065 // of line breaks - and we don't need it, since we'll calculate size within
3066 // formatted text by doing it in chunks according to the line ranges
3067
3068 if (GetAttributes().GetFont().Ok())
3069 dc.SetFont(GetAttributes().GetFont());
3070
3071 int startPos = range.GetStart() - GetRange().GetStart();
3072 long len = range.GetLength();
3073 wxString stringChunk = m_text.Mid(startPos, (size_t) len);
3074 wxCoord w, h;
3075 dc.GetTextExtent(stringChunk, & w, & h, & descent);
3076 size = wxSize(w, dc.GetCharHeight());
3077
3078 return true;
3079 }
3080
3081 /// Do a split, returning an object containing the second part, and setting
3082 /// the first part in 'this'.
3083 wxRichTextObject* wxRichTextPlainText::DoSplit(long pos)
3084 {
3085 int index = pos - GetRange().GetStart();
3086 if (index < 0 || index >= (int) m_text.Length())
3087 return NULL;
3088
3089 wxString firstPart = m_text.Mid(0, index);
3090 wxString secondPart = m_text.Mid(index);
3091
3092 m_text = firstPart;
3093
3094 wxRichTextPlainText* newObject = new wxRichTextPlainText(secondPart);
3095 newObject->SetAttributes(GetAttributes());
3096
3097 newObject->SetRange(wxRichTextRange(pos, GetRange().GetEnd()));
3098 GetRange().SetEnd(pos-1);
3099
3100 return newObject;
3101 }
3102
3103 /// Calculate range
3104 void wxRichTextPlainText::CalculateRange(long start, long& end)
3105 {
3106 end = start + m_text.Length() - 1;
3107 m_range.SetRange(start, end);
3108 }
3109
3110 /// Delete range
3111 bool wxRichTextPlainText::DeleteRange(const wxRichTextRange& range)
3112 {
3113 wxRichTextRange r = range;
3114
3115 r.LimitTo(GetRange());
3116
3117 if (r.GetStart() == GetRange().GetStart() && r.GetEnd() == GetRange().GetEnd())
3118 {
3119 m_text.Empty();
3120 return true;
3121 }
3122
3123 long startIndex = r.GetStart() - GetRange().GetStart();
3124 long len = r.GetLength();
3125
3126 m_text = m_text.Mid(0, startIndex) + m_text.Mid(startIndex+len);
3127 return true;
3128 }
3129
3130 /// Get text for the given range.
3131 wxString wxRichTextPlainText::GetTextForRange(const wxRichTextRange& range) const
3132 {
3133 wxRichTextRange r = range;
3134
3135 r.LimitTo(GetRange());
3136
3137 long startIndex = r.GetStart() - GetRange().GetStart();
3138 long len = r.GetLength();
3139
3140 return m_text.Mid(startIndex, len);
3141 }
3142
3143 /// Returns true if this object can merge itself with the given one.
3144 bool wxRichTextPlainText::CanMerge(wxRichTextObject* object) const
3145 {
3146 return object->GetClassInfo() == CLASSINFO(wxRichTextPlainText) &&
3147 (m_text.empty() || wxTextAttrEq(GetAttributes(), object->GetAttributes()));
3148 }
3149
3150 /// Returns true if this object merged itself with the given one.
3151 /// The calling code will then delete the given object.
3152 bool wxRichTextPlainText::Merge(wxRichTextObject* object)
3153 {
3154 wxRichTextPlainText* textObject = wxDynamicCast(object, wxRichTextPlainText);
3155 wxASSERT( textObject != NULL );
3156
3157 if (textObject)
3158 {
3159 m_text += textObject->GetText();
3160 return true;
3161 }
3162 else
3163 return false;
3164 }
3165
3166 /// Dump to output stream for debugging
3167 void wxRichTextPlainText::Dump(wxTextOutputStream& stream)
3168 {
3169 wxRichTextObject::Dump(stream);
3170 stream << m_text << wxT("\n");
3171 }
3172
3173 /*!
3174 * wxRichTextBuffer
3175 * This is a kind of box, used to represent the whole buffer
3176 */
3177
3178 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBuffer, wxRichTextParagraphLayoutBox)
3179
3180 wxList wxRichTextBuffer::sm_handlers;
3181
3182 /// Initialisation
3183 void wxRichTextBuffer::Init()
3184 {
3185 m_commandProcessor = new wxCommandProcessor;
3186 m_styleSheet = NULL;
3187 m_modified = false;
3188 m_batchedCommandDepth = 0;
3189 m_batchedCommand = NULL;
3190 m_suppressUndo = 0;
3191 }
3192
3193 /// Initialisation
3194 wxRichTextBuffer::~wxRichTextBuffer()
3195 {
3196 delete m_commandProcessor;
3197 delete m_batchedCommand;
3198
3199 ClearStyleStack();
3200 }
3201
3202 void wxRichTextBuffer::Clear()
3203 {
3204 DeleteChildren();
3205 GetCommandProcessor()->ClearCommands();
3206 Modify(false);
3207 Invalidate(wxRICHTEXT_ALL);
3208 }
3209
3210 void wxRichTextBuffer::Reset()
3211 {
3212 DeleteChildren();
3213 AddParagraph(wxEmptyString);
3214 GetCommandProcessor()->ClearCommands();
3215 Modify(false);
3216 Invalidate(wxRICHTEXT_ALL);
3217 }
3218
3219 /// Submit command to insert the given text
3220 bool wxRichTextBuffer::InsertTextWithUndo(long pos, const wxString& text, wxRichTextCtrl* ctrl)
3221 {
3222 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Text"), wxRICHTEXT_INSERT, this, ctrl, false);
3223
3224 action->GetNewParagraphs().AddParagraphs(text);
3225 if (action->GetNewParagraphs().GetChildCount() == 1)
3226 action->GetNewParagraphs().SetPartialParagraph(true);
3227
3228 action->SetPosition(pos);
3229
3230 // Set the range we'll need to delete in Undo
3231 action->SetRange(wxRichTextRange(pos, pos + text.Length() - 1));
3232
3233 SubmitAction(action);
3234
3235 return true;
3236 }
3237
3238 /// Submit command to insert the given text
3239 bool wxRichTextBuffer::InsertNewlineWithUndo(long pos, wxRichTextCtrl* ctrl)
3240 {
3241 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Text"), wxRICHTEXT_INSERT, this, ctrl, false);
3242
3243 wxTextAttrEx attr(GetBasicStyle());
3244 wxRichTextApplyStyle(attr, GetDefaultStyle());
3245
3246 wxRichTextParagraph* newPara = new wxRichTextParagraph(wxEmptyString, this, & attr);
3247 action->GetNewParagraphs().AppendChild(newPara);
3248 action->GetNewParagraphs().UpdateRanges();
3249 action->GetNewParagraphs().SetPartialParagraph(false);
3250 action->SetPosition(pos);
3251
3252 // Set the range we'll need to delete in Undo
3253 action->SetRange(wxRichTextRange(pos, pos));
3254
3255 SubmitAction(action);
3256
3257 return true;
3258 }
3259
3260 /// Submit command to insert the given image
3261 bool wxRichTextBuffer::InsertImageWithUndo(long pos, const wxRichTextImageBlock& imageBlock, wxRichTextCtrl* ctrl)
3262 {
3263 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Image"), wxRICHTEXT_INSERT, this, ctrl, false);
3264
3265 wxTextAttrEx attr(GetBasicStyle());
3266 wxRichTextApplyStyle(attr, GetDefaultStyle());
3267
3268 wxRichTextParagraph* newPara = new wxRichTextParagraph(this, & attr);
3269 wxRichTextImage* imageObject = new wxRichTextImage(imageBlock, newPara);
3270 newPara->AppendChild(imageObject);
3271 action->GetNewParagraphs().AppendChild(newPara);
3272 action->GetNewParagraphs().UpdateRanges();
3273
3274 action->GetNewParagraphs().SetPartialParagraph(true);
3275
3276 action->SetPosition(pos);
3277
3278 // Set the range we'll need to delete in Undo
3279 action->SetRange(wxRichTextRange(pos, pos));
3280
3281 SubmitAction(action);
3282
3283 return true;
3284 }
3285
3286 /// Submit command to delete this range
3287 bool wxRichTextBuffer::DeleteRangeWithUndo(const wxRichTextRange& range, long initialCaretPosition, long WXUNUSED(newCaretPositon), wxRichTextCtrl* ctrl)
3288 {
3289 wxRichTextAction* action = new wxRichTextAction(NULL, _("Delete"), wxRICHTEXT_DELETE, this, ctrl);
3290
3291 action->SetPosition(initialCaretPosition);
3292
3293 // Set the range to delete
3294 action->SetRange(range);
3295
3296 // Copy the fragment that we'll need to restore in Undo
3297 CopyFragment(range, action->GetOldParagraphs());
3298
3299 // Special case: if there is only one (non-partial) paragraph,
3300 // we must save the *next* paragraph's style, because that
3301 // is the style we must apply when inserting the content back
3302 // when undoing the delete. (This is because we're merging the
3303 // paragraph with the previous paragraph and throwing away
3304 // the style, and we need to restore it.)
3305 if (!action->GetOldParagraphs().GetPartialParagraph() && action->GetOldParagraphs().GetChildCount() == 1)
3306 {
3307 wxRichTextParagraph* lastPara = GetParagraphAtPosition(range.GetStart());
3308 if (lastPara)
3309 {
3310 wxRichTextParagraph* nextPara = GetParagraphAtPosition(range.GetEnd()+1);
3311 if (nextPara)
3312 {
3313 wxRichTextParagraph* para = (wxRichTextParagraph*) action->GetOldParagraphs().GetChild(0);
3314 para->SetAttributes(nextPara->GetAttributes());
3315 }
3316 }
3317 }
3318
3319 SubmitAction(action);
3320
3321 return true;
3322 }
3323
3324 /// Collapse undo/redo commands
3325 bool wxRichTextBuffer::BeginBatchUndo(const wxString& cmdName)
3326 {
3327 if (m_batchedCommandDepth == 0)
3328 {
3329 wxASSERT(m_batchedCommand == NULL);
3330 if (m_batchedCommand)
3331 {
3332 GetCommandProcessor()->Submit(m_batchedCommand);
3333 }
3334 m_batchedCommand = new wxRichTextCommand(cmdName);
3335 }
3336
3337 m_batchedCommandDepth ++;
3338
3339 return true;
3340 }
3341
3342 /// Collapse undo/redo commands
3343 bool wxRichTextBuffer::EndBatchUndo()
3344 {
3345 m_batchedCommandDepth --;
3346
3347 wxASSERT(m_batchedCommandDepth >= 0);
3348 wxASSERT(m_batchedCommand != NULL);
3349
3350 if (m_batchedCommandDepth == 0)
3351 {
3352 GetCommandProcessor()->Submit(m_batchedCommand);
3353 m_batchedCommand = NULL;
3354 }
3355
3356 return true;
3357 }
3358
3359 /// Submit immediately, or delay according to whether collapsing is on
3360 bool wxRichTextBuffer::SubmitAction(wxRichTextAction* action)
3361 {
3362 if (BatchingUndo() && m_batchedCommand && !SuppressingUndo())
3363 m_batchedCommand->AddAction(action);
3364 else
3365 {
3366 wxRichTextCommand* cmd = new wxRichTextCommand(action->GetName());
3367 cmd->AddAction(action);
3368
3369 // Only store it if we're not suppressing undo.
3370 return GetCommandProcessor()->Submit(cmd, !SuppressingUndo());
3371 }
3372
3373 return true;
3374 }
3375
3376 /// Begin suppressing undo/redo commands.
3377 bool wxRichTextBuffer::BeginSuppressUndo()
3378 {
3379 m_suppressUndo ++;
3380
3381 return true;
3382 }
3383
3384 /// End suppressing undo/redo commands.
3385 bool wxRichTextBuffer::EndSuppressUndo()
3386 {
3387 m_suppressUndo --;
3388
3389 return true;
3390 }
3391
3392 /// Begin using a style
3393 bool wxRichTextBuffer::BeginStyle(const wxTextAttrEx& style)
3394 {
3395 wxTextAttrEx newStyle(GetDefaultStyle());
3396
3397 // Save the old default style
3398 m_attributeStack.Append((wxObject*) new wxTextAttrEx(GetDefaultStyle()));
3399
3400 wxRichTextApplyStyle(newStyle, style);
3401 newStyle.SetFlags(style.GetFlags()|newStyle.GetFlags());
3402
3403 SetDefaultStyle(newStyle);
3404
3405 // wxLogDebug("Default style size = %d", GetDefaultStyle().GetFont().GetPointSize());
3406
3407 return true;
3408 }
3409
3410 /// End the style
3411 bool wxRichTextBuffer::EndStyle()
3412 {
3413 if (m_attributeStack.GetFirst() == NULL)
3414 {
3415 wxLogDebug(_("Too many EndStyle calls!"));
3416 return false;
3417 }
3418
3419 wxList::compatibility_iterator node = m_attributeStack.GetLast();
3420 wxTextAttrEx* attr = (wxTextAttrEx*)node->GetData();
3421 m_attributeStack.Erase(node);
3422
3423 SetDefaultStyle(*attr);
3424
3425 delete attr;
3426 return true;
3427 }
3428
3429 /// End all styles
3430 bool wxRichTextBuffer::EndAllStyles()
3431 {
3432 while (m_attributeStack.GetCount() != 0)
3433 EndStyle();
3434 return true;
3435 }
3436
3437 /// Clear the style stack
3438 void wxRichTextBuffer::ClearStyleStack()
3439 {
3440 for (wxList::compatibility_iterator node = m_attributeStack.GetFirst(); node; node = node->GetNext())
3441 delete (wxTextAttrEx*) node->GetData();
3442 m_attributeStack.Clear();
3443 }
3444
3445 /// Begin using bold
3446 bool wxRichTextBuffer::BeginBold()
3447 {
3448 wxFont font(GetBasicStyle().GetFont());
3449 font.SetWeight(wxBOLD);
3450
3451 wxTextAttrEx attr;
3452 attr.SetFont(font,wxTEXT_ATTR_FONT_WEIGHT);
3453
3454 return BeginStyle(attr);
3455 }
3456
3457 /// Begin using italic
3458 bool wxRichTextBuffer::BeginItalic()
3459 {
3460 wxFont font(GetBasicStyle().GetFont());
3461 font.SetStyle(wxITALIC);
3462
3463 wxTextAttrEx attr;
3464 attr.SetFont(font, wxTEXT_ATTR_FONT_ITALIC);
3465
3466 return BeginStyle(attr);
3467 }
3468
3469 /// Begin using underline
3470 bool wxRichTextBuffer::BeginUnderline()
3471 {
3472 wxFont font(GetBasicStyle().GetFont());
3473 font.SetUnderlined(true);
3474
3475 wxTextAttrEx attr;
3476 attr.SetFont(font, wxTEXT_ATTR_FONT_UNDERLINE);
3477
3478 return BeginStyle(attr);
3479 }
3480
3481 /// Begin using point size
3482 bool wxRichTextBuffer::BeginFontSize(int pointSize)
3483 {
3484 wxFont font(GetBasicStyle().GetFont());
3485 font.SetPointSize(pointSize);
3486
3487 wxTextAttrEx attr;
3488 attr.SetFont(font, wxTEXT_ATTR_FONT_SIZE);
3489
3490 return BeginStyle(attr);
3491 }
3492
3493 /// Begin using this font
3494 bool wxRichTextBuffer::BeginFont(const wxFont& font)
3495 {
3496 wxTextAttrEx attr;
3497 attr.SetFlags(wxTEXT_ATTR_FONT);
3498 attr.SetFont(font);
3499
3500 return BeginStyle(attr);
3501 }
3502
3503 /// Begin using this colour
3504 bool wxRichTextBuffer::BeginTextColour(const wxColour& colour)
3505 {
3506 wxTextAttrEx attr;
3507 attr.SetFlags(wxTEXT_ATTR_TEXT_COLOUR);
3508 attr.SetTextColour(colour);
3509
3510 return BeginStyle(attr);
3511 }
3512
3513 /// Begin using alignment
3514 bool wxRichTextBuffer::BeginAlignment(wxTextAttrAlignment alignment)
3515 {
3516 wxTextAttrEx attr;
3517 attr.SetFlags(wxTEXT_ATTR_ALIGNMENT);
3518 attr.SetAlignment(alignment);
3519
3520 return BeginStyle(attr);
3521 }
3522
3523 /// Begin left indent
3524 bool wxRichTextBuffer::BeginLeftIndent(int leftIndent, int leftSubIndent)
3525 {
3526 wxTextAttrEx attr;
3527 attr.SetFlags(wxTEXT_ATTR_LEFT_INDENT);
3528 attr.SetLeftIndent(leftIndent, leftSubIndent);
3529
3530 return BeginStyle(attr);
3531 }
3532
3533 /// Begin right indent
3534 bool wxRichTextBuffer::BeginRightIndent(int rightIndent)
3535 {
3536 wxTextAttrEx attr;
3537 attr.SetFlags(wxTEXT_ATTR_RIGHT_INDENT);
3538 attr.SetRightIndent(rightIndent);
3539
3540 return BeginStyle(attr);
3541 }
3542
3543 /// Begin paragraph spacing
3544 bool wxRichTextBuffer::BeginParagraphSpacing(int before, int after)
3545 {
3546 long flags = 0;
3547 if (before != 0)
3548 flags |= wxTEXT_ATTR_PARA_SPACING_BEFORE;
3549 if (after != 0)
3550 flags |= wxTEXT_ATTR_PARA_SPACING_AFTER;
3551
3552 wxTextAttrEx attr;
3553 attr.SetFlags(flags);
3554 attr.SetParagraphSpacingBefore(before);
3555 attr.SetParagraphSpacingAfter(after);
3556
3557 return BeginStyle(attr);
3558 }
3559
3560 /// Begin line spacing
3561 bool wxRichTextBuffer::BeginLineSpacing(int lineSpacing)
3562 {
3563 wxTextAttrEx attr;
3564 attr.SetFlags(wxTEXT_ATTR_LINE_SPACING);
3565 attr.SetLineSpacing(lineSpacing);
3566
3567 return BeginStyle(attr);
3568 }
3569
3570 /// Begin numbered bullet
3571 bool wxRichTextBuffer::BeginNumberedBullet(int bulletNumber, int leftIndent, int leftSubIndent, int bulletStyle)
3572 {
3573 wxTextAttrEx attr;
3574 attr.SetFlags(wxTEXT_ATTR_BULLET_STYLE|wxTEXT_ATTR_BULLET_NUMBER|wxTEXT_ATTR_LEFT_INDENT);
3575 attr.SetBulletStyle(bulletStyle);
3576 attr.SetBulletNumber(bulletNumber);
3577 attr.SetLeftIndent(leftIndent, leftSubIndent);
3578
3579 return BeginStyle(attr);
3580 }
3581
3582 /// Begin symbol bullet
3583 bool wxRichTextBuffer::BeginSymbolBullet(wxChar symbol, int leftIndent, int leftSubIndent, int bulletStyle)
3584 {
3585 wxTextAttrEx attr;
3586 attr.SetFlags(wxTEXT_ATTR_BULLET_STYLE|wxTEXT_ATTR_BULLET_SYMBOL|wxTEXT_ATTR_LEFT_INDENT);
3587 attr.SetBulletStyle(bulletStyle);
3588 attr.SetLeftIndent(leftIndent, leftSubIndent);
3589 attr.SetBulletSymbol(symbol);
3590
3591 return BeginStyle(attr);
3592 }
3593
3594 /// Begin named character style
3595 bool wxRichTextBuffer::BeginCharacterStyle(const wxString& characterStyle)
3596 {
3597 if (GetStyleSheet())
3598 {
3599 wxRichTextCharacterStyleDefinition* def = GetStyleSheet()->FindCharacterStyle(characterStyle);
3600 if (def)
3601 {
3602 wxTextAttrEx attr;
3603 def->GetStyle().CopyTo(attr);
3604 return BeginStyle(attr);
3605 }
3606 }
3607 return false;
3608 }
3609
3610 /// Begin named paragraph style
3611 bool wxRichTextBuffer::BeginParagraphStyle(const wxString& paragraphStyle)
3612 {
3613 if (GetStyleSheet())
3614 {
3615 wxRichTextParagraphStyleDefinition* def = GetStyleSheet()->FindParagraphStyle(paragraphStyle);
3616 if (def)
3617 {
3618 wxTextAttrEx attr;
3619 def->GetStyle().CopyTo(attr);
3620 return BeginStyle(attr);
3621 }
3622 }
3623 return false;
3624 }
3625
3626 /// Adds a handler to the end
3627 void wxRichTextBuffer::AddHandler(wxRichTextFileHandler *handler)
3628 {
3629 sm_handlers.Append(handler);
3630 }
3631
3632 /// Inserts a handler at the front
3633 void wxRichTextBuffer::InsertHandler(wxRichTextFileHandler *handler)
3634 {
3635 sm_handlers.Insert( handler );
3636 }
3637
3638 /// Removes a handler
3639 bool wxRichTextBuffer::RemoveHandler(const wxString& name)
3640 {
3641 wxRichTextFileHandler *handler = FindHandler(name);
3642 if (handler)
3643 {
3644 sm_handlers.DeleteObject(handler);
3645 delete handler;
3646 return true;
3647 }
3648 else
3649 return false;
3650 }
3651
3652 /// Finds a handler by filename or, if supplied, type
3653 wxRichTextFileHandler *wxRichTextBuffer::FindHandlerFilenameOrType(const wxString& filename, int imageType)
3654 {
3655 if (imageType != wxRICHTEXT_TYPE_ANY)
3656 return FindHandler(imageType);
3657 else
3658 {
3659 wxString path, file, ext;
3660 wxSplitPath(filename, & path, & file, & ext);
3661 return FindHandler(ext, imageType);
3662 }
3663 }
3664
3665
3666 /// Finds a handler by name
3667 wxRichTextFileHandler* wxRichTextBuffer::FindHandler(const wxString& name)
3668 {
3669 wxList::compatibility_iterator node = sm_handlers.GetFirst();
3670 while (node)
3671 {
3672 wxRichTextFileHandler *handler = (wxRichTextFileHandler*)node->GetData();
3673 if (handler->GetName().Lower() == name.Lower()) return handler;
3674
3675 node = node->GetNext();
3676 }
3677 return NULL;
3678 }
3679
3680 /// Finds a handler by extension and type
3681 wxRichTextFileHandler* wxRichTextBuffer::FindHandler(const wxString& extension, int type)
3682 {
3683 wxList::compatibility_iterator node = sm_handlers.GetFirst();
3684 while (node)
3685 {
3686 wxRichTextFileHandler *handler = (wxRichTextFileHandler*)node->GetData();
3687 if ( handler->GetExtension().Lower() == extension.Lower() &&
3688 (type == wxRICHTEXT_TYPE_ANY || handler->GetType() == type) )
3689 return handler;
3690 node = node->GetNext();
3691 }
3692 return 0;
3693 }
3694
3695 /// Finds a handler by type
3696 wxRichTextFileHandler* wxRichTextBuffer::FindHandler(int type)
3697 {
3698 wxList::compatibility_iterator node = sm_handlers.GetFirst();
3699 while (node)
3700 {
3701 wxRichTextFileHandler *handler = (wxRichTextFileHandler *)node->GetData();
3702 if (handler->GetType() == type) return handler;
3703 node = node->GetNext();
3704 }
3705 return NULL;
3706 }
3707
3708 void wxRichTextBuffer::InitStandardHandlers()
3709 {
3710 if (!FindHandler(wxRICHTEXT_TYPE_TEXT))
3711 AddHandler(new wxRichTextPlainTextHandler);
3712 }
3713
3714 void wxRichTextBuffer::CleanUpHandlers()
3715 {
3716 wxList::compatibility_iterator node = sm_handlers.GetFirst();
3717 while (node)
3718 {
3719 wxRichTextFileHandler* handler = (wxRichTextFileHandler*)node->GetData();
3720 wxList::compatibility_iterator next = node->GetNext();
3721 delete handler;
3722 node = next;
3723 }
3724
3725 sm_handlers.Clear();
3726 }
3727
3728 wxString wxRichTextBuffer::GetExtWildcard(bool combine, bool save, wxArrayInt* types)
3729 {
3730 if (types)
3731 types->Clear();
3732
3733 wxString wildcard;
3734
3735 wxList::compatibility_iterator node = GetHandlers().GetFirst();
3736 int count = 0;
3737 while (node)
3738 {
3739 wxRichTextFileHandler* handler = (wxRichTextFileHandler*) node->GetData();
3740 if (handler->IsVisible() && ((save && handler->CanSave()) || !save && handler->CanLoad()))
3741 {
3742 if (combine)
3743 {
3744 if (count > 0)
3745 wildcard += wxT(";");
3746 wildcard += wxT("*.") + handler->GetExtension();
3747 }
3748 else
3749 {
3750 if (count > 0)
3751 wildcard += wxT("|");
3752 wildcard += handler->GetName();
3753 wildcard += wxT(" ");
3754 wildcard += _("files");
3755 wildcard += wxT(" (*.");
3756 wildcard += handler->GetExtension();
3757 wildcard += wxT(")|*.");
3758 wildcard += handler->GetExtension();
3759 if (types)
3760 types->Add(handler->GetType());
3761 }
3762 count ++;
3763 }
3764
3765 node = node->GetNext();
3766 }
3767
3768 if (combine)
3769 wildcard = wxT("(") + wildcard + wxT(")|") + wildcard;
3770 return wildcard;
3771 }
3772
3773 /// Load a file
3774 bool wxRichTextBuffer::LoadFile(const wxString& filename, int type)
3775 {
3776 wxRichTextFileHandler* handler = FindHandlerFilenameOrType(filename, type);
3777 if (handler)
3778 {
3779 SetDefaultStyle(wxTextAttrEx());
3780
3781 bool success = handler->LoadFile(this, filename);
3782 Invalidate(wxRICHTEXT_ALL);
3783 return success;
3784 }
3785 else
3786 return false;
3787 }
3788
3789 /// Save a file
3790 bool wxRichTextBuffer::SaveFile(const wxString& filename, int type)
3791 {
3792 wxRichTextFileHandler* handler = FindHandlerFilenameOrType(filename, type);
3793 if (handler)
3794 return handler->SaveFile(this, filename);
3795 else
3796 return false;
3797 }
3798
3799 /// Load from a stream
3800 bool wxRichTextBuffer::LoadFile(wxInputStream& stream, int type)
3801 {
3802 wxRichTextFileHandler* handler = FindHandler(type);
3803 if (handler)
3804 {
3805 SetDefaultStyle(wxTextAttrEx());
3806 bool success = handler->LoadFile(this, stream);
3807 Invalidate(wxRICHTEXT_ALL);
3808 return success;
3809 }
3810 else
3811 return false;
3812 }
3813
3814 /// Save to a stream
3815 bool wxRichTextBuffer::SaveFile(wxOutputStream& stream, int type)
3816 {
3817 wxRichTextFileHandler* handler = FindHandler(type);
3818 if (handler)
3819 return handler->SaveFile(this, stream);
3820 else
3821 return false;
3822 }
3823
3824 /// Copy the range to the clipboard
3825 bool wxRichTextBuffer::CopyToClipboard(const wxRichTextRange& range)
3826 {
3827 bool success = false;
3828 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
3829 wxString text = GetTextForRange(range);
3830 if (!wxTheClipboard->IsOpened() && wxTheClipboard->Open())
3831 {
3832 success = wxTheClipboard->SetData(new wxTextDataObject(text));
3833 wxTheClipboard->Close();
3834 }
3835 #else
3836 wxUnusedVar(range);
3837 #endif
3838 return success;
3839 }
3840
3841 /// Paste the clipboard content to the buffer
3842 bool wxRichTextBuffer::PasteFromClipboard(long position)
3843 {
3844 bool success = false;
3845 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
3846 if (CanPasteFromClipboard())
3847 {
3848 if (wxTheClipboard->Open())
3849 {
3850 if (wxTheClipboard->IsSupported(wxDF_TEXT))
3851 {
3852 wxTextDataObject data;
3853 wxTheClipboard->GetData(data);
3854 wxString text(data.GetText());
3855
3856 InsertTextWithUndo(position+1, text, GetRichTextCtrl());
3857
3858 success = true;
3859 }
3860 else if (wxTheClipboard->IsSupported(wxDF_BITMAP))
3861 {
3862 wxBitmapDataObject data;
3863 wxTheClipboard->GetData(data);
3864 wxBitmap bitmap(data.GetBitmap());
3865 wxImage image(bitmap.ConvertToImage());
3866
3867 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Image"), wxRICHTEXT_INSERT, this, GetRichTextCtrl(), false);
3868
3869 action->GetNewParagraphs().AddImage(image);
3870
3871 if (action->GetNewParagraphs().GetChildCount() == 1)
3872 action->GetNewParagraphs().SetPartialParagraph(true);
3873
3874 action->SetPosition(position);
3875
3876 // Set the range we'll need to delete in Undo
3877 action->SetRange(wxRichTextRange(position, position));
3878
3879 SubmitAction(action);
3880
3881 success = true;
3882 }
3883 wxTheClipboard->Close();
3884 }
3885 }
3886 #else
3887 wxUnusedVar(position);
3888 #endif
3889 return success;
3890 }
3891
3892 /// Can we paste from the clipboard?
3893 bool wxRichTextBuffer::CanPasteFromClipboard() const
3894 {
3895 bool canPaste = false;
3896 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
3897 if (!wxTheClipboard->IsOpened() && wxTheClipboard->Open())
3898 {
3899 if (wxTheClipboard->IsSupported(wxDF_TEXT) || wxTheClipboard->IsSupported(wxDF_BITMAP))
3900 {
3901 canPaste = true;
3902 }
3903 wxTheClipboard->Close();
3904 }
3905 #endif
3906 return canPaste;
3907 }
3908
3909 /// Dumps contents of buffer for debugging purposes
3910 void wxRichTextBuffer::Dump()
3911 {
3912 wxString text;
3913 {
3914 wxStringOutputStream stream(& text);
3915 wxTextOutputStream textStream(stream);
3916 Dump(textStream);
3917 }
3918
3919 wxLogDebug(text);
3920 }
3921
3922
3923 /*
3924 * Module to initialise and clean up handlers
3925 */
3926
3927 class wxRichTextModule: public wxModule
3928 {
3929 DECLARE_DYNAMIC_CLASS(wxRichTextModule)
3930 public:
3931 wxRichTextModule() {}
3932 bool OnInit() { wxRichTextBuffer::InitStandardHandlers(); return true; };
3933 void OnExit() { wxRichTextBuffer::CleanUpHandlers(); };
3934 };
3935
3936 IMPLEMENT_DYNAMIC_CLASS(wxRichTextModule, wxModule)
3937
3938
3939 /*!
3940 * Commands for undo/redo
3941 *
3942 */
3943
3944 wxRichTextCommand::wxRichTextCommand(const wxString& name, wxRichTextCommandId id, wxRichTextBuffer* buffer,
3945 wxRichTextCtrl* ctrl, bool ignoreFirstTime): wxCommand(true, name)
3946 {
3947 /* wxRichTextAction* action = */ new wxRichTextAction(this, name, id, buffer, ctrl, ignoreFirstTime);
3948 }
3949
3950 wxRichTextCommand::wxRichTextCommand(const wxString& name): wxCommand(true, name)
3951 {
3952 }
3953
3954 wxRichTextCommand::~wxRichTextCommand()
3955 {
3956 ClearActions();
3957 }
3958
3959 void wxRichTextCommand::AddAction(wxRichTextAction* action)
3960 {
3961 if (!m_actions.Member(action))
3962 m_actions.Append(action);
3963 }
3964
3965 bool wxRichTextCommand::Do()
3966 {
3967 for (wxList::compatibility_iterator node = m_actions.GetFirst(); node; node = node->GetNext())
3968 {
3969 wxRichTextAction* action = (wxRichTextAction*) node->GetData();
3970 action->Do();
3971 }
3972
3973 return true;
3974 }
3975
3976 bool wxRichTextCommand::Undo()
3977 {
3978 for (wxList::compatibility_iterator node = m_actions.GetLast(); node; node = node->GetPrevious())
3979 {
3980 wxRichTextAction* action = (wxRichTextAction*) node->GetData();
3981 action->Undo();
3982 }
3983
3984 return true;
3985 }
3986
3987 void wxRichTextCommand::ClearActions()
3988 {
3989 WX_CLEAR_LIST(wxList, m_actions);
3990 }
3991
3992 /*!
3993 * Individual action
3994 *
3995 */
3996
3997 wxRichTextAction::wxRichTextAction(wxRichTextCommand* cmd, const wxString& name, wxRichTextCommandId id, wxRichTextBuffer* buffer,
3998 wxRichTextCtrl* ctrl, bool ignoreFirstTime)
3999 {
4000 m_buffer = buffer;
4001 m_ignoreThis = ignoreFirstTime;
4002 m_cmdId = id;
4003 m_position = -1;
4004 m_ctrl = ctrl;
4005 m_name = name;
4006 m_newParagraphs.SetDefaultStyle(buffer->GetDefaultStyle());
4007 m_newParagraphs.SetBasicStyle(buffer->GetBasicStyle());
4008 if (cmd)
4009 cmd->AddAction(this);
4010 }
4011
4012 wxRichTextAction::~wxRichTextAction()
4013 {
4014 }
4015
4016 bool wxRichTextAction::Do()
4017 {
4018 m_buffer->Modify(true);
4019
4020 switch (m_cmdId)
4021 {
4022 case wxRICHTEXT_INSERT:
4023 {
4024 m_buffer->InsertFragment(GetPosition(), m_newParagraphs);
4025 m_buffer->UpdateRanges();
4026 m_buffer->Invalidate(GetRange());
4027
4028 long newCaretPosition = GetPosition() + m_newParagraphs.GetRange().GetLength() - 1;
4029 if (m_newParagraphs.GetPartialParagraph())
4030 newCaretPosition --;
4031
4032 UpdateAppearance(newCaretPosition, true /* send update event */);
4033
4034 break;
4035 }
4036 case wxRICHTEXT_DELETE:
4037 {
4038 m_buffer->DeleteRange(GetRange());
4039 m_buffer->UpdateRanges();
4040 m_buffer->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
4041
4042 UpdateAppearance(GetRange().GetStart()-1, true /* send update event */);
4043
4044 break;
4045 }
4046 case wxRICHTEXT_CHANGE_STYLE:
4047 {
4048 ApplyParagraphs(GetNewParagraphs());
4049 m_buffer->Invalidate(GetRange());
4050
4051 UpdateAppearance(GetPosition());
4052
4053 break;
4054 }
4055 default:
4056 break;
4057 }
4058
4059 return true;
4060 }
4061
4062 bool wxRichTextAction::Undo()
4063 {
4064 m_buffer->Modify(true);
4065
4066 switch (m_cmdId)
4067 {
4068 case wxRICHTEXT_INSERT:
4069 {
4070 m_buffer->DeleteRange(GetRange());
4071 m_buffer->UpdateRanges();
4072 m_buffer->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
4073
4074 long newCaretPosition = GetPosition() - 1;
4075 // if (m_newParagraphs.GetPartialParagraph())
4076 // newCaretPosition --;
4077
4078 UpdateAppearance(newCaretPosition, true /* send update event */);
4079
4080 break;
4081 }
4082 case wxRICHTEXT_DELETE:
4083 {
4084 m_buffer->InsertFragment(GetRange().GetStart(), m_oldParagraphs);
4085 m_buffer->UpdateRanges();
4086 m_buffer->Invalidate(GetRange());
4087
4088 UpdateAppearance(GetPosition(), true /* send update event */);
4089
4090 break;
4091 }
4092 case wxRICHTEXT_CHANGE_STYLE:
4093 {
4094 ApplyParagraphs(GetOldParagraphs());
4095 m_buffer->Invalidate(GetRange());
4096
4097 UpdateAppearance(GetPosition());
4098
4099 break;
4100 }
4101 default:
4102 break;
4103 }
4104
4105 return true;
4106 }
4107
4108 /// Update the control appearance
4109 void wxRichTextAction::UpdateAppearance(long caretPosition, bool sendUpdateEvent)
4110 {
4111 if (m_ctrl)
4112 {
4113 m_ctrl->SetCaretPosition(caretPosition);
4114 if (!m_ctrl->IsFrozen())
4115 {
4116 m_ctrl->LayoutContent();
4117 m_ctrl->PositionCaret();
4118 m_ctrl->Refresh(false);
4119
4120 if (sendUpdateEvent)
4121 m_ctrl->SendUpdateEvent();
4122 }
4123 }
4124 }
4125
4126 /// Replace the buffer paragraphs with the new ones.
4127 void wxRichTextAction::ApplyParagraphs(const wxRichTextFragment& fragment)
4128 {
4129 wxRichTextObjectList::compatibility_iterator node = fragment.GetChildren().GetFirst();
4130 while (node)
4131 {
4132 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
4133 wxASSERT (para != NULL);
4134
4135 // We'll replace the existing paragraph by finding the paragraph at this position,
4136 // delete its node data, and setting a copy as the new node data.
4137 // TODO: make more efficient by simply swapping old and new paragraph objects.
4138
4139 wxRichTextParagraph* existingPara = m_buffer->GetParagraphAtPosition(para->GetRange().GetStart());
4140 if (existingPara)
4141 {
4142 wxRichTextObjectList::compatibility_iterator bufferParaNode = m_buffer->GetChildren().Find(existingPara);
4143 if (bufferParaNode)
4144 {
4145 wxRichTextParagraph* newPara = new wxRichTextParagraph(*para);
4146 newPara->SetParent(m_buffer);
4147
4148 bufferParaNode->SetData(newPara);
4149
4150 delete existingPara;
4151 }
4152 }
4153
4154 node = node->GetNext();
4155 }
4156 }
4157
4158
4159 /*!
4160 * wxRichTextRange
4161 * This stores beginning and end positions for a range of data.
4162 */
4163
4164 /// Limit this range to be within 'range'
4165 bool wxRichTextRange::LimitTo(const wxRichTextRange& range)
4166 {
4167 if (m_start < range.m_start)
4168 m_start = range.m_start;
4169
4170 if (m_end > range.m_end)
4171 m_end = range.m_end;
4172
4173 return true;
4174 }
4175
4176 /*!
4177 * wxRichTextImage implementation
4178 * This object represents an image.
4179 */
4180
4181 IMPLEMENT_DYNAMIC_CLASS(wxRichTextImage, wxRichTextObject)
4182
4183 wxRichTextImage::wxRichTextImage(const wxImage& image, wxRichTextObject* parent):
4184 wxRichTextObject(parent)
4185 {
4186 m_image = image;
4187 }
4188
4189 wxRichTextImage::wxRichTextImage(const wxRichTextImageBlock& imageBlock, wxRichTextObject* parent):
4190 wxRichTextObject(parent)
4191 {
4192 m_imageBlock = imageBlock;
4193 m_imageBlock.Load(m_image);
4194 }
4195
4196 /// Load wxImage from the block
4197 bool wxRichTextImage::LoadFromBlock()
4198 {
4199 m_imageBlock.Load(m_image);
4200 return m_imageBlock.Ok();
4201 }
4202
4203 /// Make block from the wxImage
4204 bool wxRichTextImage::MakeBlock()
4205 {
4206 if (m_imageBlock.GetImageType() == wxBITMAP_TYPE_ANY || m_imageBlock.GetImageType() == -1)
4207 m_imageBlock.SetImageType(wxBITMAP_TYPE_PNG);
4208
4209 m_imageBlock.MakeImageBlock(m_image, m_imageBlock.GetImageType());
4210 return m_imageBlock.Ok();
4211 }
4212
4213
4214 /// Draw the item
4215 bool wxRichTextImage::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextRange& selectionRange, const wxRect& rect, int WXUNUSED(descent), int WXUNUSED(style))
4216 {
4217 if (!m_image.Ok() && m_imageBlock.Ok())
4218 LoadFromBlock();
4219
4220 if (!m_image.Ok())
4221 return false;
4222
4223 if (m_image.Ok() && !m_bitmap.Ok())
4224 m_bitmap = wxBitmap(m_image);
4225
4226 int y = rect.y + (rect.height - m_image.GetHeight());
4227
4228 if (m_bitmap.Ok())
4229 dc.DrawBitmap(m_bitmap, rect.x, y, true);
4230
4231 if (selectionRange.Contains(range.GetStart()))
4232 {
4233 dc.SetBrush(*wxBLACK_BRUSH);
4234 dc.SetPen(*wxBLACK_PEN);
4235 dc.SetLogicalFunction(wxINVERT);
4236 dc.DrawRectangle(rect);
4237 dc.SetLogicalFunction(wxCOPY);
4238 }
4239
4240 return true;
4241 }
4242
4243 /// Lay the item out
4244 bool wxRichTextImage::Layout(wxDC& WXUNUSED(dc), const wxRect& rect, int WXUNUSED(style))
4245 {
4246 if (!m_image.Ok())
4247 LoadFromBlock();
4248
4249 if (m_image.Ok())
4250 {
4251 SetCachedSize(wxSize(m_image.GetWidth(), m_image.GetHeight()));
4252 SetPosition(rect.GetPosition());
4253 }
4254
4255 return true;
4256 }
4257
4258 /// Get/set the object size for the given range. Returns false if the range
4259 /// is invalid for this object.
4260 bool wxRichTextImage::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& WXUNUSED(descent), wxDC& WXUNUSED(dc), int WXUNUSED(flags)) const
4261 {
4262 if (!range.IsWithin(GetRange()))
4263 return false;
4264
4265 if (!m_image.Ok())
4266 return false;
4267
4268 size.x = m_image.GetWidth();
4269 size.y = m_image.GetHeight();
4270
4271 return true;
4272 }
4273
4274 /// Copy
4275 void wxRichTextImage::Copy(const wxRichTextImage& obj)
4276 {
4277 m_image = obj.m_image;
4278 m_imageBlock = obj.m_imageBlock;
4279 }
4280
4281 /*!
4282 * Utilities
4283 *
4284 */
4285
4286 /// Compare two attribute objects
4287 bool wxTextAttrEq(const wxTextAttrEx& attr1, const wxTextAttrEx& attr2)
4288 {
4289 return (
4290 attr1.GetTextColour() == attr2.GetTextColour() &&
4291 attr1.GetBackgroundColour() == attr2.GetBackgroundColour() &&
4292 attr1.GetFont() == attr2.GetFont() &&
4293 attr1.GetAlignment() == attr2.GetAlignment() &&
4294 attr1.GetLeftIndent() == attr2.GetLeftIndent() &&
4295 attr1.GetRightIndent() == attr2.GetRightIndent() &&
4296 attr1.GetLeftSubIndent() == attr2.GetLeftSubIndent() &&
4297 attr1.GetTabs().GetCount() == attr2.GetTabs().GetCount() && // heuristic
4298 attr1.GetLineSpacing() == attr2.GetLineSpacing() &&
4299 attr1.GetParagraphSpacingAfter() == attr2.GetParagraphSpacingAfter() &&
4300 attr1.GetParagraphSpacingBefore() == attr2.GetParagraphSpacingBefore() &&
4301 attr1.GetBulletStyle() == attr2.GetBulletStyle() &&
4302 attr1.GetBulletNumber() == attr2.GetBulletNumber() &&
4303 attr1.GetBulletSymbol() == attr2.GetBulletSymbol() &&
4304 attr1.GetCharacterStyleName() == attr2.GetCharacterStyleName() &&
4305 attr1.GetParagraphStyleName() == attr2.GetParagraphStyleName());
4306 }
4307
4308 bool wxTextAttrEq(const wxTextAttrEx& attr1, const wxRichTextAttr& attr2)
4309 {
4310 return (
4311 attr1.GetTextColour() == attr2.GetTextColour() &&
4312 attr1.GetBackgroundColour() == attr2.GetBackgroundColour() &&
4313 attr1.GetFont().GetPointSize() == attr2.GetFontSize() &&
4314 attr1.GetFont().GetStyle() == attr2.GetFontStyle() &&
4315 attr1.GetFont().GetWeight() == attr2.GetFontWeight() &&
4316 attr1.GetFont().GetFaceName() == attr2.GetFontFaceName() &&
4317 attr1.GetFont().GetUnderlined() == attr2.GetFontUnderlined() &&
4318 attr1.GetAlignment() == attr2.GetAlignment() &&
4319 attr1.GetLeftIndent() == attr2.GetLeftIndent() &&
4320 attr1.GetRightIndent() == attr2.GetRightIndent() &&
4321 attr1.GetLeftSubIndent() == attr2.GetLeftSubIndent() &&
4322 attr1.GetTabs().GetCount() == attr2.GetTabs().GetCount() && // heuristic
4323 attr1.GetLineSpacing() == attr2.GetLineSpacing() &&
4324 attr1.GetParagraphSpacingAfter() == attr2.GetParagraphSpacingAfter() &&
4325 attr1.GetParagraphSpacingBefore() == attr2.GetParagraphSpacingBefore() &&
4326 attr1.GetBulletStyle() == attr2.GetBulletStyle() &&
4327 attr1.GetBulletNumber() == attr2.GetBulletNumber() &&
4328 attr1.GetBulletSymbol() == attr2.GetBulletSymbol() &&
4329 attr1.GetCharacterStyleName() == attr2.GetCharacterStyleName() &&
4330 attr1.GetParagraphStyleName() == attr2.GetParagraphStyleName());
4331 }
4332
4333 /// Compare two attribute objects, but take into account the flags
4334 /// specifying attributes of interest.
4335 bool wxTextAttrEqPartial(const wxTextAttrEx& attr1, const wxTextAttrEx& attr2, int flags)
4336 {
4337 if ((flags & wxTEXT_ATTR_TEXT_COLOUR) && attr1.GetTextColour() != attr2.GetTextColour())
4338 return false;
4339
4340 if ((flags & wxTEXT_ATTR_BACKGROUND_COLOUR) && attr1.GetBackgroundColour() != attr2.GetBackgroundColour())
4341 return false;
4342
4343 if ((flags & wxTEXT_ATTR_FONT_FACE) && attr1.GetFont().Ok() && attr2.GetFont().Ok() &&
4344 attr1.GetFont().GetFaceName() != attr2.GetFont().GetFaceName())
4345 return false;
4346
4347 if ((flags & wxTEXT_ATTR_FONT_SIZE) && attr1.GetFont().Ok() && attr2.GetFont().Ok() &&
4348 attr1.GetFont().GetPointSize() != attr2.GetFont().GetPointSize())
4349 return false;
4350
4351 if ((flags & wxTEXT_ATTR_FONT_WEIGHT) && attr1.GetFont().Ok() && attr2.GetFont().Ok() &&
4352 attr1.GetFont().GetWeight() != attr2.GetFont().GetWeight())
4353 return false;
4354
4355 if ((flags & wxTEXT_ATTR_FONT_ITALIC) && attr1.GetFont().Ok() && attr2.GetFont().Ok() &&
4356 attr1.GetFont().GetStyle() != attr2.GetFont().GetStyle())
4357 return false;
4358
4359 if ((flags & wxTEXT_ATTR_FONT_UNDERLINE) && attr1.GetFont().Ok() && attr2.GetFont().Ok() &&
4360 attr1.GetFont().GetUnderlined() != attr2.GetFont().GetUnderlined())
4361 return false;
4362
4363 if ((flags & wxTEXT_ATTR_ALIGNMENT) && attr1.GetAlignment() != attr2.GetAlignment())
4364 return false;
4365
4366 if ((flags & wxTEXT_ATTR_LEFT_INDENT) &&
4367 ((attr1.GetLeftIndent() != attr2.GetLeftIndent()) || (attr1.GetLeftSubIndent() != attr2.GetLeftSubIndent())))
4368 return false;
4369
4370 if ((flags & wxTEXT_ATTR_RIGHT_INDENT) &&
4371 (attr1.GetRightIndent() != attr2.GetRightIndent()))
4372 return false;
4373
4374 if ((flags & wxTEXT_ATTR_PARA_SPACING_AFTER) &&
4375 (attr1.GetParagraphSpacingAfter() != attr2.GetParagraphSpacingAfter()))
4376 return false;
4377
4378 if ((flags & wxTEXT_ATTR_PARA_SPACING_BEFORE) &&
4379 (attr1.GetParagraphSpacingBefore() != attr2.GetParagraphSpacingBefore()))
4380 return false;
4381
4382 if ((flags & wxTEXT_ATTR_LINE_SPACING) &&
4383 (attr1.GetLineSpacing() != attr2.GetLineSpacing()))
4384 return false;
4385
4386 if ((flags & wxTEXT_ATTR_CHARACTER_STYLE_NAME) &&
4387 (attr1.GetCharacterStyleName() != attr2.GetCharacterStyleName()))
4388 return false;
4389
4390 if ((flags & wxTEXT_ATTR_PARAGRAPH_STYLE_NAME) &&
4391 (attr1.GetParagraphStyleName() != attr2.GetParagraphStyleName()))
4392 return false;
4393
4394 if ((flags & wxTEXT_ATTR_BULLET_STYLE) &&
4395 (attr1.GetBulletStyle() != attr2.GetBulletStyle()))
4396 return false;
4397
4398 if ((flags & wxTEXT_ATTR_BULLET_NUMBER) &&
4399 (attr1.GetBulletNumber() != attr2.GetBulletNumber()))
4400 return false;
4401
4402 if ((flags & wxTEXT_ATTR_BULLET_SYMBOL) &&
4403 (attr1.GetBulletSymbol() != attr2.GetBulletSymbol()))
4404 return false;
4405
4406 /* TODO
4407 if ((flags & wxTEXT_ATTR_TABS) &&
4408 return false;
4409 */
4410
4411 return true;
4412 }
4413
4414 bool wxTextAttrEqPartial(const wxTextAttrEx& attr1, const wxRichTextAttr& attr2, int flags)
4415 {
4416 if ((flags & wxTEXT_ATTR_TEXT_COLOUR) && attr1.GetTextColour() != attr2.GetTextColour())
4417 return false;
4418
4419 if ((flags & wxTEXT_ATTR_BACKGROUND_COLOUR) && attr1.GetBackgroundColour() != attr2.GetBackgroundColour())
4420 return false;
4421
4422 if ((flags & (wxTEXT_ATTR_FONT)) && !attr1.GetFont().Ok())
4423 return false;
4424
4425 if ((flags & wxTEXT_ATTR_FONT_FACE) && attr1.GetFont().Ok() &&
4426 attr1.GetFont().GetFaceName() != attr2.GetFontFaceName())
4427 return false;
4428
4429 if ((flags & wxTEXT_ATTR_FONT_SIZE) && attr1.GetFont().Ok() &&
4430 attr1.GetFont().GetPointSize() != attr2.GetFontSize())
4431 return false;
4432
4433 if ((flags & wxTEXT_ATTR_FONT_WEIGHT) && attr1.GetFont().Ok() &&
4434 attr1.GetFont().GetWeight() != attr2.GetFontWeight())
4435 return false;
4436
4437 if ((flags & wxTEXT_ATTR_FONT_ITALIC) && attr1.GetFont().Ok() &&
4438 attr1.GetFont().GetStyle() != attr2.GetFontStyle())
4439 return false;
4440
4441 if ((flags & wxTEXT_ATTR_FONT_UNDERLINE) && attr1.GetFont().Ok() &&
4442 attr1.GetFont().GetUnderlined() != attr2.GetFontUnderlined())
4443 return false;
4444
4445 if ((flags & wxTEXT_ATTR_ALIGNMENT) && attr1.GetAlignment() != attr2.GetAlignment())
4446 return false;
4447
4448 if ((flags & wxTEXT_ATTR_LEFT_INDENT) &&
4449 ((attr1.GetLeftIndent() != attr2.GetLeftIndent()) || (attr1.GetLeftSubIndent() != attr2.GetLeftSubIndent())))
4450 return false;
4451
4452 if ((flags & wxTEXT_ATTR_RIGHT_INDENT) &&
4453 (attr1.GetRightIndent() != attr2.GetRightIndent()))
4454 return false;
4455
4456 if ((flags & wxTEXT_ATTR_PARA_SPACING_AFTER) &&
4457 (attr1.GetParagraphSpacingAfter() != attr2.GetParagraphSpacingAfter()))
4458 return false;
4459
4460 if ((flags & wxTEXT_ATTR_PARA_SPACING_BEFORE) &&
4461 (attr1.GetParagraphSpacingBefore() != attr2.GetParagraphSpacingBefore()))
4462 return false;
4463
4464 if ((flags & wxTEXT_ATTR_LINE_SPACING) &&
4465 (attr1.GetLineSpacing() != attr2.GetLineSpacing()))
4466 return false;
4467
4468 if ((flags & wxTEXT_ATTR_CHARACTER_STYLE_NAME) &&
4469 (attr1.GetCharacterStyleName() != attr2.GetCharacterStyleName()))
4470 return false;
4471
4472 if ((flags & wxTEXT_ATTR_PARAGRAPH_STYLE_NAME) &&
4473 (attr1.GetParagraphStyleName() != attr2.GetParagraphStyleName()))
4474 return false;
4475
4476 if ((flags & wxTEXT_ATTR_BULLET_STYLE) &&
4477 (attr1.GetBulletStyle() != attr2.GetBulletStyle()))
4478 return false;
4479
4480 if ((flags & wxTEXT_ATTR_BULLET_NUMBER) &&
4481 (attr1.GetBulletNumber() != attr2.GetBulletNumber()))
4482 return false;
4483
4484 if ((flags & wxTEXT_ATTR_BULLET_SYMBOL) &&
4485 (attr1.GetBulletSymbol() != attr2.GetBulletSymbol()))
4486 return false;
4487
4488 /* TODO
4489 if ((flags & wxTEXT_ATTR_TABS) &&
4490 return false;
4491 */
4492
4493 return true;
4494 }
4495
4496
4497 /// Apply one style to another
4498 bool wxRichTextApplyStyle(wxTextAttrEx& destStyle, const wxTextAttrEx& style)
4499 {
4500 // Whole font
4501 if (style.GetFont().Ok() && ((style.GetFlags() & (wxTEXT_ATTR_FONT)) == (wxTEXT_ATTR_FONT)))
4502 destStyle.SetFont(style.GetFont());
4503 else if (style.GetFont().Ok())
4504 {
4505 wxFont font = destStyle.GetFont();
4506
4507 if (style.GetFlags() & wxTEXT_ATTR_FONT_FACE)
4508 font.SetFaceName(style.GetFont().GetFaceName());
4509
4510 if (style.GetFlags() & wxTEXT_ATTR_FONT_SIZE)
4511 font.SetPointSize(style.GetFont().GetPointSize());
4512
4513 if (style.GetFlags() & wxTEXT_ATTR_FONT_ITALIC)
4514 font.SetStyle(style.GetFont().GetStyle());
4515
4516 if (style.GetFlags() & wxTEXT_ATTR_FONT_WEIGHT)
4517 font.SetWeight(style.GetFont().GetWeight());
4518
4519 if (style.GetFlags() & wxTEXT_ATTR_FONT_UNDERLINE)
4520 font.SetUnderlined(style.GetFont().GetUnderlined());
4521
4522 if (font != destStyle.GetFont())
4523 destStyle.SetFont(font);
4524 }
4525
4526 if ( style.GetTextColour().Ok() && style.HasTextColour())
4527 destStyle.SetTextColour(style.GetTextColour());
4528
4529 if ( style.GetBackgroundColour().Ok() && style.HasBackgroundColour())
4530 destStyle.SetBackgroundColour(style.GetBackgroundColour());
4531
4532 if (style.HasAlignment())
4533 destStyle.SetAlignment(style.GetAlignment());
4534
4535 if (style.HasTabs())
4536 destStyle.SetTabs(style.GetTabs());
4537
4538 if (style.HasLeftIndent())
4539 destStyle.SetLeftIndent(style.GetLeftIndent(), style.GetLeftSubIndent());
4540
4541 if (style.HasRightIndent())
4542 destStyle.SetRightIndent(style.GetRightIndent());
4543
4544 if (style.HasParagraphSpacingAfter())
4545 destStyle.SetParagraphSpacingAfter(style.GetParagraphSpacingAfter());
4546
4547 if (style.HasParagraphSpacingBefore())
4548 destStyle.SetParagraphSpacingBefore(style.GetParagraphSpacingBefore());
4549
4550 if (style.HasLineSpacing())
4551 destStyle.SetLineSpacing(style.GetLineSpacing());
4552
4553 if (style.HasCharacterStyleName())
4554 destStyle.SetCharacterStyleName(style.GetCharacterStyleName());
4555
4556 if (style.HasParagraphStyleName())
4557 destStyle.SetParagraphStyleName(style.GetParagraphStyleName());
4558
4559 if (style.HasBulletStyle())
4560 {
4561 destStyle.SetBulletStyle(style.GetBulletStyle());
4562 destStyle.SetBulletSymbol(style.GetBulletSymbol());
4563 }
4564
4565 if (style.HasBulletNumber())
4566 destStyle.SetBulletNumber(style.GetBulletNumber());
4567
4568 return true;
4569 }
4570
4571 bool wxRichTextApplyStyle(wxRichTextAttr& destStyle, const wxTextAttrEx& style)
4572 {
4573 wxTextAttrEx destStyle2;
4574 destStyle.CopyTo(destStyle2);
4575 wxRichTextApplyStyle(destStyle2, style);
4576 destStyle = destStyle2;
4577 return true;
4578 }
4579
4580 bool wxRichTextApplyStyle(wxTextAttrEx& destStyle, const wxRichTextAttr& style)
4581 {
4582
4583 // Whole font. Avoiding setting individual attributes if possible, since
4584 // it recreates the font each time.
4585 if ((style.GetFlags() & (wxTEXT_ATTR_FONT)) == (wxTEXT_ATTR_FONT))
4586 {
4587 destStyle.SetFont(wxFont(style.GetFontSize(), destStyle.GetFont().Ok() ? destStyle.GetFont().GetFamily() : wxDEFAULT,
4588 style.GetFontStyle(), style.GetFontWeight(), style.GetFontUnderlined(), style.GetFontFaceName()));
4589 }
4590 else if (style.GetFlags() & (wxTEXT_ATTR_FONT))
4591 {
4592 wxFont font = destStyle.GetFont();
4593
4594 if (style.GetFlags() & wxTEXT_ATTR_FONT_FACE)
4595 font.SetFaceName(style.GetFontFaceName());
4596
4597 if (style.GetFlags() & wxTEXT_ATTR_FONT_SIZE)
4598 font.SetPointSize(style.GetFontSize());
4599
4600 if (style.GetFlags() & wxTEXT_ATTR_FONT_ITALIC)
4601 font.SetStyle(style.GetFontStyle());
4602
4603 if (style.GetFlags() & wxTEXT_ATTR_FONT_WEIGHT)
4604 font.SetWeight(style.GetFontWeight());
4605
4606 if (style.GetFlags() & wxTEXT_ATTR_FONT_UNDERLINE)
4607 font.SetUnderlined(style.GetFontUnderlined());
4608
4609 if (font != destStyle.GetFont())
4610 destStyle.SetFont(font);
4611 }
4612
4613 if ( style.GetTextColour().Ok() && style.HasTextColour())
4614 destStyle.SetTextColour(style.GetTextColour());
4615
4616 if ( style.GetBackgroundColour().Ok() && style.HasBackgroundColour())
4617 destStyle.SetBackgroundColour(style.GetBackgroundColour());
4618
4619 if (style.HasAlignment())
4620 destStyle.SetAlignment(style.GetAlignment());
4621
4622 if (style.HasTabs())
4623 destStyle.SetTabs(style.GetTabs());
4624
4625 if (style.HasLeftIndent())
4626 destStyle.SetLeftIndent(style.GetLeftIndent(), style.GetLeftSubIndent());
4627
4628 if (style.HasRightIndent())
4629 destStyle.SetRightIndent(style.GetRightIndent());
4630
4631 if (style.HasParagraphSpacingAfter())
4632 destStyle.SetParagraphSpacingAfter(style.GetParagraphSpacingAfter());
4633
4634 if (style.HasParagraphSpacingBefore())
4635 destStyle.SetParagraphSpacingBefore(style.GetParagraphSpacingBefore());
4636
4637 if (style.HasLineSpacing())
4638 destStyle.SetLineSpacing(style.GetLineSpacing());
4639
4640 if (style.HasCharacterStyleName())
4641 destStyle.SetCharacterStyleName(style.GetCharacterStyleName());
4642
4643 if (style.HasParagraphStyleName())
4644 destStyle.SetParagraphStyleName(style.GetParagraphStyleName());
4645
4646 if (style.HasBulletStyle())
4647 {
4648 destStyle.SetBulletStyle(style.GetBulletStyle());
4649 destStyle.SetBulletSymbol(style.GetBulletSymbol());
4650 }
4651
4652 if (style.HasBulletNumber())
4653 destStyle.SetBulletNumber(style.GetBulletNumber());
4654
4655 return true;
4656 }
4657
4658
4659 /*!
4660 * wxRichTextAttr stores attributes without a wxFont object, so is a much more
4661 * efficient way to query styles.
4662 */
4663
4664 // ctors
4665 wxRichTextAttr::wxRichTextAttr(const wxColour& colText,
4666 const wxColour& colBack,
4667 wxTextAttrAlignment alignment): m_textAlignment(alignment), m_colText(colText), m_colBack(colBack)
4668 {
4669 Init();
4670
4671 if (m_colText.Ok()) m_flags |= wxTEXT_ATTR_TEXT_COLOUR;
4672 if (m_colBack.Ok()) m_flags |= wxTEXT_ATTR_BACKGROUND_COLOUR;
4673 if (alignment != wxTEXT_ALIGNMENT_DEFAULT)
4674 m_flags |= wxTEXT_ATTR_ALIGNMENT;
4675 }
4676
4677 wxRichTextAttr::wxRichTextAttr(const wxTextAttrEx& attr)
4678 {
4679 Init();
4680
4681 (*this) = attr;
4682 }
4683
4684 // operations
4685 void wxRichTextAttr::Init()
4686 {
4687 m_textAlignment = wxTEXT_ALIGNMENT_DEFAULT;
4688 m_flags = 0;
4689 m_leftIndent = 0;
4690 m_leftSubIndent = 0;
4691 m_rightIndent = 0;
4692
4693 m_fontSize = 12;
4694 m_fontStyle = wxNORMAL;
4695 m_fontWeight = wxNORMAL;
4696 m_fontUnderlined = false;
4697
4698 m_paragraphSpacingAfter = 0;
4699 m_paragraphSpacingBefore = 0;
4700 m_lineSpacing = 0;
4701 m_bulletStyle = wxTEXT_ATTR_BULLET_STYLE_NONE;
4702 m_bulletNumber = 0;
4703 m_bulletSymbol = wxT('*');
4704 }
4705
4706 // operators
4707 void wxRichTextAttr::operator= (const wxRichTextAttr& attr)
4708 {
4709 m_colText = attr.m_colText;
4710 m_colBack = attr.m_colBack;
4711 m_textAlignment = attr.m_textAlignment;
4712 m_leftIndent = attr.m_leftIndent;
4713 m_leftSubIndent = attr.m_leftSubIndent;
4714 m_rightIndent = attr.m_rightIndent;
4715 m_tabs = attr.m_tabs;
4716 m_flags = attr.m_flags;
4717
4718 m_fontSize = attr.m_fontSize;
4719 m_fontStyle = attr.m_fontStyle;
4720 m_fontWeight = attr.m_fontWeight;
4721 m_fontUnderlined = attr.m_fontUnderlined;
4722 m_fontFaceName = attr.m_fontFaceName;
4723
4724 m_paragraphSpacingAfter = attr.m_paragraphSpacingAfter;
4725 m_paragraphSpacingBefore = attr.m_paragraphSpacingBefore;
4726 m_lineSpacing = attr.m_lineSpacing;
4727 m_characterStyleName = attr.m_characterStyleName;
4728 m_paragraphStyleName = attr.m_paragraphStyleName;
4729 m_bulletStyle = attr.m_bulletStyle;
4730 m_bulletNumber = attr.m_bulletNumber;
4731 m_bulletSymbol = attr.m_bulletSymbol;
4732 }
4733
4734 // operators
4735 void wxRichTextAttr::operator= (const wxTextAttrEx& attr)
4736 {
4737 m_colText = attr.GetTextColour();
4738 m_colBack = attr.GetBackgroundColour();
4739 m_textAlignment = attr.GetAlignment();
4740 m_leftIndent = attr.GetLeftIndent();
4741 m_leftSubIndent = attr.GetLeftSubIndent();
4742 m_rightIndent = attr.GetRightIndent();
4743 m_tabs = attr.GetTabs();
4744 m_flags = attr.GetFlags();
4745
4746 m_paragraphSpacingAfter = attr.GetParagraphSpacingAfter();
4747 m_paragraphSpacingBefore = attr.GetParagraphSpacingBefore();
4748 m_lineSpacing = attr.GetLineSpacing();
4749 m_characterStyleName = attr.GetCharacterStyleName();
4750 m_paragraphStyleName = attr.GetParagraphStyleName();
4751
4752 if (attr.GetFont().Ok())
4753 GetFontAttributes(attr.GetFont());
4754 }
4755
4756 // Making a wxTextAttrEx object.
4757 wxRichTextAttr::operator wxTextAttrEx () const
4758 {
4759 wxTextAttrEx attr;
4760 CopyTo(attr);
4761 return attr;
4762 }
4763
4764 // Copy to a wxTextAttr
4765 void wxRichTextAttr::CopyTo(wxTextAttrEx& attr) const
4766 {
4767 attr.SetTextColour(GetTextColour());
4768 attr.SetBackgroundColour(GetBackgroundColour());
4769 attr.SetAlignment(GetAlignment());
4770 attr.SetTabs(GetTabs());
4771 attr.SetLeftIndent(GetLeftIndent(), GetLeftSubIndent());
4772 attr.SetRightIndent(GetRightIndent());
4773 attr.SetFont(CreateFont());
4774 attr.SetFlags(GetFlags()); // Important: set after SetFont, since SetFont sets flags
4775
4776 attr.SetParagraphSpacingAfter(m_paragraphSpacingAfter);
4777 attr.SetParagraphSpacingBefore(m_paragraphSpacingBefore);
4778 attr.SetLineSpacing(m_lineSpacing);
4779 attr.SetBulletStyle(m_bulletStyle);
4780 attr.SetBulletNumber(m_bulletNumber);
4781 attr.SetBulletSymbol(m_bulletSymbol);
4782 attr.SetCharacterStyleName(m_characterStyleName);
4783 attr.SetParagraphStyleName(m_paragraphStyleName);
4784
4785 }
4786
4787 // Create font from font attributes.
4788 wxFont wxRichTextAttr::CreateFont() const
4789 {
4790 wxFont font(m_fontSize, wxDEFAULT, m_fontStyle, m_fontWeight, m_fontUnderlined, m_fontFaceName);
4791 #ifdef __WXMAC__
4792 font.SetNoAntiAliasing(true);
4793 #endif
4794 return font;
4795 }
4796
4797 // Get attributes from font.
4798 bool wxRichTextAttr::GetFontAttributes(const wxFont& font)
4799 {
4800 if (!font.Ok())
4801 return false;
4802
4803 m_fontSize = font.GetPointSize();
4804 m_fontStyle = font.GetStyle();
4805 m_fontWeight = font.GetWeight();
4806 m_fontUnderlined = font.GetUnderlined();
4807 m_fontFaceName = font.GetFaceName();
4808
4809 return true;
4810 }
4811
4812 /*!
4813 * wxTextAttrEx is an extended version of wxTextAttr with more paragraph attributes.
4814 */
4815
4816 wxTextAttrEx::wxTextAttrEx(const wxTextAttrEx& attr): wxTextAttr(attr)
4817 {
4818 m_paragraphSpacingAfter = attr.m_paragraphSpacingAfter;
4819 m_paragraphSpacingBefore = attr.m_paragraphSpacingBefore;
4820 m_lineSpacing = attr.m_lineSpacing;
4821 m_paragraphStyleName = attr.m_paragraphStyleName;
4822 m_characterStyleName = attr.m_characterStyleName;
4823 m_bulletStyle = attr.m_bulletStyle;
4824 m_bulletNumber = attr.m_bulletNumber;
4825 m_bulletSymbol = attr.m_bulletSymbol;
4826 }
4827
4828 // Initialise this object.
4829 void wxTextAttrEx::Init()
4830 {
4831 m_paragraphSpacingAfter = 0;
4832 m_paragraphSpacingBefore = 0;
4833 m_lineSpacing = 0;
4834 m_bulletStyle = wxTEXT_ATTR_BULLET_STYLE_NONE;
4835 m_bulletNumber = 0;
4836 m_bulletSymbol = 0;
4837 m_bulletSymbol = wxT('*');
4838 }
4839
4840 // Assignment from a wxTextAttrEx object
4841 void wxTextAttrEx::operator= (const wxTextAttrEx& attr)
4842 {
4843 wxTextAttr::operator= (attr);
4844
4845 m_paragraphSpacingAfter = attr.m_paragraphSpacingAfter;
4846 m_paragraphSpacingBefore = attr.m_paragraphSpacingBefore;
4847 m_lineSpacing = attr.m_lineSpacing;
4848 m_characterStyleName = attr.m_characterStyleName;
4849 m_paragraphStyleName = attr.m_paragraphStyleName;
4850 m_bulletStyle = attr.m_bulletStyle;
4851 m_bulletNumber = attr.m_bulletNumber;
4852 m_bulletSymbol = attr.m_bulletSymbol;
4853 }
4854
4855 // Assignment from a wxTextAttr object.
4856 void wxTextAttrEx::operator= (const wxTextAttr& attr)
4857 {
4858 wxTextAttr::operator= (attr);
4859 }
4860
4861 /*!
4862 * wxRichTextFileHandler
4863 * Base class for file handlers
4864 */
4865
4866 IMPLEMENT_CLASS(wxRichTextFileHandler, wxObject)
4867
4868 #if wxUSE_STREAMS
4869 bool wxRichTextFileHandler::LoadFile(wxRichTextBuffer *buffer, const wxString& filename)
4870 {
4871 wxFFileInputStream stream(filename);
4872 if (stream.Ok())
4873 return LoadFile(buffer, stream);
4874 else
4875 return false;
4876 }
4877
4878 bool wxRichTextFileHandler::SaveFile(wxRichTextBuffer *buffer, const wxString& filename)
4879 {
4880 wxFFileOutputStream stream(filename);
4881 if (stream.Ok())
4882 return SaveFile(buffer, stream);
4883 else
4884 return false;
4885 }
4886 #endif // wxUSE_STREAMS
4887
4888 /// Can we handle this filename (if using files)? By default, checks the extension.
4889 bool wxRichTextFileHandler::CanHandle(const wxString& filename) const
4890 {
4891 wxString path, file, ext;
4892 wxSplitPath(filename, & path, & file, & ext);
4893
4894 return (ext.Lower() == GetExtension());
4895 }
4896
4897 /*!
4898 * wxRichTextTextHandler
4899 * Plain text handler
4900 */
4901
4902 IMPLEMENT_CLASS(wxRichTextPlainTextHandler, wxRichTextFileHandler)
4903
4904 #if wxUSE_STREAMS
4905 bool wxRichTextPlainTextHandler::DoLoadFile(wxRichTextBuffer *buffer, wxInputStream& stream)
4906 {
4907 if (!stream.IsOk())
4908 return false;
4909
4910 wxString str;
4911 int lastCh = 0;
4912
4913 while (!stream.Eof())
4914 {
4915 int ch = stream.GetC();
4916
4917 if (!stream.Eof())
4918 {
4919 if (ch == 10 && lastCh != 13)
4920 str += wxT('\n');
4921
4922 if (ch > 0 && ch != 10)
4923 str += wxChar(ch);
4924
4925 lastCh = ch;
4926 }
4927 }
4928
4929 buffer->Clear();
4930 buffer->AddParagraphs(str);
4931 buffer->UpdateRanges();
4932
4933 return true;
4934
4935 }
4936
4937 bool wxRichTextPlainTextHandler::DoSaveFile(wxRichTextBuffer *buffer, wxOutputStream& stream)
4938 {
4939 if (!stream.IsOk())
4940 return false;
4941
4942 wxString text = buffer->GetText();
4943 wxCharBuffer buf = text.ToAscii();
4944
4945 stream.Write((const char*) buf, text.Length());
4946 return true;
4947 }
4948 #endif // wxUSE_STREAMS
4949
4950 /*
4951 * Stores information about an image, in binary in-memory form
4952 */
4953
4954 wxRichTextImageBlock::wxRichTextImageBlock()
4955 {
4956 Init();
4957 }
4958
4959 wxRichTextImageBlock::wxRichTextImageBlock(const wxRichTextImageBlock& block):wxObject()
4960 {
4961 Init();
4962 Copy(block);
4963 }
4964
4965 wxRichTextImageBlock::~wxRichTextImageBlock()
4966 {
4967 if (m_data)
4968 {
4969 delete[] m_data;
4970 m_data = NULL;
4971 }
4972 }
4973
4974 void wxRichTextImageBlock::Init()
4975 {
4976 m_data = NULL;
4977 m_dataSize = 0;
4978 m_imageType = -1;
4979 }
4980
4981 void wxRichTextImageBlock::Clear()
4982 {
4983 if (m_data)
4984 delete m_data;
4985 m_data = NULL;
4986 m_dataSize = 0;
4987 m_imageType = -1;
4988 }
4989
4990
4991 // Load the original image into a memory block.
4992 // If the image is not a JPEG, we must convert it into a JPEG
4993 // to conserve space.
4994 // If it's not a JPEG we can make use of 'image', already scaled, so we don't have to
4995 // load the image a 2nd time.
4996
4997 bool wxRichTextImageBlock::MakeImageBlock(const wxString& filename, int imageType, wxImage& image, bool convertToJPEG)
4998 {
4999 m_imageType = imageType;
5000
5001 wxString filenameToRead(filename);
5002 bool removeFile = false;
5003
5004 if (imageType == -1)
5005 return false; // Could not determine image type
5006
5007 if ((imageType != wxBITMAP_TYPE_JPEG) && convertToJPEG)
5008 {
5009 wxString tempFile;
5010 bool success = wxGetTempFileName(_("image"), tempFile) ;
5011
5012 wxASSERT(success);
5013
5014 wxUnusedVar(success);
5015
5016 image.SaveFile(tempFile, wxBITMAP_TYPE_JPEG);
5017 filenameToRead = tempFile;
5018 removeFile = true;
5019
5020 m_imageType = wxBITMAP_TYPE_JPEG;
5021 }
5022 wxFile file;
5023 if (!file.Open(filenameToRead))
5024 return false;
5025
5026 m_dataSize = (size_t) file.Length();
5027 file.Close();
5028
5029 if (m_data)
5030 delete[] m_data;
5031 m_data = ReadBlock(filenameToRead, m_dataSize);
5032
5033 if (removeFile)
5034 wxRemoveFile(filenameToRead);
5035
5036 return (m_data != NULL);
5037 }
5038
5039 // Make an image block from the wxImage in the given
5040 // format.
5041 bool wxRichTextImageBlock::MakeImageBlock(wxImage& image, int imageType, int quality)
5042 {
5043 m_imageType = imageType;
5044 image.SetOption(wxT("quality"), quality);
5045
5046 if (imageType == -1)
5047 return false; // Could not determine image type
5048
5049 wxString tempFile;
5050 bool success = wxGetTempFileName(_("image"), tempFile) ;
5051
5052 wxASSERT(success);
5053 wxUnusedVar(success);
5054
5055 if (!image.SaveFile(tempFile, m_imageType))
5056 {
5057 if (wxFileExists(tempFile))
5058 wxRemoveFile(tempFile);
5059 return false;
5060 }
5061
5062 wxFile file;
5063 if (!file.Open(tempFile))
5064 return false;
5065
5066 m_dataSize = (size_t) file.Length();
5067 file.Close();
5068
5069 if (m_data)
5070 delete[] m_data;
5071 m_data = ReadBlock(tempFile, m_dataSize);
5072
5073 wxRemoveFile(tempFile);
5074
5075 return (m_data != NULL);
5076 }
5077
5078
5079 // Write to a file
5080 bool wxRichTextImageBlock::Write(const wxString& filename)
5081 {
5082 return WriteBlock(filename, m_data, m_dataSize);
5083 }
5084
5085 void wxRichTextImageBlock::Copy(const wxRichTextImageBlock& block)
5086 {
5087 m_imageType = block.m_imageType;
5088 if (m_data)
5089 {
5090 delete[] m_data;
5091 m_data = NULL;
5092 }
5093 m_dataSize = block.m_dataSize;
5094 if (m_dataSize == 0)
5095 return;
5096
5097 m_data = new unsigned char[m_dataSize];
5098 unsigned int i;
5099 for (i = 0; i < m_dataSize; i++)
5100 m_data[i] = block.m_data[i];
5101 }
5102
5103 //// Operators
5104 void wxRichTextImageBlock::operator=(const wxRichTextImageBlock& block)
5105 {
5106 Copy(block);
5107 }
5108
5109 // Load a wxImage from the block
5110 bool wxRichTextImageBlock::Load(wxImage& image)
5111 {
5112 if (!m_data)
5113 return false;
5114
5115 // Read in the image.
5116 #if 1
5117 wxMemoryInputStream mstream(m_data, m_dataSize);
5118 bool success = image.LoadFile(mstream, GetImageType());
5119 #else
5120 wxString tempFile;
5121 bool success = wxGetTempFileName(_("image"), tempFile) ;
5122 wxASSERT(success);
5123
5124 if (!WriteBlock(tempFile, m_data, m_dataSize))
5125 {
5126 return false;
5127 }
5128 success = image.LoadFile(tempFile, GetImageType());
5129 wxRemoveFile(tempFile);
5130 #endif
5131
5132 return success;
5133 }
5134
5135 // Write data in hex to a stream
5136 bool wxRichTextImageBlock::WriteHex(wxOutputStream& stream)
5137 {
5138 wxString hex;
5139 int i;
5140 for (i = 0; i < (int) m_dataSize; i++)
5141 {
5142 hex = wxDecToHex(m_data[i]);
5143 wxCharBuffer buf = hex.ToAscii();
5144
5145 stream.Write((const char*) buf, hex.Length());
5146 }
5147
5148 return true;
5149 }
5150
5151 // Read data in hex from a stream
5152 bool wxRichTextImageBlock::ReadHex(wxInputStream& stream, int length, int imageType)
5153 {
5154 int dataSize = length/2;
5155
5156 if (m_data)
5157 delete[] m_data;
5158
5159 wxString str(wxT(" "));
5160 m_data = new unsigned char[dataSize];
5161 int i;
5162 for (i = 0; i < dataSize; i ++)
5163 {
5164 str[0] = stream.GetC();
5165 str[1] = stream.GetC();
5166
5167 m_data[i] = (unsigned char)wxHexToDec(str);
5168 }
5169
5170 m_dataSize = dataSize;
5171 m_imageType = imageType;
5172
5173 return true;
5174 }
5175
5176
5177 // Allocate and read from stream as a block of memory
5178 unsigned char* wxRichTextImageBlock::ReadBlock(wxInputStream& stream, size_t size)
5179 {
5180 unsigned char* block = new unsigned char[size];
5181 if (!block)
5182 return NULL;
5183
5184 stream.Read(block, size);
5185
5186 return block;
5187 }
5188
5189 unsigned char* wxRichTextImageBlock::ReadBlock(const wxString& filename, size_t size)
5190 {
5191 wxFileInputStream stream(filename);
5192 if (!stream.Ok())
5193 return NULL;
5194
5195 return ReadBlock(stream, size);
5196 }
5197
5198 // Write memory block to stream
5199 bool wxRichTextImageBlock::WriteBlock(wxOutputStream& stream, unsigned char* block, size_t size)
5200 {
5201 stream.Write((void*) block, size);
5202 return stream.IsOk();
5203
5204 }
5205
5206 // Write memory block to file
5207 bool wxRichTextImageBlock::WriteBlock(const wxString& filename, unsigned char* block, size_t size)
5208 {
5209 wxFileOutputStream outStream(filename);
5210 if (!outStream.Ok())
5211 return false;
5212
5213 return WriteBlock(outStream, block, size);
5214 }
5215
5216 #endif
5217 // wxUSE_RICHTEXT