1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/richtext/richtextbuffer.cpp
3 // Purpose: Buffer for wxRichTextCtrl
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // For compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
21 #include "wx/richtext/richtextbuffer.h"
27 #include "wx/dataobj.h"
28 #include "wx/module.h"
31 #include "wx/settings.h"
32 #include "wx/filename.h"
33 #include "wx/clipbrd.h"
34 #include "wx/wfstream.h"
35 #include "wx/mstream.h"
36 #include "wx/sstream.h"
37 #include "wx/textfile.h"
38 #include "wx/hashmap.h"
40 #include "wx/richtext/richtextctrl.h"
41 #include "wx/richtext/richtextstyles.h"
43 #include "wx/listimpl.cpp"
45 WX_DEFINE_LIST(wxRichTextObjectList
)
46 WX_DEFINE_LIST(wxRichTextLineList
)
48 // Switch off if the platform doesn't like it for some reason
49 #define wxRICHTEXT_USE_OPTIMIZED_DRAWING 1
51 // Use GetPartialTextExtents for platforms that support it natively
52 #define wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS 1
54 const wxChar wxRichTextLineBreakChar
= (wxChar
) 29;
56 // Helpers for efficiency
58 inline void wxCheckSetFont(wxDC
& dc
, const wxFont
& font
)
60 const wxFont
& font1
= dc
.GetFont();
61 if (font1
.IsOk() && font
.IsOk())
63 if (font1
.GetPointSize() == font
.GetPointSize() &&
64 font1
.GetFamily() == font
.GetFamily() &&
65 font1
.GetStyle() == font
.GetStyle() &&
66 font1
.GetWeight() == font
.GetWeight() &&
67 font1
.GetUnderlined() == font
.GetUnderlined() &&
68 font1
.GetFaceName() == font
.GetFaceName())
74 inline void wxCheckSetPen(wxDC
& dc
, const wxPen
& pen
)
76 const wxPen
& pen1
= dc
.GetPen();
77 if (pen1
.IsOk() && pen
.IsOk())
79 if (pen1
.GetWidth() == pen
.GetWidth() &&
80 pen1
.GetStyle() == pen
.GetStyle() &&
81 pen1
.GetColour() == pen
.GetColour())
87 inline void wxCheckSetBrush(wxDC
& dc
, const wxBrush
& brush
)
89 const wxBrush
& brush1
= dc
.GetBrush();
90 if (brush1
.IsOk() && brush
.IsOk())
92 if (brush1
.GetStyle() == brush
.GetStyle() &&
93 brush1
.GetColour() == brush
.GetColour())
101 * This is the base for drawable objects.
104 IMPLEMENT_CLASS(wxRichTextObject
, wxObject
)
106 wxRichTextObject::wxRichTextObject(wxRichTextObject
* parent
)
118 wxRichTextObject::~wxRichTextObject()
122 void wxRichTextObject::Dereference()
130 void wxRichTextObject::Copy(const wxRichTextObject
& obj
)
134 m_dirty
= obj
.m_dirty
;
135 m_range
= obj
.m_range
;
136 m_attributes
= obj
.m_attributes
;
137 m_descent
= obj
.m_descent
;
140 void wxRichTextObject::SetMargins(int margin
)
142 m_leftMargin
= m_rightMargin
= m_topMargin
= m_bottomMargin
= margin
;
145 void wxRichTextObject::SetMargins(int leftMargin
, int rightMargin
, int topMargin
, int bottomMargin
)
147 m_leftMargin
= leftMargin
;
148 m_rightMargin
= rightMargin
;
149 m_topMargin
= topMargin
;
150 m_bottomMargin
= bottomMargin
;
153 // Convert units in tenths of a millimetre to device units
154 int wxRichTextObject::ConvertTenthsMMToPixels(wxDC
& dc
, int units
)
156 int p
= ConvertTenthsMMToPixels(dc
.GetPPI().x
, units
);
159 wxRichTextBuffer
* buffer
= GetBuffer();
161 p
= (int) ((double)p
/ buffer
->GetScale());
165 // Convert units in tenths of a millimetre to device units
166 int wxRichTextObject::ConvertTenthsMMToPixels(int ppi
, int units
)
168 // There are ppi pixels in 254.1 "1/10 mm"
170 double pixels
= ((double) units
* (double)ppi
) / 254.1;
175 /// Dump to output stream for debugging
176 void wxRichTextObject::Dump(wxTextOutputStream
& stream
)
178 stream
<< GetClassInfo()->GetClassName() << wxT("\n");
179 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");
180 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");
183 /// Gets the containing buffer
184 wxRichTextBuffer
* wxRichTextObject::GetBuffer() const
186 const wxRichTextObject
* obj
= this;
187 while (obj
&& !obj
->IsKindOf(CLASSINFO(wxRichTextBuffer
)))
188 obj
= obj
->GetParent();
189 return wxDynamicCast(obj
, wxRichTextBuffer
);
193 * wxRichTextCompositeObject
194 * This is the base for drawable objects.
197 IMPLEMENT_CLASS(wxRichTextCompositeObject
, wxRichTextObject
)
199 wxRichTextCompositeObject::wxRichTextCompositeObject(wxRichTextObject
* parent
):
200 wxRichTextObject(parent
)
204 wxRichTextCompositeObject::~wxRichTextCompositeObject()
209 /// Get the nth child
210 wxRichTextObject
* wxRichTextCompositeObject::GetChild(size_t n
) const
212 wxASSERT ( n
< m_children
.GetCount() );
214 return m_children
.Item(n
)->GetData();
217 /// Append a child, returning the position
218 size_t wxRichTextCompositeObject::AppendChild(wxRichTextObject
* child
)
220 m_children
.Append(child
);
221 child
->SetParent(this);
222 return m_children
.GetCount() - 1;
225 /// Insert the child in front of the given object, or at the beginning
226 bool wxRichTextCompositeObject::InsertChild(wxRichTextObject
* child
, wxRichTextObject
* inFrontOf
)
230 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(inFrontOf
);
231 m_children
.Insert(node
, child
);
234 m_children
.Insert(child
);
235 child
->SetParent(this);
241 bool wxRichTextCompositeObject::RemoveChild(wxRichTextObject
* child
, bool deleteChild
)
243 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(child
);
246 wxRichTextObject
* obj
= node
->GetData();
247 m_children
.Erase(node
);
256 /// Delete all children
257 bool wxRichTextCompositeObject::DeleteChildren()
259 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
262 wxRichTextObjectList::compatibility_iterator oldNode
= node
;
264 wxRichTextObject
* child
= node
->GetData();
265 child
->Dereference(); // Only delete if reference count is zero
267 node
= node
->GetNext();
268 m_children
.Erase(oldNode
);
274 /// Get the child count
275 size_t wxRichTextCompositeObject::GetChildCount() const
277 return m_children
.GetCount();
281 void wxRichTextCompositeObject::Copy(const wxRichTextCompositeObject
& obj
)
283 wxRichTextObject::Copy(obj
);
287 wxRichTextObjectList::compatibility_iterator node
= obj
.m_children
.GetFirst();
290 wxRichTextObject
* child
= node
->GetData();
291 wxRichTextObject
* newChild
= child
->Clone();
292 newChild
->SetParent(this);
293 m_children
.Append(newChild
);
295 node
= node
->GetNext();
299 /// Hit-testing: returns a flag indicating hit test details, plus
300 /// information about position
301 int wxRichTextCompositeObject::HitTest(wxDC
& dc
, const wxPoint
& pt
, long& textPosition
)
303 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
306 wxRichTextObject
* child
= node
->GetData();
308 int ret
= child
->HitTest(dc
, pt
, textPosition
);
309 if (ret
!= wxRICHTEXT_HITTEST_NONE
)
312 node
= node
->GetNext();
315 textPosition
= GetRange().GetEnd()-1;
316 return wxRICHTEXT_HITTEST_AFTER
|wxRICHTEXT_HITTEST_OUTSIDE
;
319 /// Finds the absolute position and row height for the given character position
320 bool wxRichTextCompositeObject::FindPosition(wxDC
& dc
, long index
, wxPoint
& pt
, int* height
, bool forceLineStart
)
322 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
325 wxRichTextObject
* child
= node
->GetData();
327 if (child
->FindPosition(dc
, index
, pt
, height
, forceLineStart
))
330 node
= node
->GetNext();
337 void wxRichTextCompositeObject::CalculateRange(long start
, long& end
)
339 long current
= start
;
340 long lastEnd
= current
;
342 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
345 wxRichTextObject
* child
= node
->GetData();
348 child
->CalculateRange(current
, childEnd
);
351 current
= childEnd
+ 1;
353 node
= node
->GetNext();
358 // An object with no children has zero length
359 if (m_children
.GetCount() == 0)
362 m_range
.SetRange(start
, end
);
365 /// Delete range from layout.
366 bool wxRichTextCompositeObject::DeleteRange(const wxRichTextRange
& range
)
368 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
372 wxRichTextObject
* obj
= (wxRichTextObject
*) node
->GetData();
373 wxRichTextObjectList::compatibility_iterator next
= node
->GetNext();
375 // Delete the range in each paragraph
377 // When a chunk has been deleted, internally the content does not
378 // now match the ranges.
379 // However, so long as deletion is not done on the same object twice this is OK.
380 // If you may delete content from the same object twice, recalculate
381 // the ranges inbetween DeleteRange calls by calling CalculateRanges, and
382 // adjust the range you're deleting accordingly.
384 if (!obj
->GetRange().IsOutside(range
))
386 obj
->DeleteRange(range
);
388 // Delete an empty object, or paragraph within this range.
389 if (obj
->IsEmpty() ||
390 (range
.GetStart() <= obj
->GetRange().GetStart() && range
.GetEnd() >= obj
->GetRange().GetEnd()))
392 // An empty paragraph has length 1, so won't be deleted unless the
393 // whole range is deleted.
394 RemoveChild(obj
, true);
404 /// Get any text in this object for the given range
405 wxString
wxRichTextCompositeObject::GetTextForRange(const wxRichTextRange
& range
) const
408 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
411 wxRichTextObject
* child
= node
->GetData();
412 wxRichTextRange childRange
= range
;
413 if (!child
->GetRange().IsOutside(range
))
415 childRange
.LimitTo(child
->GetRange());
417 wxString childText
= child
->GetTextForRange(childRange
);
421 node
= node
->GetNext();
427 /// Recursively merge all pieces that can be merged.
428 bool wxRichTextCompositeObject::Defragment(const wxRichTextRange
& range
)
430 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
433 wxRichTextObject
* child
= node
->GetData();
434 if (!child
->GetRange().IsOutside(range
))
436 wxRichTextCompositeObject
* composite
= wxDynamicCast(child
, wxRichTextCompositeObject
);
438 composite
->Defragment();
442 wxRichTextObject
* nextChild
= node
->GetNext()->GetData();
443 if (child
->CanMerge(nextChild
) && child
->Merge(nextChild
))
445 nextChild
->Dereference();
446 m_children
.Erase(node
->GetNext());
448 // Don't set node -- we'll see if we can merge again with the next
452 node
= node
->GetNext();
455 node
= node
->GetNext();
458 node
= node
->GetNext();
464 /// Dump to output stream for debugging
465 void wxRichTextCompositeObject::Dump(wxTextOutputStream
& stream
)
467 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
470 wxRichTextObject
* child
= node
->GetData();
472 node
= node
->GetNext();
479 * This defines a 2D space to lay out objects
482 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBox
, wxRichTextCompositeObject
)
484 wxRichTextBox::wxRichTextBox(wxRichTextObject
* parent
):
485 wxRichTextCompositeObject(parent
)
490 bool wxRichTextBox::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& WXUNUSED(rect
), int descent
, int style
)
492 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
495 wxRichTextObject
* child
= node
->GetData();
497 wxRect childRect
= wxRect(child
->GetPosition(), child
->GetCachedSize());
498 child
->Draw(dc
, range
, selectionRange
, childRect
, descent
, style
);
500 node
= node
->GetNext();
506 bool wxRichTextBox::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
508 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
511 wxRichTextObject
* child
= node
->GetData();
512 child
->Layout(dc
, rect
, style
);
514 node
= node
->GetNext();
520 /// Get/set the size for the given range. Assume only has one child.
521 bool wxRichTextBox::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
, wxArrayInt
* partialExtents
) const
523 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
526 wxRichTextObject
* child
= node
->GetData();
527 return child
->GetRangeSize(range
, size
, descent
, dc
, flags
, position
, partialExtents
);
534 void wxRichTextBox::Copy(const wxRichTextBox
& obj
)
536 wxRichTextCompositeObject::Copy(obj
);
541 * wxRichTextParagraphLayoutBox
542 * This box knows how to lay out paragraphs.
545 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraphLayoutBox
, wxRichTextBox
)
547 wxRichTextParagraphLayoutBox::wxRichTextParagraphLayoutBox(wxRichTextObject
* parent
):
548 wxRichTextBox(parent
)
553 /// Initialize the object.
554 void wxRichTextParagraphLayoutBox::Init()
558 // For now, assume is the only box and has no initial size.
559 m_range
= wxRichTextRange(0, -1);
561 m_invalidRange
.SetRange(-1, -1);
566 m_partialParagraph
= false;
570 bool wxRichTextParagraphLayoutBox::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int descent
, int style
)
572 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
575 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
576 wxASSERT (child
!= NULL
);
578 if (child
&& !child
->GetRange().IsOutside(range
))
580 wxRect
childRect(child
->GetPosition(), child
->GetCachedSize());
582 if (((style
& wxRICHTEXT_DRAW_IGNORE_CACHE
) == 0) && childRect
.GetTop() > rect
.GetBottom())
587 else if (((style
& wxRICHTEXT_DRAW_IGNORE_CACHE
) == 0) && childRect
.GetBottom() < rect
.GetTop())
592 child
->Draw(dc
, range
, selectionRange
, rect
, descent
, style
);
595 node
= node
->GetNext();
601 bool wxRichTextParagraphLayoutBox::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
603 wxRect availableSpace
;
604 bool formatRect
= (style
& wxRICHTEXT_LAYOUT_SPECIFIED_RECT
) == wxRICHTEXT_LAYOUT_SPECIFIED_RECT
;
606 // If only laying out a specific area, the passed rect has a different meaning:
607 // the visible part of the buffer. This is used in wxRichTextCtrl::OnSize,
608 // so that during a size, only the visible part will be relaid out, or
609 // it would take too long causing flicker. As an approximation, we assume that
610 // everything up to the start of the visible area is laid out correctly.
613 availableSpace
= wxRect(0 + m_leftMargin
,
615 rect
.width
- m_leftMargin
- m_rightMargin
,
618 // Invalidate the part of the buffer from the first visible line
619 // to the end. If other parts of the buffer are currently invalid,
620 // then they too will be taken into account if they are above
621 // the visible point.
623 wxRichTextLine
* line
= GetLineAtYPosition(rect
.y
);
625 startPos
= line
->GetAbsoluteRange().GetStart();
627 Invalidate(wxRichTextRange(startPos
, GetRange().GetEnd()));
630 availableSpace
= wxRect(rect
.x
+ m_leftMargin
,
631 rect
.y
+ m_topMargin
,
632 rect
.width
- m_leftMargin
- m_rightMargin
,
633 rect
.height
- m_topMargin
- m_bottomMargin
);
637 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
639 bool layoutAll
= true;
641 // Get invalid range, rounding to paragraph start/end.
642 wxRichTextRange invalidRange
= GetInvalidRange(true);
644 if (invalidRange
== wxRICHTEXT_NONE
&& !formatRect
)
647 if (invalidRange
== wxRICHTEXT_ALL
)
649 else // If we know what range is affected, start laying out from that point on.
650 if (invalidRange
.GetStart() >= GetRange().GetStart())
652 wxRichTextParagraph
* firstParagraph
= GetParagraphAtPosition(invalidRange
.GetStart());
655 wxRichTextObjectList::compatibility_iterator firstNode
= m_children
.Find(firstParagraph
);
656 wxRichTextObjectList::compatibility_iterator previousNode
;
658 previousNode
= firstNode
->GetPrevious();
663 wxRichTextParagraph
* previousParagraph
= wxDynamicCast(previousNode
->GetData(), wxRichTextParagraph
);
664 availableSpace
.y
= previousParagraph
->GetPosition().y
+ previousParagraph
->GetCachedSize().y
;
667 // Now we're going to start iterating from the first affected paragraph.
675 // A way to force speedy rest-of-buffer layout (the 'else' below)
676 bool forceQuickLayout
= false;
680 // Assume this box only contains paragraphs
682 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
683 wxCHECK_MSG( child
, false, _T("Unknown object in layout") );
685 // TODO: what if the child hasn't been laid out (e.g. involved in Undo) but still has 'old' lines
686 if ( !forceQuickLayout
&&
688 child
->GetLines().IsEmpty() ||
689 !child
->GetRange().IsOutside(invalidRange
)) )
691 child
->Layout(dc
, availableSpace
, style
);
693 // Layout must set the cached size
694 availableSpace
.y
+= child
->GetCachedSize().y
;
695 maxWidth
= wxMax(maxWidth
, child
->GetCachedSize().x
);
697 // If we're just formatting the visible part of the buffer,
698 // and we're now past the bottom of the window, start quick
700 if (formatRect
&& child
->GetPosition().y
> rect
.GetBottom())
701 forceQuickLayout
= true;
705 // We're outside the immediately affected range, so now let's just
706 // move everything up or down. This assumes that all the children have previously
707 // been laid out and have wrapped line lists associated with them.
708 // TODO: check all paragraphs before the affected range.
710 int inc
= availableSpace
.y
- child
->GetPosition().y
;
714 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
717 if (child
->GetLines().GetCount() == 0)
718 child
->Layout(dc
, availableSpace
, style
);
720 child
->SetPosition(wxPoint(child
->GetPosition().x
, child
->GetPosition().y
+ inc
));
722 availableSpace
.y
+= child
->GetCachedSize().y
;
723 maxWidth
= wxMax(maxWidth
, child
->GetCachedSize().x
);
726 node
= node
->GetNext();
731 node
= node
->GetNext();
734 SetCachedSize(wxSize(maxWidth
, availableSpace
.y
));
737 m_invalidRange
= wxRICHTEXT_NONE
;
743 void wxRichTextParagraphLayoutBox::Copy(const wxRichTextParagraphLayoutBox
& obj
)
745 wxRichTextBox::Copy(obj
);
747 m_partialParagraph
= obj
.m_partialParagraph
;
748 m_defaultAttributes
= obj
.m_defaultAttributes
;
751 /// Get/set the size for the given range.
752 bool wxRichTextParagraphLayoutBox::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
, wxArrayInt
* WXUNUSED(partialExtents
)) const
756 wxRichTextObjectList::compatibility_iterator startPara
= wxRichTextObjectList::compatibility_iterator();
757 wxRichTextObjectList::compatibility_iterator endPara
= wxRichTextObjectList::compatibility_iterator();
759 // First find the first paragraph whose starting position is within the range.
760 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
763 // child is a paragraph
764 wxRichTextObject
* child
= node
->GetData();
765 const wxRichTextRange
& r
= child
->GetRange();
767 if (r
.GetStart() <= range
.GetStart() && r
.GetEnd() >= range
.GetStart())
773 node
= node
->GetNext();
776 // Next find the last paragraph containing part of the range
777 node
= m_children
.GetFirst();
780 // child is a paragraph
781 wxRichTextObject
* child
= node
->GetData();
782 const wxRichTextRange
& r
= child
->GetRange();
784 if (r
.GetStart() <= range
.GetEnd() && r
.GetEnd() >= range
.GetEnd())
790 node
= node
->GetNext();
793 if (!startPara
|| !endPara
)
796 // Now we can add up the sizes
797 for (node
= startPara
; node
; node
= node
->GetNext())
799 // child is a paragraph
800 wxRichTextObject
* child
= node
->GetData();
801 const wxRichTextRange
& childRange
= child
->GetRange();
802 wxRichTextRange rangeToFind
= range
;
803 rangeToFind
.LimitTo(childRange
);
807 int childDescent
= 0;
808 child
->GetRangeSize(rangeToFind
, childSize
, childDescent
, dc
, flags
, position
);
810 descent
= wxMax(childDescent
, descent
);
812 sz
.x
= wxMax(sz
.x
, childSize
.x
);
824 /// Get the paragraph at the given position
825 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphAtPosition(long pos
, bool caretPosition
) const
830 // First find the first paragraph whose starting position is within the range.
831 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
834 // child is a paragraph
835 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
836 wxASSERT (child
!= NULL
);
838 // Return first child in buffer if position is -1
842 if (child
->GetRange().Contains(pos
))
845 node
= node
->GetNext();
850 /// Get the line at the given position
851 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineAtPosition(long pos
, bool caretPosition
) const
856 // First find the first paragraph whose starting position is within the range.
857 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
860 wxRichTextObject
* obj
= (wxRichTextObject
*) node
->GetData();
861 if (obj
->GetRange().Contains(pos
))
863 // child is a paragraph
864 wxRichTextParagraph
* child
= wxDynamicCast(obj
, wxRichTextParagraph
);
865 wxASSERT (child
!= NULL
);
867 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
870 wxRichTextLine
* line
= node2
->GetData();
872 wxRichTextRange range
= line
->GetAbsoluteRange();
874 if (range
.Contains(pos
) ||
876 // If the position is end-of-paragraph, then return the last line of
878 ((range
.GetEnd() == child
->GetRange().GetEnd()-1) && (pos
== child
->GetRange().GetEnd())))
881 node2
= node2
->GetNext();
885 node
= node
->GetNext();
888 int lineCount
= GetLineCount();
890 return GetLineForVisibleLineNumber(lineCount
-1);
895 /// Get the line at the given y pixel position, or the last line.
896 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineAtYPosition(int y
) const
898 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
901 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
902 wxASSERT (child
!= NULL
);
904 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
907 wxRichTextLine
* line
= node2
->GetData();
909 wxRect
rect(line
->GetRect());
911 if (y
<= rect
.GetBottom())
914 node2
= node2
->GetNext();
917 node
= node
->GetNext();
921 int lineCount
= GetLineCount();
923 return GetLineForVisibleLineNumber(lineCount
-1);
928 /// Get the number of visible lines
929 int wxRichTextParagraphLayoutBox::GetLineCount() const
933 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
936 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
937 wxASSERT (child
!= NULL
);
939 count
+= child
->GetLines().GetCount();
940 node
= node
->GetNext();
946 /// Get the paragraph for a given line
947 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphForLine(wxRichTextLine
* line
) const
949 return GetParagraphAtPosition(line
->GetAbsoluteRange().GetStart());
952 /// Get the line size at the given position
953 wxSize
wxRichTextParagraphLayoutBox::GetLineSizeAtPosition(long pos
, bool caretPosition
) const
955 wxRichTextLine
* line
= GetLineAtPosition(pos
, caretPosition
);
958 return line
->GetSize();
965 /// Convenience function to add a paragraph of text
966 wxRichTextRange
wxRichTextParagraphLayoutBox::AddParagraph(const wxString
& text
, wxTextAttr
* paraStyle
)
968 // Don't use the base style, just the default style, and the base style will
969 // be combined at display time.
970 // Divide into paragraph and character styles.
972 wxTextAttr defaultCharStyle
;
973 wxTextAttr defaultParaStyle
;
975 // If the default style is a named paragraph style, don't apply any character formatting
976 // to the initial text string.
977 if (GetDefaultStyle().HasParagraphStyleName() && GetStyleSheet())
979 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(GetDefaultStyle().GetParagraphStyleName());
981 defaultParaStyle
= def
->GetStyleMergedWithBase(GetStyleSheet());
984 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
986 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
987 wxTextAttr
* cStyle
= & defaultCharStyle
;
989 wxRichTextParagraph
* para
= new wxRichTextParagraph(text
, this, pStyle
, cStyle
);
996 return para
->GetRange();
999 /// Adds multiple paragraphs, based on newlines.
1000 wxRichTextRange
wxRichTextParagraphLayoutBox::AddParagraphs(const wxString
& text
, wxTextAttr
* paraStyle
)
1002 // Don't use the base style, just the default style, and the base style will
1003 // be combined at display time.
1004 // Divide into paragraph and character styles.
1006 wxTextAttr defaultCharStyle
;
1007 wxTextAttr defaultParaStyle
;
1009 // If the default style is a named paragraph style, don't apply any character formatting
1010 // to the initial text string.
1011 if (GetDefaultStyle().HasParagraphStyleName() && GetStyleSheet())
1013 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(GetDefaultStyle().GetParagraphStyleName());
1015 defaultParaStyle
= def
->GetStyleMergedWithBase(GetStyleSheet());
1018 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
1020 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
1021 wxTextAttr
* cStyle
= & defaultCharStyle
;
1023 wxRichTextParagraph
* firstPara
= NULL
;
1024 wxRichTextParagraph
* lastPara
= NULL
;
1026 wxRichTextRange
range(-1, -1);
1029 size_t len
= text
.length();
1031 wxRichTextParagraph
* para
= new wxRichTextParagraph(wxEmptyString
, this, pStyle
, cStyle
);
1040 wxChar ch
= text
[i
];
1041 if (ch
== wxT('\n') || ch
== wxT('\r'))
1045 wxRichTextPlainText
* plainText
= (wxRichTextPlainText
*) para
->GetChildren().GetFirst()->GetData();
1046 plainText
->SetText(line
);
1048 para
= new wxRichTextParagraph(wxEmptyString
, this, pStyle
, cStyle
);
1053 line
= wxEmptyString
;
1064 wxRichTextPlainText
* plainText
= (wxRichTextPlainText
*) para
->GetChildren().GetFirst()->GetData();
1065 plainText
->SetText(line
);
1072 return wxRichTextRange(firstPara
->GetRange().GetStart(), lastPara
->GetRange().GetEnd());
1075 /// Convenience function to add an image
1076 wxRichTextRange
wxRichTextParagraphLayoutBox::AddImage(const wxImage
& image
, wxTextAttr
* paraStyle
)
1078 // Don't use the base style, just the default style, and the base style will
1079 // be combined at display time.
1080 // Divide into paragraph and character styles.
1082 wxTextAttr defaultCharStyle
;
1083 wxTextAttr defaultParaStyle
;
1085 // If the default style is a named paragraph style, don't apply any character formatting
1086 // to the initial text string.
1087 if (GetDefaultStyle().HasParagraphStyleName() && GetStyleSheet())
1089 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(GetDefaultStyle().GetParagraphStyleName());
1091 defaultParaStyle
= def
->GetStyleMergedWithBase(GetStyleSheet());
1094 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
1096 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
1097 wxTextAttr
* cStyle
= & defaultCharStyle
;
1099 wxRichTextParagraph
* para
= new wxRichTextParagraph(this, pStyle
);
1101 para
->AppendChild(new wxRichTextImage(image
, this, cStyle
));
1106 return para
->GetRange();
1110 /// Insert fragment into this box at the given position. If partialParagraph is true,
1111 /// it is assumed that the last (or only) paragraph is just a piece of data with no paragraph
1114 bool wxRichTextParagraphLayoutBox::InsertFragment(long position
, wxRichTextParagraphLayoutBox
& fragment
)
1118 // First, find the first paragraph whose starting position is within the range.
1119 wxRichTextParagraph
* para
= GetParagraphAtPosition(position
);
1122 wxTextAttrEx originalAttr
= para
->GetAttributes();
1124 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(para
);
1126 // Now split at this position, returning the object to insert the new
1127 // ones in front of.
1128 wxRichTextObject
* nextObject
= para
->SplitAt(position
);
1130 // Special case: partial paragraph, just one paragraph. Might be a small amount of
1131 // text, for example, so let's optimize.
1133 if (fragment
.GetPartialParagraph() && fragment
.GetChildren().GetCount() == 1)
1135 // Add the first para to this para...
1136 wxRichTextObjectList::compatibility_iterator firstParaNode
= fragment
.GetChildren().GetFirst();
1140 // Iterate through the fragment paragraph inserting the content into this paragraph.
1141 wxRichTextParagraph
* firstPara
= wxDynamicCast(firstParaNode
->GetData(), wxRichTextParagraph
);
1142 wxASSERT (firstPara
!= NULL
);
1144 wxRichTextObjectList::compatibility_iterator objectNode
= firstPara
->GetChildren().GetFirst();
1147 wxRichTextObject
* newObj
= objectNode
->GetData()->Clone();
1152 para
->AppendChild(newObj
);
1156 // Insert before nextObject
1157 para
->InsertChild(newObj
, nextObject
);
1160 objectNode
= objectNode
->GetNext();
1167 // Procedure for inserting a fragment consisting of a number of
1170 // 1. Remove and save the content that's after the insertion point, for adding
1171 // back once we've added the fragment.
1172 // 2. Add the content from the first fragment paragraph to the current
1174 // 3. Add remaining fragment paragraphs after the current paragraph.
1175 // 4. Add back the saved content from the first paragraph. If partialParagraph
1176 // is true, add it to the last paragraph added and not a new one.
1178 // 1. Remove and save objects after split point.
1179 wxList savedObjects
;
1181 para
->MoveToList(nextObject
, savedObjects
);
1183 // 2. Add the content from the 1st fragment paragraph.
1184 wxRichTextObjectList::compatibility_iterator firstParaNode
= fragment
.GetChildren().GetFirst();
1188 wxRichTextParagraph
* firstPara
= wxDynamicCast(firstParaNode
->GetData(), wxRichTextParagraph
);
1189 wxASSERT(firstPara
!= NULL
);
1191 if (!(fragment
.GetAttributes().GetFlags() & wxTEXT_ATTR_KEEP_FIRST_PARA_STYLE
))
1192 para
->SetAttributes(firstPara
->GetAttributes());
1194 // Save empty paragraph attributes for appending later
1195 // These are character attributes deliberately set for a new paragraph. Without this,
1196 // we couldn't pass default attributes when appending a new paragraph.
1197 wxTextAttrEx emptyParagraphAttributes
;
1199 wxRichTextObjectList::compatibility_iterator objectNode
= firstPara
->GetChildren().GetFirst();
1201 if (objectNode
&& firstPara
->GetChildren().GetCount() == 1 && objectNode
->GetData()->IsEmpty())
1202 emptyParagraphAttributes
= objectNode
->GetData()->GetAttributes();
1206 wxRichTextObject
* newObj
= objectNode
->GetData()->Clone();
1209 para
->AppendChild(newObj
);
1211 objectNode
= objectNode
->GetNext();
1214 // 3. Add remaining fragment paragraphs after the current paragraph.
1215 wxRichTextObjectList::compatibility_iterator nextParagraphNode
= node
->GetNext();
1216 wxRichTextObject
* nextParagraph
= NULL
;
1217 if (nextParagraphNode
)
1218 nextParagraph
= nextParagraphNode
->GetData();
1220 wxRichTextObjectList::compatibility_iterator i
= fragment
.GetChildren().GetFirst()->GetNext();
1221 wxRichTextParagraph
* finalPara
= para
;
1223 bool needExtraPara
= (!i
|| !fragment
.GetPartialParagraph());
1225 // If there was only one paragraph, we need to insert a new one.
1228 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1229 wxASSERT( para
!= NULL
);
1231 finalPara
= (wxRichTextParagraph
*) para
->Clone();
1234 InsertChild(finalPara
, nextParagraph
);
1236 AppendChild(finalPara
);
1241 // If there was only one paragraph, or we have full paragraphs in our fragment,
1242 // we need to insert a new one.
1245 finalPara
= new wxRichTextParagraph
;
1248 InsertChild(finalPara
, nextParagraph
);
1250 AppendChild(finalPara
);
1253 // 4. Add back the remaining content.
1257 finalPara
->MoveFromList(savedObjects
);
1259 // Ensure there's at least one object
1260 if (finalPara
->GetChildCount() == 0)
1262 wxRichTextPlainText
* text
= new wxRichTextPlainText(wxEmptyString
);
1263 text
->SetAttributes(emptyParagraphAttributes
);
1265 finalPara
->AppendChild(text
);
1269 if ((fragment
.GetAttributes().GetFlags() & wxTEXT_ATTR_KEEP_FIRST_PARA_STYLE
) && firstPara
)
1270 finalPara
->SetAttributes(firstPara
->GetAttributes());
1271 else if (finalPara
&& finalPara
!= para
)
1272 finalPara
->SetAttributes(originalAttr
);
1280 wxRichTextObjectList::compatibility_iterator i
= fragment
.GetChildren().GetFirst();
1283 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1284 wxASSERT( para
!= NULL
);
1286 AppendChild(para
->Clone());
1295 /// Make a copy of the fragment corresponding to the given range, putting it in 'fragment'.
1296 /// If there was an incomplete paragraph at the end, partialParagraph is set to true.
1297 bool wxRichTextParagraphLayoutBox::CopyFragment(const wxRichTextRange
& range
, wxRichTextParagraphLayoutBox
& fragment
)
1299 wxRichTextObjectList::compatibility_iterator i
= GetChildren().GetFirst();
1302 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1303 wxASSERT( para
!= NULL
);
1305 if (!para
->GetRange().IsOutside(range
))
1307 fragment
.AppendChild(para
->Clone());
1312 // Now top and tail the first and last paragraphs in our new fragment (which might be the same).
1313 if (!fragment
.IsEmpty())
1315 wxRichTextRange
topTailRange(range
);
1317 wxRichTextParagraph
* firstPara
= wxDynamicCast(fragment
.GetChildren().GetFirst()->GetData(), wxRichTextParagraph
);
1318 wxASSERT( firstPara
!= NULL
);
1320 // Chop off the start of the paragraph
1321 if (topTailRange
.GetStart() > firstPara
->GetRange().GetStart())
1323 wxRichTextRange
r(firstPara
->GetRange().GetStart(), topTailRange
.GetStart()-1);
1324 firstPara
->DeleteRange(r
);
1326 // Make sure the numbering is correct
1328 fragment
.CalculateRange(firstPara
->GetRange().GetStart(), end
);
1330 // Now, we've deleted some positions, so adjust the range
1332 topTailRange
.SetEnd(topTailRange
.GetEnd() - r
.GetLength());
1335 wxRichTextParagraph
* lastPara
= wxDynamicCast(fragment
.GetChildren().GetLast()->GetData(), wxRichTextParagraph
);
1336 wxASSERT( lastPara
!= NULL
);
1338 if (topTailRange
.GetEnd() < (lastPara
->GetRange().GetEnd()-1))
1340 wxRichTextRange
r(topTailRange
.GetEnd()+1, lastPara
->GetRange().GetEnd()-1); /* -1 since actual text ends 1 position before end of para marker */
1341 lastPara
->DeleteRange(r
);
1343 // Make sure the numbering is correct
1345 fragment
.CalculateRange(firstPara
->GetRange().GetStart(), end
);
1347 // We only have part of a paragraph at the end
1348 fragment
.SetPartialParagraph(true);
1352 if (topTailRange
.GetEnd() == (lastPara
->GetRange().GetEnd() - 1))
1353 // We have a partial paragraph (don't save last new paragraph marker)
1354 fragment
.SetPartialParagraph(true);
1356 // We have a complete paragraph
1357 fragment
.SetPartialParagraph(false);
1364 /// Given a position, get the number of the visible line (potentially many to a paragraph),
1365 /// starting from zero at the start of the buffer.
1366 long wxRichTextParagraphLayoutBox::GetVisibleLineNumber(long pos
, bool caretPosition
, bool startOfLine
) const
1373 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1376 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1377 wxASSERT( child
!= NULL
);
1379 if (child
->GetRange().Contains(pos
))
1381 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
1384 wxRichTextLine
* line
= node2
->GetData();
1385 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
1387 if (lineRange
.Contains(pos
))
1389 // If the caret is displayed at the end of the previous wrapped line,
1390 // we want to return the line it's _displayed_ at (not the actual line
1391 // containing the position).
1392 if (lineRange
.GetStart() == pos
&& !startOfLine
&& child
->GetRange().GetStart() != pos
)
1393 return lineCount
- 1;
1400 node2
= node2
->GetNext();
1402 // If we didn't find it in the lines, it must be
1403 // the last position of the paragraph. So return the last line.
1407 lineCount
+= child
->GetLines().GetCount();
1409 node
= node
->GetNext();
1416 /// Given a line number, get the corresponding wxRichTextLine object.
1417 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineForVisibleLineNumber(long lineNumber
) const
1421 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1424 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1425 wxASSERT(child
!= NULL
);
1427 if (lineNumber
< (int) (child
->GetLines().GetCount() + lineCount
))
1429 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
1432 wxRichTextLine
* line
= node2
->GetData();
1434 if (lineCount
== lineNumber
)
1439 node2
= node2
->GetNext();
1443 lineCount
+= child
->GetLines().GetCount();
1445 node
= node
->GetNext();
1452 /// Delete range from layout.
1453 bool wxRichTextParagraphLayoutBox::DeleteRange(const wxRichTextRange
& range
)
1455 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1457 wxRichTextParagraph
* firstPara
= NULL
;
1460 wxRichTextParagraph
* obj
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1461 wxASSERT (obj
!= NULL
);
1463 wxRichTextObjectList::compatibility_iterator next
= node
->GetNext();
1465 // Delete the range in each paragraph
1467 if (!obj
->GetRange().IsOutside(range
))
1469 // Deletes the content of this object within the given range
1470 obj
->DeleteRange(range
);
1472 wxRichTextRange thisRange
= obj
->GetRange();
1473 wxTextAttrEx thisAttr
= obj
->GetAttributes();
1475 // If the whole paragraph is within the range to delete,
1476 // delete the whole thing.
1477 if (range
.GetStart() <= thisRange
.GetStart() && range
.GetEnd() >= thisRange
.GetEnd())
1479 // Delete the whole object
1480 RemoveChild(obj
, true);
1483 else if (!firstPara
)
1486 // If the range includes the paragraph end, we need to join this
1487 // and the next paragraph.
1488 if (range
.GetEnd() <= thisRange
.GetEnd())
1490 // We need to move the objects from the next paragraph
1491 // to this paragraph
1493 wxRichTextParagraph
* nextParagraph
= NULL
;
1494 if ((range
.GetEnd() < thisRange
.GetEnd()) && obj
)
1495 nextParagraph
= obj
;
1498 // We're ending at the end of the paragraph, so merge the _next_ paragraph.
1500 nextParagraph
= wxDynamicCast(next
->GetData(), wxRichTextParagraph
);
1503 bool applyFinalParagraphStyle
= firstPara
&& nextParagraph
&& nextParagraph
!= firstPara
;
1505 wxTextAttrEx nextParaAttr
;
1506 if (applyFinalParagraphStyle
)
1508 // Special case when deleting the end of a paragraph - use _this_ paragraph's style,
1509 // not the next one.
1510 if (range
.GetStart() == range
.GetEnd() && range
.GetStart() == thisRange
.GetEnd())
1511 nextParaAttr
= thisAttr
;
1513 nextParaAttr
= nextParagraph
->GetAttributes();
1516 if (firstPara
&& nextParagraph
&& firstPara
!= nextParagraph
)
1518 // Move the objects to the previous para
1519 wxRichTextObjectList::compatibility_iterator node1
= nextParagraph
->GetChildren().GetFirst();
1523 wxRichTextObject
* obj1
= node1
->GetData();
1525 firstPara
->AppendChild(obj1
);
1527 wxRichTextObjectList::compatibility_iterator next1
= node1
->GetNext();
1528 nextParagraph
->GetChildren().Erase(node1
);
1533 // Delete the paragraph
1534 RemoveChild(nextParagraph
, true);
1537 // Avoid empty paragraphs
1538 if (firstPara
&& firstPara
->GetChildren().GetCount() == 0)
1540 wxRichTextPlainText
* text
= new wxRichTextPlainText(wxEmptyString
);
1541 firstPara
->AppendChild(text
);
1544 if (applyFinalParagraphStyle
)
1545 firstPara
->SetAttributes(nextParaAttr
);
1557 /// Get any text in this object for the given range
1558 wxString
wxRichTextParagraphLayoutBox::GetTextForRange(const wxRichTextRange
& range
) const
1562 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1565 wxRichTextObject
* child
= node
->GetData();
1566 if (!child
->GetRange().IsOutside(range
))
1568 wxRichTextRange childRange
= range
;
1569 childRange
.LimitTo(child
->GetRange());
1571 wxString childText
= child
->GetTextForRange(childRange
);
1575 if ((childRange
.GetEnd() == child
->GetRange().GetEnd()) && node
->GetNext())
1580 node
= node
->GetNext();
1586 /// Get all the text
1587 wxString
wxRichTextParagraphLayoutBox::GetText() const
1589 return GetTextForRange(GetRange());
1592 /// Get the paragraph by number
1593 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphAtLine(long paragraphNumber
) const
1595 if ((size_t) paragraphNumber
>= GetChildCount())
1598 return (wxRichTextParagraph
*) GetChild((size_t) paragraphNumber
);
1601 /// Get the length of the paragraph
1602 int wxRichTextParagraphLayoutBox::GetParagraphLength(long paragraphNumber
) const
1604 wxRichTextParagraph
* para
= GetParagraphAtLine(paragraphNumber
);
1606 return para
->GetRange().GetLength() - 1; // don't include newline
1611 /// Get the text of the paragraph
1612 wxString
wxRichTextParagraphLayoutBox::GetParagraphText(long paragraphNumber
) const
1614 wxRichTextParagraph
* para
= GetParagraphAtLine(paragraphNumber
);
1616 return para
->GetTextForRange(para
->GetRange());
1618 return wxEmptyString
;
1621 /// Convert zero-based line column and paragraph number to a position.
1622 long wxRichTextParagraphLayoutBox::XYToPosition(long x
, long y
) const
1624 wxRichTextParagraph
* para
= GetParagraphAtLine(y
);
1627 return para
->GetRange().GetStart() + x
;
1633 /// Convert zero-based position to line column and paragraph number
1634 bool wxRichTextParagraphLayoutBox::PositionToXY(long pos
, long* x
, long* y
) const
1636 wxRichTextParagraph
* para
= GetParagraphAtPosition(pos
);
1640 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1643 wxRichTextObject
* child
= node
->GetData();
1647 node
= node
->GetNext();
1651 *x
= pos
- para
->GetRange().GetStart();
1659 /// Get the leaf object in a paragraph at this position.
1660 /// Given a line number, get the corresponding wxRichTextLine object.
1661 wxRichTextObject
* wxRichTextParagraphLayoutBox::GetLeafObjectAtPosition(long position
) const
1663 wxRichTextParagraph
* para
= GetParagraphAtPosition(position
);
1666 wxRichTextObjectList::compatibility_iterator node
= para
->GetChildren().GetFirst();
1670 wxRichTextObject
* child
= node
->GetData();
1671 if (child
->GetRange().Contains(position
))
1674 node
= node
->GetNext();
1676 if (position
== para
->GetRange().GetEnd() && para
->GetChildCount() > 0)
1677 return para
->GetChildren().GetLast()->GetData();
1682 /// Set character or paragraph text attributes: apply character styles only to immediate text nodes
1683 bool wxRichTextParagraphLayoutBox::SetStyle(const wxRichTextRange
& range
, const wxTextAttr
& style
, int flags
)
1685 bool characterStyle
= false;
1686 bool paragraphStyle
= false;
1688 if (style
.IsCharacterStyle())
1689 characterStyle
= true;
1690 if (style
.IsParagraphStyle())
1691 paragraphStyle
= true;
1693 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
1694 bool applyMinimal
= ((flags
& wxRICHTEXT_SETSTYLE_OPTIMIZE
) != 0);
1695 bool parasOnly
= ((flags
& wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY
) != 0);
1696 bool charactersOnly
= ((flags
& wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY
) != 0);
1697 bool resetExistingStyle
= ((flags
& wxRICHTEXT_SETSTYLE_RESET
) != 0);
1698 bool removeStyle
= ((flags
& wxRICHTEXT_SETSTYLE_REMOVE
) != 0);
1700 // Apply paragraph style first, if any
1701 wxTextAttr
wholeStyle(style
);
1703 if (!removeStyle
&& wholeStyle
.HasParagraphStyleName() && GetStyleSheet())
1705 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(wholeStyle
.GetParagraphStyleName());
1707 wxRichTextApplyStyle(wholeStyle
, def
->GetStyleMergedWithBase(GetStyleSheet()));
1710 // Limit the attributes to be set to the content to only character attributes.
1711 wxTextAttr
characterAttributes(wholeStyle
);
1712 characterAttributes
.SetFlags(characterAttributes
.GetFlags() & (wxTEXT_ATTR_CHARACTER
));
1714 if (!removeStyle
&& characterAttributes
.HasCharacterStyleName() && GetStyleSheet())
1716 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterAttributes
.GetCharacterStyleName());
1718 wxRichTextApplyStyle(characterAttributes
, def
->GetStyleMergedWithBase(GetStyleSheet()));
1721 // If we are associated with a control, make undoable; otherwise, apply immediately
1724 bool haveControl
= (GetRichTextCtrl() != NULL
);
1726 wxRichTextAction
* action
= NULL
;
1728 if (haveControl
&& withUndo
)
1730 action
= new wxRichTextAction(NULL
, _("Change Style"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
1731 action
->SetRange(range
);
1732 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
1735 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1738 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1739 wxASSERT (para
!= NULL
);
1741 if (para
&& para
->GetChildCount() > 0)
1743 // Stop searching if we're beyond the range of interest
1744 if (para
->GetRange().GetStart() > range
.GetEnd())
1747 if (!para
->GetRange().IsOutside(range
))
1749 // We'll be using a copy of the paragraph to make style changes,
1750 // not updating the buffer directly.
1751 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
1753 if (haveControl
&& withUndo
)
1755 newPara
= new wxRichTextParagraph(*para
);
1756 action
->GetNewParagraphs().AppendChild(newPara
);
1758 // Also store the old ones for Undo
1759 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
1764 // If we're specifying paragraphs only, then we really mean character formatting
1765 // to be included in the paragraph style
1766 if ((paragraphStyle
|| parasOnly
) && !charactersOnly
)
1770 // Removes the given style from the paragraph
1771 wxRichTextRemoveStyle(newPara
->GetAttributes(), style
);
1773 else if (resetExistingStyle
)
1774 newPara
->GetAttributes() = wholeStyle
;
1779 // Only apply attributes that will make a difference to the combined
1780 // style as seen on the display
1781 wxTextAttr
combinedAttr(para
->GetCombinedAttributes());
1782 wxRichTextApplyStyle(newPara
->GetAttributes(), wholeStyle
, & combinedAttr
);
1785 wxRichTextApplyStyle(newPara
->GetAttributes(), wholeStyle
);
1789 // When applying paragraph styles dynamically, don't change the text objects' attributes
1790 // since they will computed as needed. Only apply the character styling if it's _only_
1791 // character styling. This policy is subject to change and might be put under user control.
1793 // Hm. we might well be applying a mix of paragraph and character styles, in which
1794 // case we _do_ want to apply character styles regardless of what para styles are set.
1795 // But if we're applying a paragraph style, which has some character attributes, but
1796 // we only want the paragraphs to hold this character style, then we _don't_ want to
1797 // apply the character style. So we need to be able to choose.
1799 if (!parasOnly
&& (characterStyle
|charactersOnly
) && range
.GetStart() != newPara
->GetRange().GetEnd())
1801 wxRichTextRange
childRange(range
);
1802 childRange
.LimitTo(newPara
->GetRange());
1804 // Find the starting position and if necessary split it so
1805 // we can start applying a different style.
1806 // TODO: check that the style actually changes or is different
1807 // from style outside of range
1808 wxRichTextObject
* firstObject
wxDUMMY_INITIALIZE(NULL
);
1809 wxRichTextObject
* lastObject
wxDUMMY_INITIALIZE(NULL
);
1811 if (childRange
.GetStart() == newPara
->GetRange().GetStart())
1812 firstObject
= newPara
->GetChildren().GetFirst()->GetData();
1814 firstObject
= newPara
->SplitAt(range
.GetStart());
1816 // Increment by 1 because we're apply the style one _after_ the split point
1817 long splitPoint
= childRange
.GetEnd();
1818 if (splitPoint
!= newPara
->GetRange().GetEnd())
1822 if (splitPoint
== newPara
->GetRange().GetEnd())
1823 lastObject
= newPara
->GetChildren().GetLast()->GetData();
1825 // lastObject is set as a side-effect of splitting. It's
1826 // returned as the object before the new object.
1827 (void) newPara
->SplitAt(splitPoint
, & lastObject
);
1829 wxASSERT(firstObject
!= NULL
);
1830 wxASSERT(lastObject
!= NULL
);
1832 if (!firstObject
|| !lastObject
)
1835 wxRichTextObjectList::compatibility_iterator firstNode
= newPara
->GetChildren().Find(firstObject
);
1836 wxRichTextObjectList::compatibility_iterator lastNode
= newPara
->GetChildren().Find(lastObject
);
1838 wxASSERT(firstNode
);
1841 wxRichTextObjectList::compatibility_iterator node2
= firstNode
;
1845 wxRichTextObject
* child
= node2
->GetData();
1849 // Removes the given style from the paragraph
1850 wxRichTextRemoveStyle(child
->GetAttributes(), style
);
1852 else if (resetExistingStyle
)
1853 child
->GetAttributes() = characterAttributes
;
1858 // Only apply attributes that will make a difference to the combined
1859 // style as seen on the display
1860 wxTextAttr
combinedAttr(newPara
->GetCombinedAttributes(child
->GetAttributes()));
1861 wxRichTextApplyStyle(child
->GetAttributes(), characterAttributes
, & combinedAttr
);
1864 wxRichTextApplyStyle(child
->GetAttributes(), characterAttributes
);
1867 if (node2
== lastNode
)
1870 node2
= node2
->GetNext();
1876 node
= node
->GetNext();
1879 // Do action, or delay it until end of batch.
1880 if (haveControl
&& withUndo
)
1881 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
1886 /// Get the text attributes for this position.
1887 bool wxRichTextParagraphLayoutBox::GetStyle(long position
, wxTextAttr
& style
)
1889 return DoGetStyle(position
, style
, true);
1892 bool wxRichTextParagraphLayoutBox::GetUncombinedStyle(long position
, wxTextAttr
& style
)
1894 return DoGetStyle(position
, style
, false);
1897 /// Implementation helper for GetStyle. If combineStyles is true, combine base, paragraph and
1898 /// context attributes.
1899 bool wxRichTextParagraphLayoutBox::DoGetStyle(long position
, wxTextAttr
& style
, bool combineStyles
)
1901 wxRichTextObject
* obj
wxDUMMY_INITIALIZE(NULL
);
1903 if (style
.IsParagraphStyle())
1905 obj
= GetParagraphAtPosition(position
);
1910 // Start with the base style
1911 style
= GetAttributes();
1913 // Apply the paragraph style
1914 wxRichTextApplyStyle(style
, obj
->GetAttributes());
1917 style
= obj
->GetAttributes();
1924 obj
= GetLeafObjectAtPosition(position
);
1929 wxRichTextParagraph
* para
= wxDynamicCast(obj
->GetParent(), wxRichTextParagraph
);
1930 style
= para
? para
->GetCombinedAttributes(obj
->GetAttributes()) : obj
->GetAttributes();
1933 style
= obj
->GetAttributes();
1941 static bool wxHasStyle(long flags
, long style
)
1943 return (flags
& style
) != 0;
1946 /// Combines 'style' with 'currentStyle' for the purpose of summarising the attributes of a range of
1948 bool wxRichTextParagraphLayoutBox::CollectStyle(wxTextAttr
& currentStyle
, const wxTextAttr
& style
, long& multipleStyleAttributes
, int& multipleTextEffectAttributes
, int& absentStyleAttributes
, int& absentTextEffectAttributes
)
1950 absentStyleAttributes
|= (~style
.GetFlags() & wxTEXT_ATTR_ALL
);
1951 absentTextEffectAttributes
|= (~style
.GetTextEffectFlags() & 0xFFFF);
1953 if (style
.HasFont())
1955 if (style
.HasFontSize() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_FONT_SIZE
))
1957 if (currentStyle
.HasFontSize())
1959 if (currentStyle
.GetFontSize() != style
.GetFontSize())
1961 // Clash of style - mark as such
1962 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_SIZE
;
1963 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_SIZE
);
1968 currentStyle
.SetFontSize(style
.GetFontSize());
1972 if (style
.HasFontItalic() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_FONT_ITALIC
))
1974 if (currentStyle
.HasFontItalic())
1976 if (currentStyle
.GetFontStyle() != style
.GetFontStyle())
1978 // Clash of style - mark as such
1979 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_ITALIC
;
1980 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_ITALIC
);
1985 currentStyle
.SetFontStyle(style
.GetFontStyle());
1989 if (style
.HasFontWeight() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_FONT_WEIGHT
))
1991 if (currentStyle
.HasFontWeight())
1993 if (currentStyle
.GetFontWeight() != style
.GetFontWeight())
1995 // Clash of style - mark as such
1996 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_WEIGHT
;
1997 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_WEIGHT
);
2002 currentStyle
.SetFontWeight(style
.GetFontWeight());
2006 if (style
.HasFontFaceName() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_FONT_FACE
))
2008 if (currentStyle
.HasFontFaceName())
2010 wxString
faceName1(currentStyle
.GetFontFaceName());
2011 wxString
faceName2(style
.GetFontFaceName());
2013 if (faceName1
!= faceName2
)
2015 // Clash of style - mark as such
2016 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_FACE
;
2017 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_FACE
);
2022 currentStyle
.SetFontFaceName(style
.GetFontFaceName());
2026 if (style
.HasFontUnderlined() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_FONT_UNDERLINE
))
2028 if (currentStyle
.HasFontUnderlined())
2030 if (currentStyle
.GetFontUnderlined() != style
.GetFontUnderlined())
2032 // Clash of style - mark as such
2033 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_UNDERLINE
;
2034 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_UNDERLINE
);
2039 currentStyle
.SetFontUnderlined(style
.GetFontUnderlined());
2044 if (style
.HasTextColour() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_TEXT_COLOUR
))
2046 if (currentStyle
.HasTextColour())
2048 if (currentStyle
.GetTextColour() != style
.GetTextColour())
2050 // Clash of style - mark as such
2051 multipleStyleAttributes
|= wxTEXT_ATTR_TEXT_COLOUR
;
2052 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_TEXT_COLOUR
);
2056 currentStyle
.SetTextColour(style
.GetTextColour());
2059 if (style
.HasBackgroundColour() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_BACKGROUND_COLOUR
))
2061 if (currentStyle
.HasBackgroundColour())
2063 if (currentStyle
.GetBackgroundColour() != style
.GetBackgroundColour())
2065 // Clash of style - mark as such
2066 multipleStyleAttributes
|= wxTEXT_ATTR_BACKGROUND_COLOUR
;
2067 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BACKGROUND_COLOUR
);
2071 currentStyle
.SetBackgroundColour(style
.GetBackgroundColour());
2074 if (style
.HasAlignment() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_ALIGNMENT
))
2076 if (currentStyle
.HasAlignment())
2078 if (currentStyle
.GetAlignment() != style
.GetAlignment())
2080 // Clash of style - mark as such
2081 multipleStyleAttributes
|= wxTEXT_ATTR_ALIGNMENT
;
2082 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_ALIGNMENT
);
2086 currentStyle
.SetAlignment(style
.GetAlignment());
2089 if (style
.HasTabs() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_TABS
))
2091 if (currentStyle
.HasTabs())
2093 if (!wxRichTextTabsEq(currentStyle
.GetTabs(), style
.GetTabs()))
2095 // Clash of style - mark as such
2096 multipleStyleAttributes
|= wxTEXT_ATTR_TABS
;
2097 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_TABS
);
2101 currentStyle
.SetTabs(style
.GetTabs());
2104 if (style
.HasLeftIndent() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_LEFT_INDENT
))
2106 if (currentStyle
.HasLeftIndent())
2108 if (currentStyle
.GetLeftIndent() != style
.GetLeftIndent() || currentStyle
.GetLeftSubIndent() != style
.GetLeftSubIndent())
2110 // Clash of style - mark as such
2111 multipleStyleAttributes
|= wxTEXT_ATTR_LEFT_INDENT
;
2112 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LEFT_INDENT
);
2116 currentStyle
.SetLeftIndent(style
.GetLeftIndent(), style
.GetLeftSubIndent());
2119 if (style
.HasRightIndent() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_RIGHT_INDENT
))
2121 if (currentStyle
.HasRightIndent())
2123 if (currentStyle
.GetRightIndent() != style
.GetRightIndent())
2125 // Clash of style - mark as such
2126 multipleStyleAttributes
|= wxTEXT_ATTR_RIGHT_INDENT
;
2127 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_RIGHT_INDENT
);
2131 currentStyle
.SetRightIndent(style
.GetRightIndent());
2134 if (style
.HasParagraphSpacingAfter() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_PARA_SPACING_AFTER
))
2136 if (currentStyle
.HasParagraphSpacingAfter())
2138 if (currentStyle
.GetParagraphSpacingAfter() != style
.GetParagraphSpacingAfter())
2140 // Clash of style - mark as such
2141 multipleStyleAttributes
|= wxTEXT_ATTR_PARA_SPACING_AFTER
;
2142 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARA_SPACING_AFTER
);
2146 currentStyle
.SetParagraphSpacingAfter(style
.GetParagraphSpacingAfter());
2149 if (style
.HasParagraphSpacingBefore() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_PARA_SPACING_BEFORE
))
2151 if (currentStyle
.HasParagraphSpacingBefore())
2153 if (currentStyle
.GetParagraphSpacingBefore() != style
.GetParagraphSpacingBefore())
2155 // Clash of style - mark as such
2156 multipleStyleAttributes
|= wxTEXT_ATTR_PARA_SPACING_BEFORE
;
2157 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARA_SPACING_BEFORE
);
2161 currentStyle
.SetParagraphSpacingBefore(style
.GetParagraphSpacingBefore());
2164 if (style
.HasLineSpacing() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_LINE_SPACING
))
2166 if (currentStyle
.HasLineSpacing())
2168 if (currentStyle
.GetLineSpacing() != style
.GetLineSpacing())
2170 // Clash of style - mark as such
2171 multipleStyleAttributes
|= wxTEXT_ATTR_LINE_SPACING
;
2172 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LINE_SPACING
);
2176 currentStyle
.SetLineSpacing(style
.GetLineSpacing());
2179 if (style
.HasCharacterStyleName() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_CHARACTER_STYLE_NAME
))
2181 if (currentStyle
.HasCharacterStyleName())
2183 if (currentStyle
.GetCharacterStyleName() != style
.GetCharacterStyleName())
2185 // Clash of style - mark as such
2186 multipleStyleAttributes
|= wxTEXT_ATTR_CHARACTER_STYLE_NAME
;
2187 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_CHARACTER_STYLE_NAME
);
2191 currentStyle
.SetCharacterStyleName(style
.GetCharacterStyleName());
2194 if (style
.HasParagraphStyleName() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
))
2196 if (currentStyle
.HasParagraphStyleName())
2198 if (currentStyle
.GetParagraphStyleName() != style
.GetParagraphStyleName())
2200 // Clash of style - mark as such
2201 multipleStyleAttributes
|= wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
;
2202 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
);
2206 currentStyle
.SetParagraphStyleName(style
.GetParagraphStyleName());
2209 if (style
.HasListStyleName() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_LIST_STYLE_NAME
))
2211 if (currentStyle
.HasListStyleName())
2213 if (currentStyle
.GetListStyleName() != style
.GetListStyleName())
2215 // Clash of style - mark as such
2216 multipleStyleAttributes
|= wxTEXT_ATTR_LIST_STYLE_NAME
;
2217 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LIST_STYLE_NAME
);
2221 currentStyle
.SetListStyleName(style
.GetListStyleName());
2224 if (style
.HasBulletStyle() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_BULLET_STYLE
))
2226 if (currentStyle
.HasBulletStyle())
2228 if (currentStyle
.GetBulletStyle() != style
.GetBulletStyle())
2230 // Clash of style - mark as such
2231 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_STYLE
;
2232 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_STYLE
);
2236 currentStyle
.SetBulletStyle(style
.GetBulletStyle());
2239 if (style
.HasBulletNumber() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_BULLET_NUMBER
))
2241 if (currentStyle
.HasBulletNumber())
2243 if (currentStyle
.GetBulletNumber() != style
.GetBulletNumber())
2245 // Clash of style - mark as such
2246 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_NUMBER
;
2247 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_NUMBER
);
2251 currentStyle
.SetBulletNumber(style
.GetBulletNumber());
2254 if (style
.HasBulletText() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_BULLET_TEXT
))
2256 if (currentStyle
.HasBulletText())
2258 if (currentStyle
.GetBulletText() != style
.GetBulletText())
2260 // Clash of style - mark as such
2261 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_TEXT
;
2262 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_TEXT
);
2267 currentStyle
.SetBulletText(style
.GetBulletText());
2268 currentStyle
.SetBulletFont(style
.GetBulletFont());
2272 if (style
.HasBulletName() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_BULLET_NAME
))
2274 if (currentStyle
.HasBulletName())
2276 if (currentStyle
.GetBulletName() != style
.GetBulletName())
2278 // Clash of style - mark as such
2279 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_NAME
;
2280 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_NAME
);
2285 currentStyle
.SetBulletName(style
.GetBulletName());
2289 if (style
.HasURL() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_URL
))
2291 if (currentStyle
.HasURL())
2293 if (currentStyle
.GetURL() != style
.GetURL())
2295 // Clash of style - mark as such
2296 multipleStyleAttributes
|= wxTEXT_ATTR_URL
;
2297 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_URL
);
2302 currentStyle
.SetURL(style
.GetURL());
2306 if (style
.HasTextEffects() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_EFFECTS
))
2308 if (currentStyle
.HasTextEffects())
2310 // We need to find the bits in the new style that are different:
2311 // just look at those bits that are specified by the new style.
2313 // We need to remove the bits and flags that are not common between current style
2314 // and new style. In so doing we need to take account of the styles absent from one or more of the
2317 int currentRelevantTextEffects
= currentStyle
.GetTextEffects() & style
.GetTextEffectFlags();
2318 int newRelevantTextEffects
= style
.GetTextEffects() & style
.GetTextEffectFlags();
2320 if (currentRelevantTextEffects
!= newRelevantTextEffects
)
2322 // Find the text effects that were different, using XOR
2323 int differentEffects
= currentRelevantTextEffects
^ newRelevantTextEffects
;
2325 // Clash of style - mark as such
2326 multipleTextEffectAttributes
|= differentEffects
;
2327 currentStyle
.SetTextEffectFlags(currentStyle
.GetTextEffectFlags() & ~differentEffects
);
2332 currentStyle
.SetTextEffects(style
.GetTextEffects());
2333 currentStyle
.SetTextEffectFlags(style
.GetTextEffectFlags());
2336 // Mask out the flags and values that cannot be common because they were absent in one or more objecrs
2337 // that we've looked at so far
2338 currentStyle
.SetTextEffects(currentStyle
.GetTextEffects() & ~absentTextEffectAttributes
);
2339 currentStyle
.SetTextEffectFlags(currentStyle
.GetTextEffectFlags() & ~absentTextEffectAttributes
);
2341 if (currentStyle
.GetTextEffectFlags() == 0)
2342 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_EFFECTS
);
2345 if (style
.HasOutlineLevel() && !wxHasStyle(multipleStyleAttributes
|absentStyleAttributes
, wxTEXT_ATTR_OUTLINE_LEVEL
))
2347 if (currentStyle
.HasOutlineLevel())
2349 if (currentStyle
.GetOutlineLevel() != style
.GetOutlineLevel())
2351 // Clash of style - mark as such
2352 multipleStyleAttributes
|= wxTEXT_ATTR_OUTLINE_LEVEL
;
2353 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_OUTLINE_LEVEL
);
2357 currentStyle
.SetOutlineLevel(style
.GetOutlineLevel());
2363 /// Get the combined style for a range - if any attribute is different within the range,
2364 /// that attribute is not present within the flags.
2365 /// *** Note that this is not recursive, and so assumes that content inside a paragraph is not itself
2367 bool wxRichTextParagraphLayoutBox::GetStyleForRange(const wxRichTextRange
& range
, wxTextAttr
& style
)
2369 style
= wxTextAttr();
2371 // The attributes that aren't valid because of multiple styles within the range
2372 long multipleStyleAttributes
= 0;
2373 int multipleTextEffectAttributes
= 0;
2375 int absentStyleAttributesPara
= 0;
2376 int absentStyleAttributesChar
= 0;
2377 int absentTextEffectAttributesPara
= 0;
2378 int absentTextEffectAttributesChar
= 0;
2380 wxRichTextObjectList::compatibility_iterator node
= GetChildren().GetFirst();
2383 wxRichTextParagraph
* para
= (wxRichTextParagraph
*) node
->GetData();
2384 if (!(para
->GetRange().GetStart() > range
.GetEnd() || para
->GetRange().GetEnd() < range
.GetStart()))
2386 if (para
->GetChildren().GetCount() == 0)
2388 wxTextAttr paraStyle
= para
->GetCombinedAttributes();
2390 CollectStyle(style
, paraStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
, absentStyleAttributesPara
, absentTextEffectAttributesPara
);
2394 wxRichTextRange
paraRange(para
->GetRange());
2395 paraRange
.LimitTo(range
);
2397 // First collect paragraph attributes only
2398 wxTextAttr paraStyle
= para
->GetCombinedAttributes();
2399 paraStyle
.SetFlags(paraStyle
.GetFlags() & wxTEXT_ATTR_PARAGRAPH
);
2400 CollectStyle(style
, paraStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
, absentStyleAttributesPara
, absentTextEffectAttributesPara
);
2402 wxRichTextObjectList::compatibility_iterator childNode
= para
->GetChildren().GetFirst();
2406 wxRichTextObject
* child
= childNode
->GetData();
2407 if (!(child
->GetRange().GetStart() > range
.GetEnd() || child
->GetRange().GetEnd() < range
.GetStart()))
2409 wxTextAttr childStyle
= para
->GetCombinedAttributes(child
->GetAttributes());
2411 // Now collect character attributes only
2412 childStyle
.SetFlags(childStyle
.GetFlags() & wxTEXT_ATTR_CHARACTER
);
2414 CollectStyle(style
, childStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
, absentStyleAttributesChar
, absentTextEffectAttributesChar
);
2417 childNode
= childNode
->GetNext();
2421 node
= node
->GetNext();
2426 /// Set default style
2427 bool wxRichTextParagraphLayoutBox::SetDefaultStyle(const wxTextAttr
& style
)
2429 m_defaultAttributes
= style
;
2433 /// Test if this whole range has character attributes of the specified kind. If any
2434 /// of the attributes are different within the range, the test fails. You
2435 /// can use this to implement, for example, bold button updating. style must have
2436 /// flags indicating which attributes are of interest.
2437 bool wxRichTextParagraphLayoutBox::HasCharacterAttributes(const wxRichTextRange
& range
, const wxTextAttr
& style
) const
2440 int matchingCount
= 0;
2442 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2445 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2446 wxASSERT (para
!= NULL
);
2450 // Stop searching if we're beyond the range of interest
2451 if (para
->GetRange().GetStart() > range
.GetEnd())
2452 return foundCount
== matchingCount
;
2454 if (!para
->GetRange().IsOutside(range
))
2456 wxRichTextObjectList::compatibility_iterator node2
= para
->GetChildren().GetFirst();
2460 wxRichTextObject
* child
= node2
->GetData();
2461 if (!child
->GetRange().IsOutside(range
) && child
->IsKindOf(CLASSINFO(wxRichTextPlainText
)))
2464 wxTextAttr textAttr
= para
->GetCombinedAttributes(child
->GetAttributes());
2466 if (wxTextAttrEqPartial(textAttr
, style
, style
.GetFlags()))
2470 node2
= node2
->GetNext();
2475 node
= node
->GetNext();
2478 return foundCount
== matchingCount
;
2481 /// Test if this whole range has paragraph attributes of the specified kind. If any
2482 /// of the attributes are different within the range, the test fails. You
2483 /// can use this to implement, for example, centering button updating. style must have
2484 /// flags indicating which attributes are of interest.
2485 bool wxRichTextParagraphLayoutBox::HasParagraphAttributes(const wxRichTextRange
& range
, const wxTextAttr
& style
) const
2488 int matchingCount
= 0;
2490 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2493 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2494 wxASSERT (para
!= NULL
);
2498 // Stop searching if we're beyond the range of interest
2499 if (para
->GetRange().GetStart() > range
.GetEnd())
2500 return foundCount
== matchingCount
;
2502 if (!para
->GetRange().IsOutside(range
))
2504 wxTextAttr textAttr
= GetAttributes();
2505 // Apply the paragraph style
2506 wxRichTextApplyStyle(textAttr
, para
->GetAttributes());
2509 if (wxTextAttrEqPartial(textAttr
, style
, style
.GetFlags()))
2514 node
= node
->GetNext();
2516 return foundCount
== matchingCount
;
2519 void wxRichTextParagraphLayoutBox::Clear()
2524 void wxRichTextParagraphLayoutBox::Reset()
2528 wxRichTextBuffer
* buffer
= wxDynamicCast(this, wxRichTextBuffer
);
2529 if (buffer
&& GetRichTextCtrl())
2531 wxRichTextEvent
event(wxEVT_COMMAND_RICHTEXT_BUFFER_RESET
, GetRichTextCtrl()->GetId());
2532 event
.SetEventObject(GetRichTextCtrl());
2534 buffer
->SendEvent(event
, true);
2537 AddParagraph(wxEmptyString
);
2539 Invalidate(wxRICHTEXT_ALL
);
2542 /// Invalidate the buffer. With no argument, invalidates whole buffer.
2543 void wxRichTextParagraphLayoutBox::Invalidate(const wxRichTextRange
& invalidRange
)
2547 if (invalidRange
== wxRICHTEXT_ALL
)
2549 m_invalidRange
= wxRICHTEXT_ALL
;
2553 // Already invalidating everything
2554 if (m_invalidRange
== wxRICHTEXT_ALL
)
2557 if ((invalidRange
.GetStart() < m_invalidRange
.GetStart()) || m_invalidRange
.GetStart() == -1)
2558 m_invalidRange
.SetStart(invalidRange
.GetStart());
2559 if (invalidRange
.GetEnd() > m_invalidRange
.GetEnd())
2560 m_invalidRange
.SetEnd(invalidRange
.GetEnd());
2563 /// Get invalid range, rounding to entire paragraphs if argument is true.
2564 wxRichTextRange
wxRichTextParagraphLayoutBox::GetInvalidRange(bool wholeParagraphs
) const
2566 if (m_invalidRange
== wxRICHTEXT_ALL
|| m_invalidRange
== wxRICHTEXT_NONE
)
2567 return m_invalidRange
;
2569 wxRichTextRange range
= m_invalidRange
;
2571 if (wholeParagraphs
)
2573 wxRichTextParagraph
* para1
= GetParagraphAtPosition(range
.GetStart());
2574 wxRichTextParagraph
* para2
= GetParagraphAtPosition(range
.GetEnd());
2576 range
.SetStart(para1
->GetRange().GetStart());
2578 range
.SetEnd(para2
->GetRange().GetEnd());
2583 /// Apply the style sheet to the buffer, for example if the styles have changed.
2584 bool wxRichTextParagraphLayoutBox::ApplyStyleSheet(wxRichTextStyleSheet
* styleSheet
)
2586 wxASSERT(styleSheet
!= NULL
);
2592 wxRichTextAttr
attr(GetBasicStyle());
2593 if (GetBasicStyle().HasParagraphStyleName())
2595 wxRichTextParagraphStyleDefinition
* paraDef
= styleSheet
->FindParagraphStyle(GetBasicStyle().GetParagraphStyleName());
2598 attr
.Apply(paraDef
->GetStyleMergedWithBase(styleSheet
));
2599 SetBasicStyle(attr
);
2604 if (GetBasicStyle().HasCharacterStyleName())
2606 wxRichTextCharacterStyleDefinition
* charDef
= styleSheet
->FindCharacterStyle(GetBasicStyle().GetCharacterStyleName());
2609 attr
.Apply(charDef
->GetStyleMergedWithBase(styleSheet
));
2610 SetBasicStyle(attr
);
2615 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2618 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2619 wxASSERT (para
!= NULL
);
2623 // Combine paragraph and list styles. If there is a list style in the original attributes,
2624 // the current indentation overrides anything else and is used to find the item indentation.
2625 // Also, for applying paragraph styles, consider having 2 modes: (1) we merge with what we have,
2626 // thereby taking into account all user changes, (2) reset the style completely (except for indentation/list
2627 // exception as above).
2628 // Problem: when changing from one list style to another, there's a danger that the level info will get lost.
2629 // So when changing a list style interactively, could retrieve level based on current style, then
2630 // set appropriate indent and apply new style.
2632 if (!para
->GetAttributes().GetParagraphStyleName().IsEmpty() && !para
->GetAttributes().GetListStyleName().IsEmpty())
2634 int currentIndent
= para
->GetAttributes().GetLeftIndent();
2636 wxRichTextParagraphStyleDefinition
* paraDef
= styleSheet
->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
2637 wxRichTextListStyleDefinition
* listDef
= styleSheet
->FindListStyle(para
->GetAttributes().GetListStyleName());
2638 if (paraDef
&& !listDef
)
2640 para
->GetAttributes() = paraDef
->GetStyleMergedWithBase(styleSheet
);
2643 else if (listDef
&& !paraDef
)
2645 // Set overall style defined for the list style definition
2646 para
->GetAttributes() = listDef
->GetStyleMergedWithBase(styleSheet
);
2648 // Apply the style for this level
2649 wxRichTextApplyStyle(para
->GetAttributes(), * listDef
->GetLevelAttributes(listDef
->FindLevelForIndent(currentIndent
)));
2652 else if (listDef
&& paraDef
)
2654 // Combines overall list style, style for level, and paragraph style
2655 para
->GetAttributes() = listDef
->CombineWithParagraphStyle(currentIndent
, paraDef
->GetStyleMergedWithBase(styleSheet
));
2659 else if (para
->GetAttributes().GetParagraphStyleName().IsEmpty() && !para
->GetAttributes().GetListStyleName().IsEmpty())
2661 int currentIndent
= para
->GetAttributes().GetLeftIndent();
2663 wxRichTextListStyleDefinition
* listDef
= styleSheet
->FindListStyle(para
->GetAttributes().GetListStyleName());
2665 // Overall list definition style
2666 para
->GetAttributes() = listDef
->GetStyleMergedWithBase(styleSheet
);
2668 // Style for this level
2669 wxRichTextApplyStyle(para
->GetAttributes(), * listDef
->GetLevelAttributes(listDef
->FindLevelForIndent(currentIndent
)));
2673 else if (!para
->GetAttributes().GetParagraphStyleName().IsEmpty() && para
->GetAttributes().GetListStyleName().IsEmpty())
2675 wxRichTextParagraphStyleDefinition
* def
= styleSheet
->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
2678 para
->GetAttributes() = def
->GetStyleMergedWithBase(styleSheet
);
2684 node
= node
->GetNext();
2686 return foundCount
!= 0;
2690 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2692 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2694 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
2695 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2696 bool specifyLevel
= ((flags
& wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL
) != 0);
2697 bool renumber
= ((flags
& wxRICHTEXT_SETSTYLE_RENUMBER
) != 0);
2699 // Current number, if numbering
2702 wxASSERT (!specifyLevel
|| (specifyLevel
&& (specifiedLevel
>= 0)));
2704 // If we are associated with a control, make undoable; otherwise, apply immediately
2707 bool haveControl
= (GetRichTextCtrl() != NULL
);
2709 wxRichTextAction
* action
= NULL
;
2711 if (haveControl
&& withUndo
)
2713 action
= new wxRichTextAction(NULL
, _("Change List Style"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2714 action
->SetRange(range
);
2715 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2718 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2721 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2722 wxASSERT (para
!= NULL
);
2724 if (para
&& para
->GetChildCount() > 0)
2726 // Stop searching if we're beyond the range of interest
2727 if (para
->GetRange().GetStart() > range
.GetEnd())
2730 if (!para
->GetRange().IsOutside(range
))
2732 // We'll be using a copy of the paragraph to make style changes,
2733 // not updating the buffer directly.
2734 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
2736 if (haveControl
&& withUndo
)
2738 newPara
= new wxRichTextParagraph(*para
);
2739 action
->GetNewParagraphs().AppendChild(newPara
);
2741 // Also store the old ones for Undo
2742 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
2749 int thisIndent
= newPara
->GetAttributes().GetLeftIndent();
2750 int thisLevel
= specifyLevel
? specifiedLevel
: def
->FindLevelForIndent(thisIndent
);
2752 // How is numbering going to work?
2753 // If we are renumbering, or numbering for the first time, we need to keep
2754 // track of the number for each level. But we might be simply applying a different
2756 // In Word, applying a style to several paragraphs, even if at different levels,
2757 // reverts the level back to the same one. So we could do the same here.
2758 // Renumbering will need to be done when we promote/demote a paragraph.
2760 // Apply the overall list style, and item style for this level
2761 wxTextAttr
listStyle(def
->GetCombinedStyleForLevel(thisLevel
, styleSheet
));
2762 wxRichTextApplyStyle(newPara
->GetAttributes(), listStyle
);
2764 // Now we need to do numbering
2767 newPara
->GetAttributes().SetBulletNumber(n
);
2772 else if (!newPara
->GetAttributes().GetListStyleName().IsEmpty())
2774 // if def is NULL, remove list style, applying any associated paragraph style
2775 // to restore the attributes
2777 newPara
->GetAttributes().SetListStyleName(wxEmptyString
);
2778 newPara
->GetAttributes().SetLeftIndent(0, 0);
2779 newPara
->GetAttributes().SetBulletText(wxEmptyString
);
2781 // Eliminate the main list-related attributes
2782 newPara
->GetAttributes().SetFlags(newPara
->GetAttributes().GetFlags() & ~wxTEXT_ATTR_LEFT_INDENT
& ~wxTEXT_ATTR_BULLET_STYLE
& ~wxTEXT_ATTR_BULLET_NUMBER
& ~wxTEXT_ATTR_BULLET_TEXT
& wxTEXT_ATTR_LIST_STYLE_NAME
);
2784 if (styleSheet
&& !newPara
->GetAttributes().GetParagraphStyleName().IsEmpty())
2786 wxRichTextParagraphStyleDefinition
* def
= styleSheet
->FindParagraphStyle(newPara
->GetAttributes().GetParagraphStyleName());
2789 newPara
->GetAttributes() = def
->GetStyleMergedWithBase(styleSheet
);
2796 node
= node
->GetNext();
2799 // Do action, or delay it until end of batch.
2800 if (haveControl
&& withUndo
)
2801 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
2806 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int startFrom
, int specifiedLevel
)
2808 if (GetStyleSheet())
2810 wxRichTextListStyleDefinition
* def
= GetStyleSheet()->FindListStyle(defName
);
2812 return SetListStyle(range
, def
, flags
, startFrom
, specifiedLevel
);
2817 /// Clear list for given range
2818 bool wxRichTextParagraphLayoutBox::ClearListStyle(const wxRichTextRange
& range
, int flags
)
2820 return SetListStyle(range
, NULL
, flags
);
2823 /// Number/renumber any list elements in the given range
2824 bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2826 return DoNumberList(range
, range
, 0, def
, flags
, startFrom
, specifiedLevel
);
2829 /// Number/renumber any list elements in the given range. Also do promotion or demotion of items, if specified
2830 bool wxRichTextParagraphLayoutBox::DoNumberList(const wxRichTextRange
& range
, const wxRichTextRange
& promotionRange
, int promoteBy
,
2831 wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2833 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2835 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
2836 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2838 bool specifyLevel
= ((flags
& wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL
) != 0);
2841 bool renumber
= ((flags
& wxRICHTEXT_SETSTYLE_RENUMBER
) != 0);
2843 // Max number of levels
2844 const int maxLevels
= 10;
2846 // The level we're looking at now
2847 int currentLevel
= -1;
2849 // The item number for each level
2850 int levels
[maxLevels
];
2853 // Reset all numbering
2854 for (i
= 0; i
< maxLevels
; i
++)
2856 if (startFrom
!= -1)
2857 levels
[i
] = startFrom
-1;
2858 else if (renumber
) // start again
2861 levels
[i
] = -1; // start from the number we found, if any
2864 wxASSERT(!specifyLevel
|| (specifyLevel
&& (specifiedLevel
>= 0)));
2866 // If we are associated with a control, make undoable; otherwise, apply immediately
2869 bool haveControl
= (GetRichTextCtrl() != NULL
);
2871 wxRichTextAction
* action
= NULL
;
2873 if (haveControl
&& withUndo
)
2875 action
= new wxRichTextAction(NULL
, _("Renumber List"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2876 action
->SetRange(range
);
2877 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2880 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2883 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2884 wxASSERT (para
!= NULL
);
2886 if (para
&& para
->GetChildCount() > 0)
2888 // Stop searching if we're beyond the range of interest
2889 if (para
->GetRange().GetStart() > range
.GetEnd())
2892 if (!para
->GetRange().IsOutside(range
))
2894 // We'll be using a copy of the paragraph to make style changes,
2895 // not updating the buffer directly.
2896 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
2898 if (haveControl
&& withUndo
)
2900 newPara
= new wxRichTextParagraph(*para
);
2901 action
->GetNewParagraphs().AppendChild(newPara
);
2903 // Also store the old ones for Undo
2904 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
2909 wxRichTextListStyleDefinition
* defToUse
= def
;
2912 if (styleSheet
&& !newPara
->GetAttributes().GetListStyleName().IsEmpty())
2913 defToUse
= styleSheet
->FindListStyle(newPara
->GetAttributes().GetListStyleName());
2918 int thisIndent
= newPara
->GetAttributes().GetLeftIndent();
2919 int thisLevel
= defToUse
->FindLevelForIndent(thisIndent
);
2921 // If we've specified a level to apply to all, change the level.
2922 if (specifiedLevel
!= -1)
2923 thisLevel
= specifiedLevel
;
2925 // Do promotion if specified
2926 if ((promoteBy
!= 0) && !para
->GetRange().IsOutside(promotionRange
))
2928 thisLevel
= thisLevel
- promoteBy
;
2935 // Apply the overall list style, and item style for this level
2936 wxTextAttr
listStyle(defToUse
->GetCombinedStyleForLevel(thisLevel
, styleSheet
));
2937 wxRichTextApplyStyle(newPara
->GetAttributes(), listStyle
);
2939 // OK, we've (re)applied the style, now let's get the numbering right.
2941 if (currentLevel
== -1)
2942 currentLevel
= thisLevel
;
2944 // Same level as before, do nothing except increment level's number afterwards
2945 if (currentLevel
== thisLevel
)
2948 // A deeper level: start renumbering all levels after current level
2949 else if (thisLevel
> currentLevel
)
2951 for (i
= currentLevel
+1; i
<= thisLevel
; i
++)
2955 currentLevel
= thisLevel
;
2957 else if (thisLevel
< currentLevel
)
2959 currentLevel
= thisLevel
;
2962 // Use the current numbering if -1 and we have a bullet number already
2963 if (levels
[currentLevel
] == -1)
2965 if (newPara
->GetAttributes().HasBulletNumber())
2966 levels
[currentLevel
] = newPara
->GetAttributes().GetBulletNumber();
2968 levels
[currentLevel
] = 1;
2972 levels
[currentLevel
] ++;
2975 newPara
->GetAttributes().SetBulletNumber(levels
[currentLevel
]);
2977 // Create the bullet text if an outline list
2978 if (listStyle
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
)
2981 for (i
= 0; i
<= currentLevel
; i
++)
2983 if (!text
.IsEmpty())
2985 text
+= wxString::Format(wxT("%d"), levels
[i
]);
2987 newPara
->GetAttributes().SetBulletText(text
);
2993 node
= node
->GetNext();
2996 // Do action, or delay it until end of batch.
2997 if (haveControl
&& withUndo
)
2998 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
3003 bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int startFrom
, int specifiedLevel
)
3005 if (GetStyleSheet())
3007 wxRichTextListStyleDefinition
* def
= NULL
;
3008 if (!defName
.IsEmpty())
3009 def
= GetStyleSheet()->FindListStyle(defName
);
3010 return NumberList(range
, def
, flags
, startFrom
, specifiedLevel
);
3015 /// Promote the list items within the given range. promoteBy can be a positive or negative number, e.g. 1 or -1
3016 bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy
, const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int specifiedLevel
)
3019 // One strategy is to first work out the range within which renumbering must occur. Then could pass these two ranges
3020 // to NumberList with a flag indicating promotion is required within one of the ranges.
3021 // Find first and last paragraphs in range. Then for first, calculate new indentation and look back until we find
3022 // a paragraph that either has no list style, or has one that is different or whose indentation is less.
3023 // We start renumbering from the para after that different para we found. We specify that the numbering of that
3024 // list position will start from 1.
3025 // Similarly, we look after the last para in the promote range for an indentation that is less (or no list style).
3026 // We can end the renumbering at this point.
3028 // For now, only renumber within the promotion range.
3030 return DoNumberList(range
, range
, promoteBy
, def
, flags
, 1, specifiedLevel
);
3033 bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy
, const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int specifiedLevel
)
3035 if (GetStyleSheet())
3037 wxRichTextListStyleDefinition
* def
= NULL
;
3038 if (!defName
.IsEmpty())
3039 def
= GetStyleSheet()->FindListStyle(defName
);
3040 return PromoteList(promoteBy
, range
, def
, flags
, specifiedLevel
);
3045 /// Fills in the attributes for numbering a paragraph after previousParagraph. It also finds the
3046 /// position of the paragraph that it had to start looking from.
3047 bool wxRichTextParagraphLayoutBox::FindNextParagraphNumber(wxRichTextParagraph
* previousParagraph
, wxTextAttr
& attr
) const
3049 if (!previousParagraph
->GetAttributes().HasFlag(wxTEXT_ATTR_BULLET_STYLE
) || previousParagraph
->GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE
)
3052 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
3053 if (styleSheet
&& !previousParagraph
->GetAttributes().GetListStyleName().IsEmpty())
3055 wxRichTextListStyleDefinition
* def
= styleSheet
->FindListStyle(previousParagraph
->GetAttributes().GetListStyleName());
3058 // int thisIndent = previousParagraph->GetAttributes().GetLeftIndent();
3059 // int thisLevel = def->FindLevelForIndent(thisIndent);
3061 bool isOutline
= (previousParagraph
->GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
) != 0;
3063 attr
.SetFlags(previousParagraph
->GetAttributes().GetFlags() & (wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_BULLET_NUMBER
|wxTEXT_ATTR_BULLET_TEXT
|wxTEXT_ATTR_BULLET_NAME
));
3064 if (previousParagraph
->GetAttributes().HasBulletName())
3065 attr
.SetBulletName(previousParagraph
->GetAttributes().GetBulletName());
3066 attr
.SetBulletStyle(previousParagraph
->GetAttributes().GetBulletStyle());
3067 attr
.SetListStyleName(previousParagraph
->GetAttributes().GetListStyleName());
3069 int nextNumber
= previousParagraph
->GetAttributes().GetBulletNumber() + 1;
3070 attr
.SetBulletNumber(nextNumber
);
3074 wxString text
= previousParagraph
->GetAttributes().GetBulletText();
3075 if (!text
.IsEmpty())
3077 int pos
= text
.Find(wxT('.'), true);
3078 if (pos
!= wxNOT_FOUND
)
3080 text
= text
.Mid(0, text
.Length() - pos
- 1);
3083 text
= wxEmptyString
;
3084 if (!text
.IsEmpty())
3086 text
+= wxString::Format(wxT("%d"), nextNumber
);
3087 attr
.SetBulletText(text
);
3101 * wxRichTextParagraph
3102 * This object represents a single paragraph (or in a straight text editor, a line).
3105 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraph
, wxRichTextBox
)
3107 wxArrayInt
wxRichTextParagraph::sm_defaultTabs
;
3109 wxRichTextParagraph::wxRichTextParagraph(wxRichTextObject
* parent
, wxTextAttr
* style
):
3110 wxRichTextBox(parent
)
3113 SetAttributes(*style
);
3116 wxRichTextParagraph::wxRichTextParagraph(const wxString
& text
, wxRichTextObject
* parent
, wxTextAttr
* paraStyle
, wxTextAttr
* charStyle
):
3117 wxRichTextBox(parent
)
3120 SetAttributes(*paraStyle
);
3122 AppendChild(new wxRichTextPlainText(text
, this, charStyle
));
3125 wxRichTextParagraph::~wxRichTextParagraph()
3131 bool wxRichTextParagraph::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int WXUNUSED(descent
), int style
)
3133 wxTextAttr attr
= GetCombinedAttributes();
3135 // Draw the bullet, if any
3136 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3138 if (attr
.GetLeftSubIndent() != 0)
3140 int spaceBeforePara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingBefore());
3141 int leftIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftIndent());
3143 wxTextAttr
bulletAttr(GetCombinedAttributes());
3145 // Combine with the font of the first piece of content, if one is specified
3146 if (GetChildren().GetCount() > 0)
3148 wxRichTextObject
* firstObj
= (wxRichTextObject
*) GetChildren().GetFirst()->GetData();
3149 if (firstObj
->GetAttributes().HasFont())
3151 wxRichTextApplyStyle(bulletAttr
, firstObj
->GetAttributes());
3155 // Get line height from first line, if any
3156 wxRichTextLine
* line
= m_cachedLines
.GetFirst() ? (wxRichTextLine
* ) m_cachedLines
.GetFirst()->GetData() : (wxRichTextLine
*) NULL
;
3159 int lineHeight
wxDUMMY_INITIALIZE(0);
3162 lineHeight
= line
->GetSize().y
;
3163 linePos
= line
->GetPosition() + GetPosition();
3168 if (bulletAttr
.HasFont() && GetBuffer())
3169 font
= GetBuffer()->GetFontTable().FindFont(bulletAttr
);
3171 font
= (*wxNORMAL_FONT
);
3173 wxCheckSetFont(dc
, font
);
3175 lineHeight
= dc
.GetCharHeight();
3176 linePos
= GetPosition();
3177 linePos
.y
+= spaceBeforePara
;
3180 wxRect
bulletRect(GetPosition().x
+ leftIndent
, linePos
.y
, linePos
.x
- (GetPosition().x
+ leftIndent
), lineHeight
);
3182 if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP
)
3184 if (wxRichTextBuffer::GetRenderer())
3185 wxRichTextBuffer::GetRenderer()->DrawBitmapBullet(this, dc
, bulletAttr
, bulletRect
);
3187 else if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_STANDARD
)
3189 if (wxRichTextBuffer::GetRenderer())
3190 wxRichTextBuffer::GetRenderer()->DrawStandardBullet(this, dc
, bulletAttr
, bulletRect
);
3194 wxString bulletText
= GetBulletText();
3196 if (!bulletText
.empty() && wxRichTextBuffer::GetRenderer())
3197 wxRichTextBuffer::GetRenderer()->DrawTextBullet(this, dc
, bulletAttr
, bulletRect
, bulletText
);
3202 // Draw the range for each line, one object at a time.
3204 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3207 wxRichTextLine
* line
= node
->GetData();
3208 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3210 // Lines are specified relative to the paragraph
3212 wxPoint linePosition
= line
->GetPosition() + GetPosition();
3214 // Don't draw if off the screen
3215 if (((style
& wxRICHTEXT_DRAW_IGNORE_CACHE
) != 0) || ((linePosition
.y
+ line
->GetSize().y
) >= rect
.y
&& linePosition
.y
<= rect
.y
+ rect
.height
))
3217 wxPoint objectPosition
= linePosition
;
3218 int maxDescent
= line
->GetDescent();
3220 // Loop through objects until we get to the one within range
3221 wxRichTextObjectList::compatibility_iterator node2
= m_children
.GetFirst();
3226 wxRichTextObject
* child
= node2
->GetData();
3228 if (child
->GetRange().GetLength() > 0 && !child
->GetRange().IsOutside(lineRange
) && !lineRange
.IsOutside(range
))
3230 // Draw this part of the line at the correct position
3231 wxRichTextRange
objectRange(child
->GetRange());
3232 objectRange
.LimitTo(lineRange
);
3235 #if wxRICHTEXT_USE_OPTIMIZED_LINE_DRAWING && wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
3236 if (i
< (int) line
->GetObjectSizes().GetCount())
3238 objectSize
.x
= line
->GetObjectSizes()[(size_t) i
];
3244 child
->GetRangeSize(objectRange
, objectSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, objectPosition
);
3247 // Use the child object's width, but the whole line's height
3248 wxRect
childRect(objectPosition
, wxSize(objectSize
.x
, line
->GetSize().y
));
3249 child
->Draw(dc
, objectRange
, selectionRange
, childRect
, maxDescent
, style
);
3251 objectPosition
.x
+= objectSize
.x
;
3254 else if (child
->GetRange().GetStart() > lineRange
.GetEnd())
3255 // Can break out of inner loop now since we've passed this line's range
3258 node2
= node2
->GetNext();
3262 node
= node
->GetNext();
3268 // Get the range width using partial extents calculated for the whole paragraph.
3269 static int wxRichTextGetRangeWidth(const wxRichTextParagraph
& para
, const wxRichTextRange
& range
, const wxArrayInt
& partialExtents
)
3271 wxASSERT(partialExtents
.GetCount() >= (size_t) range
.GetLength());
3273 if (partialExtents
.GetCount() < (size_t) range
.GetLength())
3276 int leftMostPos
= 0;
3277 if (range
.GetStart() - para
.GetRange().GetStart() > 0)
3278 leftMostPos
= partialExtents
[range
.GetStart() - para
.GetRange().GetStart() - 1];
3280 int rightMostPos
= partialExtents
[range
.GetEnd() - para
.GetRange().GetStart()];
3282 int w
= rightMostPos
- leftMostPos
;
3287 /// Lay the item out
3288 bool wxRichTextParagraph::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
3290 wxTextAttr attr
= GetCombinedAttributes();
3294 // Increase the size of the paragraph due to spacing
3295 int spaceBeforePara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingBefore());
3296 int spaceAfterPara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingAfter());
3297 int leftIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftIndent());
3298 int leftSubIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftSubIndent());
3299 int rightIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetRightIndent());
3301 int lineSpacing
= 0;
3303 // Let's assume line spacing of 10 is normal, 15 is 1.5, 20 is 2, etc.
3304 if (attr
.GetLineSpacing() != 10 && GetBuffer())
3306 wxFont
font(GetBuffer()->GetFontTable().FindFont(attr
));
3307 wxCheckSetFont(dc
, font
);
3308 lineSpacing
= (ConvertTenthsMMToPixels(dc
, dc
.GetCharHeight()) * attr
.GetLineSpacing())/10;
3311 // Available space for text on each line differs.
3312 int availableTextSpaceFirstLine
= rect
.GetWidth() - leftIndent
- rightIndent
;
3314 // Bullets start the text at the same position as subsequent lines
3315 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3316 availableTextSpaceFirstLine
-= leftSubIndent
;
3318 int availableTextSpaceSubsequentLines
= rect
.GetWidth() - leftIndent
- rightIndent
- leftSubIndent
;
3320 // Start position for each line relative to the paragraph
3321 int startPositionFirstLine
= leftIndent
;
3322 int startPositionSubsequentLines
= leftIndent
+ leftSubIndent
;
3324 // If we have a bullet in this paragraph, the start position for the first line's text
3325 // is actually leftIndent + leftSubIndent.
3326 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3327 startPositionFirstLine
= startPositionSubsequentLines
;
3329 long lastEndPos
= GetRange().GetStart()-1;
3330 long lastCompletedEndPos
= lastEndPos
;
3332 int currentWidth
= 0;
3333 SetPosition(rect
.GetPosition());
3335 wxPoint
currentPosition(0, spaceBeforePara
); // We will calculate lines relative to paragraph
3342 wxRichTextObjectList::compatibility_iterator node
;
3344 #if wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
3346 wxArrayInt partialExtents
;
3351 // This calculates the partial text extents
3352 GetRangeSize(GetRange(), paraSize
, paraDescent
, dc
, wxRICHTEXT_UNFORMATTED
|wxRICHTEXT_CACHE_SIZE
, wxPoint(0,0), & partialExtents
);
3354 node
= m_children
.GetFirst();
3357 wxRichTextObject
* child
= node
->GetData();
3359 child
->SetCachedSize(wxDefaultSize
);
3360 child
->Layout(dc
, rect
, style
);
3362 node
= node
->GetNext();
3369 // We may need to go back to a previous child, in which case create the new line,
3370 // find the child corresponding to the start position of the string, and
3373 node
= m_children
.GetFirst();
3376 wxRichTextObject
* child
= node
->GetData();
3378 if (child
->GetRange().GetLength() == 0)
3380 node
= node
->GetNext();
3384 // If this is e.g. a composite text box, it will need to be laid out itself.
3385 // But if just a text fragment or image, for example, this will
3386 // do nothing. NB: won't we need to set the position after layout?
3387 // since for example if position is dependent on vertical line size, we
3388 // can't tell the position until the size is determined. So possibly introduce
3389 // another layout phase.
3391 // Available width depends on whether we're on the first or subsequent lines
3392 int availableSpaceForText
= (lineCount
== 0 ? availableTextSpaceFirstLine
: availableTextSpaceSubsequentLines
);
3394 currentPosition
.x
= (lineCount
== 0 ? startPositionFirstLine
: startPositionSubsequentLines
);
3396 // We may only be looking at part of a child, if we searched back for wrapping
3397 // and found a suitable point some way into the child. So get the size for the fragment
3400 long nextBreakPos
= GetFirstLineBreakPosition(lastEndPos
+1);
3401 long lastPosToUse
= child
->GetRange().GetEnd();
3402 bool lineBreakInThisObject
= (nextBreakPos
> -1 && nextBreakPos
<= child
->GetRange().GetEnd());
3404 if (lineBreakInThisObject
)
3405 lastPosToUse
= nextBreakPos
;
3408 int childDescent
= 0;
3410 if ((nextBreakPos
== -1) && (lastEndPos
== child
->GetRange().GetStart() - 1)) // i.e. we want to get the whole thing
3412 childSize
= child
->GetCachedSize();
3413 childDescent
= child
->GetDescent();
3417 #if wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
3418 // Get height only, then the width using the partial extents
3419 GetRangeSize(wxRichTextRange(lastEndPos
+1, lastPosToUse
), childSize
, childDescent
, dc
, wxRICHTEXT_UNFORMATTED
|wxRICHTEXT_HEIGHT_ONLY
);
3420 childSize
.x
= wxRichTextGetRangeWidth(*this, wxRichTextRange(lastEndPos
+1, lastPosToUse
), partialExtents
);
3422 GetRangeSize(wxRichTextRange(lastEndPos
+1, lastPosToUse
), childSize
, childDescent
, dc
, wxRICHTEXT_UNFORMATTED
, rect
.GetPosition());
3427 // 1) There was a line break BEFORE the natural break
3428 // 2) There was a line break AFTER the natural break
3429 // 3) The child still fits (carry on)
3431 if ((lineBreakInThisObject
&& (childSize
.x
+ currentWidth
<= availableSpaceForText
)) ||
3432 (childSize
.x
+ currentWidth
> availableSpaceForText
))
3434 long wrapPosition
= 0;
3436 // Find a place to wrap. This may walk back to previous children,
3437 // for example if a word spans several objects.
3438 if (!FindWrapPosition(wxRichTextRange(lastCompletedEndPos
+1, child
->GetRange().GetEnd()), dc
, availableSpaceForText
, wrapPosition
, & partialExtents
))
3440 // If the function failed, just cut it off at the end of this child.
3441 wrapPosition
= child
->GetRange().GetEnd();
3444 // FindWrapPosition can still return a value that will put us in an endless wrapping loop
3445 if (wrapPosition
<= lastCompletedEndPos
)
3446 wrapPosition
= wxMax(lastCompletedEndPos
+1,child
->GetRange().GetEnd());
3448 // wxLogDebug(wxT("Split at %ld"), wrapPosition);
3450 // Let's find the actual size of the current line now
3452 wxRichTextRange
actualRange(lastCompletedEndPos
+1, wrapPosition
);
3454 #if wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
3455 // Get height only, then the width using the partial extents
3456 GetRangeSize(actualRange
, actualSize
, childDescent
, dc
, wxRICHTEXT_UNFORMATTED
|wxRICHTEXT_HEIGHT_ONLY
);
3457 actualSize
.x
= wxRichTextGetRangeWidth(*this, actualRange
, partialExtents
);
3459 GetRangeSize(actualRange
, actualSize
, childDescent
, dc
, wxRICHTEXT_UNFORMATTED
);
3462 currentWidth
= actualSize
.x
;
3463 lineHeight
= wxMax(lineHeight
, actualSize
.y
);
3464 maxDescent
= wxMax(childDescent
, maxDescent
);
3467 wxRichTextLine
* line
= AllocateLine(lineCount
);
3469 // Set relative range so we won't have to change line ranges when paragraphs are moved
3470 line
->SetRange(wxRichTextRange(actualRange
.GetStart() - GetRange().GetStart(), actualRange
.GetEnd() - GetRange().GetStart()));
3471 line
->SetPosition(currentPosition
);
3472 line
->SetSize(wxSize(currentWidth
, lineHeight
));
3473 line
->SetDescent(maxDescent
);
3475 // Now move down a line. TODO: add margins, spacing
3476 currentPosition
.y
+= lineHeight
;
3477 currentPosition
.y
+= lineSpacing
;
3480 maxWidth
= wxMax(maxWidth
, currentWidth
);
3484 // TODO: account for zero-length objects, such as fields
3485 wxASSERT(wrapPosition
> lastCompletedEndPos
);
3487 lastEndPos
= wrapPosition
;
3488 lastCompletedEndPos
= lastEndPos
;
3492 // May need to set the node back to a previous one, due to searching back in wrapping
3493 wxRichTextObject
* childAfterWrapPosition
= FindObjectAtPosition(wrapPosition
+1);
3494 if (childAfterWrapPosition
)
3495 node
= m_children
.Find(childAfterWrapPosition
);
3497 node
= node
->GetNext();
3501 // We still fit, so don't add a line, and keep going
3502 currentWidth
+= childSize
.x
;
3503 lineHeight
= wxMax(lineHeight
, childSize
.y
);
3504 maxDescent
= wxMax(childDescent
, maxDescent
);
3506 maxWidth
= wxMax(maxWidth
, currentWidth
);
3507 lastEndPos
= child
->GetRange().GetEnd();
3509 node
= node
->GetNext();
3513 // Add the last line - it's the current pos -> last para pos
3514 // Substract -1 because the last position is always the end-paragraph position.
3515 if (lastCompletedEndPos
<= GetRange().GetEnd()-1)
3517 currentPosition
.x
= (lineCount
== 0 ? startPositionFirstLine
: startPositionSubsequentLines
);
3519 wxRichTextLine
* line
= AllocateLine(lineCount
);
3521 wxRichTextRange
actualRange(lastCompletedEndPos
+1, GetRange().GetEnd()-1);
3523 // Set relative range so we won't have to change line ranges when paragraphs are moved
3524 line
->SetRange(wxRichTextRange(actualRange
.GetStart() - GetRange().GetStart(), actualRange
.GetEnd() - GetRange().GetStart()));
3526 line
->SetPosition(currentPosition
);
3528 if (lineHeight
== 0 && GetBuffer())
3530 wxFont
font(GetBuffer()->GetFontTable().FindFont(attr
));
3531 wxCheckSetFont(dc
, font
);
3532 lineHeight
= dc
.GetCharHeight();
3534 if (maxDescent
== 0)
3537 dc
.GetTextExtent(wxT("X"), & w
, &h
, & maxDescent
);
3540 line
->SetSize(wxSize(currentWidth
, lineHeight
));
3541 line
->SetDescent(maxDescent
);
3542 currentPosition
.y
+= lineHeight
;
3543 currentPosition
.y
+= lineSpacing
;
3547 // Remove remaining unused line objects, if any
3548 ClearUnusedLines(lineCount
);
3550 // Apply styles to wrapped lines
3551 ApplyParagraphStyle(attr
, rect
);
3553 SetCachedSize(wxSize(maxWidth
, currentPosition
.y
+ spaceBeforePara
+ spaceAfterPara
));
3557 #if wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
3558 #if wxRICHTEXT_USE_OPTIMIZED_LINE_DRAWING
3559 // Use the text extents to calculate the size of each fragment in each line
3560 wxRichTextLineList::compatibility_iterator lineNode
= m_cachedLines
.GetFirst();
3563 wxRichTextLine
* line
= lineNode
->GetData();
3564 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3566 // Loop through objects until we get to the one within range
3567 wxRichTextObjectList::compatibility_iterator node2
= m_children
.GetFirst();
3571 wxRichTextObject
* child
= node2
->GetData();
3573 if (child
->GetRange().GetLength() > 0 && !child
->GetRange().IsOutside(lineRange
))
3575 wxRichTextRange rangeToUse
= lineRange
;
3576 rangeToUse
.LimitTo(child
->GetRange());
3578 // Find the size of the child from the text extents, and store in an array
3579 // for drawing later
3581 if (rangeToUse
.GetStart() > GetRange().GetStart())
3582 left
= partialExtents
[(rangeToUse
.GetStart()-1) - GetRange().GetStart()];
3583 int right
= partialExtents
[rangeToUse
.GetEnd() - GetRange().GetStart()];
3584 int sz
= right
- left
;
3585 line
->GetObjectSizes().Add(sz
);
3587 else if (child
->GetRange().GetStart() > lineRange
.GetEnd())
3588 // Can break out of inner loop now since we've passed this line's range
3591 node2
= node2
->GetNext();
3594 lineNode
= lineNode
->GetNext();
3602 /// Apply paragraph styles, such as centering, to wrapped lines
3603 void wxRichTextParagraph::ApplyParagraphStyle(const wxTextAttr
& attr
, const wxRect
& rect
)
3605 if (!attr
.HasAlignment())
3608 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3611 wxRichTextLine
* line
= node
->GetData();
3613 wxPoint pos
= line
->GetPosition();
3614 wxSize size
= line
->GetSize();
3616 // centering, right-justification
3617 if (attr
.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_CENTRE
)
3619 pos
.x
= (rect
.GetWidth() - size
.x
)/2 + pos
.x
;
3620 line
->SetPosition(pos
);
3622 else if (attr
.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_RIGHT
)
3624 pos
.x
= pos
.x
+ rect
.GetWidth() - size
.x
;
3625 line
->SetPosition(pos
);
3628 node
= node
->GetNext();
3632 /// Insert text at the given position
3633 bool wxRichTextParagraph::InsertText(long pos
, const wxString
& text
)
3635 wxRichTextObject
* childToUse
= NULL
;
3636 wxRichTextObjectList::compatibility_iterator nodeToUse
= wxRichTextObjectList::compatibility_iterator();
3638 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3641 wxRichTextObject
* child
= node
->GetData();
3642 if (child
->GetRange().Contains(pos
) && child
->GetRange().GetLength() > 0)
3649 node
= node
->GetNext();
3654 wxRichTextPlainText
* textObject
= wxDynamicCast(childToUse
, wxRichTextPlainText
);
3657 int posInString
= pos
- textObject
->GetRange().GetStart();
3659 wxString newText
= textObject
->GetText().Mid(0, posInString
) +
3660 text
+ textObject
->GetText().Mid(posInString
);
3661 textObject
->SetText(newText
);
3663 int textLength
= text
.length();
3665 textObject
->SetRange(wxRichTextRange(textObject
->GetRange().GetStart(),
3666 textObject
->GetRange().GetEnd() + textLength
));
3668 // Increment the end range of subsequent fragments in this paragraph.
3669 // We'll set the paragraph range itself at a higher level.
3671 wxRichTextObjectList::compatibility_iterator node
= nodeToUse
->GetNext();
3674 wxRichTextObject
* child
= node
->GetData();
3675 child
->SetRange(wxRichTextRange(textObject
->GetRange().GetStart() + textLength
,
3676 textObject
->GetRange().GetEnd() + textLength
));
3678 node
= node
->GetNext();
3685 // TODO: if not a text object, insert at closest position, e.g. in front of it
3691 // Don't pass parent initially to suppress auto-setting of parent range.
3692 // We'll do that at a higher level.
3693 wxRichTextPlainText
* textObject
= new wxRichTextPlainText(text
, this);
3695 AppendChild(textObject
);
3702 void wxRichTextParagraph::Copy(const wxRichTextParagraph
& obj
)
3704 wxRichTextBox::Copy(obj
);
3707 /// Clear the cached lines
3708 void wxRichTextParagraph::ClearLines()
3710 WX_CLEAR_LIST(wxRichTextLineList
, m_cachedLines
);
3713 /// Get/set the object size for the given range. Returns false if the range
3714 /// is invalid for this object.
3715 bool wxRichTextParagraph::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
, wxArrayInt
* partialExtents
) const
3717 if (!range
.IsWithin(GetRange()))
3720 if (flags
& wxRICHTEXT_UNFORMATTED
)
3722 // Just use unformatted data, assume no line breaks
3723 // TODO: take into account line breaks
3727 wxArrayInt childExtents
;
3734 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3738 wxRichTextObject
* child
= node
->GetData();
3739 if (!child
->GetRange().IsOutside(range
))
3743 wxRichTextRange rangeToUse
= range
;
3744 rangeToUse
.LimitTo(child
->GetRange());
3745 int childDescent
= 0;
3747 // At present wxRICHTEXT_HEIGHT_ONLY is only fast if we're already cached the size,
3748 // but it's only going to be used after caching has taken place.
3749 if ((flags
& wxRICHTEXT_HEIGHT_ONLY
) && child
->GetCachedSize().y
!= 0)
3751 childDescent
= child
->GetDescent();
3752 childSize
= child
->GetCachedSize();
3754 sz
.y
= wxMax(sz
.y
, childSize
.y
);
3755 sz
.x
+= childSize
.x
;
3756 descent
= wxMax(descent
, childDescent
);
3758 else if (child
->GetRangeSize(rangeToUse
, childSize
, childDescent
, dc
, flags
, wxPoint(position
.x
+ sz
.x
, position
.y
), p
))
3760 sz
.y
= wxMax(sz
.y
, childSize
.y
);
3761 sz
.x
+= childSize
.x
;
3762 descent
= wxMax(descent
, childDescent
);
3764 if ((flags
& wxRICHTEXT_CACHE_SIZE
) && (rangeToUse
== child
->GetRange()))
3766 child
->SetCachedSize(childSize
);
3767 child
->SetDescent(childDescent
);
3773 if (partialExtents
->GetCount() > 0)
3774 lastSize
= (*partialExtents
)[partialExtents
->GetCount()-1];
3779 for (i
= 0; i
< childExtents
.GetCount(); i
++)
3781 partialExtents
->Add(childExtents
[i
] + lastSize
);
3790 node
= node
->GetNext();
3796 // Use formatted data, with line breaks
3799 // We're going to loop through each line, and then for each line,
3800 // call GetRangeSize for the fragment that comprises that line.
3801 // Only we have to do that multiple times within the line, because
3802 // the line may be broken into pieces. For now ignore line break commands
3803 // (so we can assume that getting the unformatted size for a fragment
3804 // within a line is the actual size)
3806 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3809 wxRichTextLine
* line
= node
->GetData();
3810 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3811 if (!lineRange
.IsOutside(range
))
3815 wxRichTextObjectList::compatibility_iterator node2
= m_children
.GetFirst();
3818 wxRichTextObject
* child
= node2
->GetData();
3820 if (!child
->GetRange().IsOutside(lineRange
))
3822 wxRichTextRange rangeToUse
= lineRange
;
3823 rangeToUse
.LimitTo(child
->GetRange());
3826 int childDescent
= 0;
3827 if (child
->GetRangeSize(rangeToUse
, childSize
, childDescent
, dc
, flags
, wxPoint(position
.x
+ sz
.x
, position
.y
)))
3829 lineSize
.y
= wxMax(lineSize
.y
, childSize
.y
);
3830 lineSize
.x
+= childSize
.x
;
3832 descent
= wxMax(descent
, childDescent
);
3835 node2
= node2
->GetNext();
3838 // Increase size by a line (TODO: paragraph spacing)
3840 sz
.x
= wxMax(sz
.x
, lineSize
.x
);
3842 node
= node
->GetNext();
3849 /// Finds the absolute position and row height for the given character position
3850 bool wxRichTextParagraph::FindPosition(wxDC
& dc
, long index
, wxPoint
& pt
, int* height
, bool forceLineStart
)
3854 wxRichTextLine
* line
= ((wxRichTextParagraphLayoutBox
*)GetParent())->GetLineAtPosition(0);
3856 *height
= line
->GetSize().y
;
3858 *height
= dc
.GetCharHeight();
3860 // -1 means 'the start of the buffer'.
3863 pt
= pt
+ line
->GetPosition();
3868 // The final position in a paragraph is taken to mean the position
3869 // at the start of the next paragraph.
3870 if (index
== GetRange().GetEnd())
3872 wxRichTextParagraphLayoutBox
* parent
= wxDynamicCast(GetParent(), wxRichTextParagraphLayoutBox
);
3873 wxASSERT( parent
!= NULL
);
3875 // Find the height at the next paragraph, if any
3876 wxRichTextLine
* line
= parent
->GetLineAtPosition(index
+ 1);
3879 *height
= line
->GetSize().y
;
3880 pt
= line
->GetAbsolutePosition();
3884 *height
= dc
.GetCharHeight();
3885 int indent
= ConvertTenthsMMToPixels(dc
, m_attributes
.GetLeftIndent());
3886 pt
= wxPoint(indent
, GetCachedSize().y
);
3892 if (index
< GetRange().GetStart() || index
> GetRange().GetEnd())
3895 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3898 wxRichTextLine
* line
= node
->GetData();
3899 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3900 if (index
>= lineRange
.GetStart() && index
<= lineRange
.GetEnd())
3902 // If this is the last point in the line, and we're forcing the
3903 // returned value to be the start of the next line, do the required
3905 if (index
== lineRange
.GetEnd() && forceLineStart
)
3907 if (node
->GetNext())
3909 wxRichTextLine
* nextLine
= node
->GetNext()->GetData();
3910 *height
= nextLine
->GetSize().y
;
3911 pt
= nextLine
->GetAbsolutePosition();
3916 pt
.y
= line
->GetPosition().y
+ GetPosition().y
;
3918 wxRichTextRange
r(lineRange
.GetStart(), index
);
3922 // We find the size of the line up to this point,
3923 // then we can add this size to the line start position and
3924 // paragraph start position to find the actual position.
3926 if (GetRangeSize(r
, rangeSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, line
->GetPosition()+ GetPosition()))
3928 pt
.x
= line
->GetPosition().x
+ GetPosition().x
+ rangeSize
.x
;
3929 *height
= line
->GetSize().y
;
3936 node
= node
->GetNext();
3942 /// Hit-testing: returns a flag indicating hit test details, plus
3943 /// information about position
3944 int wxRichTextParagraph::HitTest(wxDC
& dc
, const wxPoint
& pt
, long& textPosition
)
3946 wxPoint paraPos
= GetPosition();
3948 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3951 wxRichTextLine
* line
= node
->GetData();
3952 wxPoint linePos
= paraPos
+ line
->GetPosition();
3953 wxSize lineSize
= line
->GetSize();
3954 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3956 if (pt
.y
<= linePos
.y
+ lineSize
.y
)
3958 if (pt
.x
< linePos
.x
)
3960 textPosition
= lineRange
.GetStart();
3961 return wxRICHTEXT_HITTEST_BEFORE
|wxRICHTEXT_HITTEST_OUTSIDE
;
3963 else if (pt
.x
>= (linePos
.x
+ lineSize
.x
))
3965 textPosition
= lineRange
.GetEnd();
3966 return wxRICHTEXT_HITTEST_AFTER
|wxRICHTEXT_HITTEST_OUTSIDE
;
3970 #if wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
3971 wxArrayInt partialExtents
;
3976 // This calculates the partial text extents
3977 GetRangeSize(lineRange
, paraSize
, paraDescent
, dc
, wxRICHTEXT_UNFORMATTED
, wxPoint(0,0), & partialExtents
);
3979 int lastX
= linePos
.x
;
3981 for (i
= 0; i
< partialExtents
.GetCount(); i
++)
3983 int nextX
= partialExtents
[i
] + linePos
.x
;
3985 if (pt
.x
>= lastX
&& pt
.x
<= nextX
)
3987 textPosition
= i
+ lineRange
.GetStart(); // minus 1?
3989 // So now we know it's between i-1 and i.
3990 // Let's see if we can be more precise about
3991 // which side of the position it's on.
3993 int midPoint
= (nextX
- lastX
)/2 + lastX
;
3994 if (pt
.x
>= midPoint
)
3995 return wxRICHTEXT_HITTEST_AFTER
;
3997 return wxRICHTEXT_HITTEST_BEFORE
;
4004 int lastX
= linePos
.x
;
4005 for (i
= lineRange
.GetStart(); i
<= lineRange
.GetEnd(); i
++)
4010 wxRichTextRange
rangeToUse(lineRange
.GetStart(), i
);
4012 GetRangeSize(rangeToUse
, childSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, linePos
);
4014 int nextX
= childSize
.x
+ linePos
.x
;
4016 if (pt
.x
>= lastX
&& pt
.x
<= nextX
)
4020 // So now we know it's between i-1 and i.
4021 // Let's see if we can be more precise about
4022 // which side of the position it's on.
4024 int midPoint
= (nextX
- lastX
)/2 + lastX
;
4025 if (pt
.x
>= midPoint
)
4026 return wxRICHTEXT_HITTEST_AFTER
;
4028 return wxRICHTEXT_HITTEST_BEFORE
;
4039 node
= node
->GetNext();
4042 return wxRICHTEXT_HITTEST_NONE
;
4045 /// Split an object at this position if necessary, and return
4046 /// the previous object, or NULL if inserting at beginning.
4047 wxRichTextObject
* wxRichTextParagraph::SplitAt(long pos
, wxRichTextObject
** previousObject
)
4049 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
4052 wxRichTextObject
* child
= node
->GetData();
4054 if (pos
== child
->GetRange().GetStart())
4058 if (node
->GetPrevious())
4059 *previousObject
= node
->GetPrevious()->GetData();
4061 *previousObject
= NULL
;
4067 if (child
->GetRange().Contains(pos
))
4069 // This should create a new object, transferring part of
4070 // the content to the old object and the rest to the new object.
4071 wxRichTextObject
* newObject
= child
->DoSplit(pos
);
4073 // If we couldn't split this object, just insert in front of it.
4076 // Maybe this is an empty string, try the next one
4081 // Insert the new object after 'child'
4082 if (node
->GetNext())
4083 m_children
.Insert(node
->GetNext(), newObject
);
4085 m_children
.Append(newObject
);
4086 newObject
->SetParent(this);
4089 *previousObject
= child
;
4095 node
= node
->GetNext();
4098 *previousObject
= NULL
;
4102 /// Move content to a list from obj on
4103 void wxRichTextParagraph::MoveToList(wxRichTextObject
* obj
, wxList
& list
)
4105 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(obj
);
4108 wxRichTextObject
* child
= node
->GetData();
4111 wxRichTextObjectList::compatibility_iterator oldNode
= node
;
4113 node
= node
->GetNext();
4115 m_children
.DeleteNode(oldNode
);
4119 /// Add content back from list
4120 void wxRichTextParagraph::MoveFromList(wxList
& list
)
4122 for (wxList::compatibility_iterator node
= list
.GetFirst(); node
; node
= node
->GetNext())
4124 AppendChild((wxRichTextObject
*) node
->GetData());
4129 void wxRichTextParagraph::CalculateRange(long start
, long& end
)
4131 wxRichTextCompositeObject::CalculateRange(start
, end
);
4133 // Add one for end of paragraph
4136 m_range
.SetRange(start
, end
);
4139 /// Find the object at the given position
4140 wxRichTextObject
* wxRichTextParagraph::FindObjectAtPosition(long position
)
4142 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
4145 wxRichTextObject
* obj
= node
->GetData();
4146 if (obj
->GetRange().Contains(position
))
4149 node
= node
->GetNext();
4154 /// Get the plain text searching from the start or end of the range.
4155 /// The resulting string may be shorter than the range given.
4156 bool wxRichTextParagraph::GetContiguousPlainText(wxString
& text
, const wxRichTextRange
& range
, bool fromStart
)
4158 text
= wxEmptyString
;
4162 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
4165 wxRichTextObject
* obj
= node
->GetData();
4166 if (!obj
->GetRange().IsOutside(range
))
4168 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
4171 text
+= textObj
->GetTextForRange(range
);
4179 node
= node
->GetNext();
4184 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetLast();
4187 wxRichTextObject
* obj
= node
->GetData();
4188 if (!obj
->GetRange().IsOutside(range
))
4190 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
4193 text
= textObj
->GetTextForRange(range
) + text
;
4197 text
= wxT(" ") + text
;
4201 node
= node
->GetPrevious();
4208 /// Find a suitable wrap position.
4209 bool wxRichTextParagraph::FindWrapPosition(const wxRichTextRange
& range
, wxDC
& dc
, int availableSpace
, long& wrapPosition
, wxArrayInt
* partialExtents
)
4211 if (range
.GetLength() <= 0)
4214 // Find the first position where the line exceeds the available space.
4216 long breakPosition
= range
.GetEnd();
4218 #if wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
4219 if (partialExtents
&& partialExtents
->GetCount() >= (size_t) (GetRange().GetLength()-1)) // the final position in a paragraph is the newline
4223 if (range
.GetStart() > GetRange().GetStart())
4224 widthBefore
= (*partialExtents
)[range
.GetStart() - GetRange().GetStart() - 1];
4229 for (i
= (size_t) range
.GetStart(); i
< (size_t) range
.GetEnd(); i
++)
4231 int widthFromStartOfThisRange
= (*partialExtents
)[i
- GetRange().GetStart()] - widthBefore
;
4233 if (widthFromStartOfThisRange
> availableSpace
)
4235 breakPosition
= i
-1;
4243 // Binary chop for speed
4244 long minPos
= range
.GetStart();
4245 long maxPos
= range
.GetEnd();
4248 if (minPos
== maxPos
)
4251 GetRangeSize(wxRichTextRange(range
.GetStart(), minPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
4253 if (sz
.x
> availableSpace
)
4254 breakPosition
= minPos
- 1;
4257 else if ((maxPos
- minPos
) == 1)
4260 GetRangeSize(wxRichTextRange(range
.GetStart(), minPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
4262 if (sz
.x
> availableSpace
)
4263 breakPosition
= minPos
- 1;
4266 GetRangeSize(wxRichTextRange(range
.GetStart(), maxPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
4267 if (sz
.x
> availableSpace
)
4268 breakPosition
= maxPos
-1;
4274 long nextPos
= minPos
+ ((maxPos
- minPos
) / 2);
4277 GetRangeSize(wxRichTextRange(range
.GetStart(), nextPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
4279 if (sz
.x
> availableSpace
)
4291 // Now we know the last position on the line.
4292 // Let's try to find a word break.
4295 if (GetContiguousPlainText(plainText
, wxRichTextRange(range
.GetStart(), breakPosition
), false))
4297 int newLinePos
= plainText
.Find(wxRichTextLineBreakChar
);
4298 if (newLinePos
!= wxNOT_FOUND
)
4300 breakPosition
= wxMax(0, range
.GetStart() + newLinePos
);
4304 int spacePos
= plainText
.Find(wxT(' '), true);
4305 int tabPos
= plainText
.Find(wxT('\t'), true);
4306 int pos
= wxMax(spacePos
, tabPos
);
4307 if (pos
!= wxNOT_FOUND
)
4309 int positionsFromEndOfString
= plainText
.length() - pos
- 1;
4310 breakPosition
= breakPosition
- positionsFromEndOfString
;
4315 wrapPosition
= breakPosition
;
4320 /// Get the bullet text for this paragraph.
4321 wxString
wxRichTextParagraph::GetBulletText()
4323 if (GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE
||
4324 (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP
))
4325 return wxEmptyString
;
4327 int number
= GetAttributes().GetBulletNumber();
4330 if ((GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ARABIC
) || (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
))
4332 text
.Printf(wxT("%d"), number
);
4334 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER
)
4336 // TODO: Unicode, and also check if number > 26
4337 text
.Printf(wxT("%c"), (wxChar
) (number
+64));
4339 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER
)
4341 // TODO: Unicode, and also check if number > 26
4342 text
.Printf(wxT("%c"), (wxChar
) (number
+96));
4344 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER
)
4346 text
= wxRichTextDecimalToRoman(number
);
4348 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER
)
4350 text
= wxRichTextDecimalToRoman(number
);
4353 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL
)
4355 text
= GetAttributes().GetBulletText();
4358 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
)
4360 // The outline style relies on the text being computed statically,
4361 // since it depends on other levels points (e.g. 1.2.1.1). So normally the bullet text
4362 // should be stored in the attributes; if not, just use the number for this
4363 // level, as previously computed.
4364 if (!GetAttributes().GetBulletText().IsEmpty())
4365 text
= GetAttributes().GetBulletText();
4368 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PARENTHESES
)
4370 text
= wxT("(") + text
+ wxT(")");
4372 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS
)
4374 text
= text
+ wxT(")");
4377 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PERIOD
)
4385 /// Allocate or reuse a line object
4386 wxRichTextLine
* wxRichTextParagraph::AllocateLine(int pos
)
4388 if (pos
< (int) m_cachedLines
.GetCount())
4390 wxRichTextLine
* line
= m_cachedLines
.Item(pos
)->GetData();
4396 wxRichTextLine
* line
= new wxRichTextLine(this);
4397 m_cachedLines
.Append(line
);
4402 /// Clear remaining unused line objects, if any
4403 bool wxRichTextParagraph::ClearUnusedLines(int lineCount
)
4405 int cachedLineCount
= m_cachedLines
.GetCount();
4406 if ((int) cachedLineCount
> lineCount
)
4408 for (int i
= 0; i
< (int) (cachedLineCount
- lineCount
); i
++)
4410 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetLast();
4411 wxRichTextLine
* line
= node
->GetData();
4412 m_cachedLines
.Erase(node
);
4419 /// Get combined attributes of the base style, paragraph style and character style. We use this to dynamically
4420 /// retrieve the actual style.
4421 wxTextAttr
wxRichTextParagraph::GetCombinedAttributes(const wxTextAttr
& contentStyle
) const
4424 wxRichTextBuffer
* buf
= wxDynamicCast(GetParent(), wxRichTextBuffer
);
4427 attr
= buf
->GetBasicStyle();
4428 wxRichTextApplyStyle(attr
, GetAttributes());
4431 attr
= GetAttributes();
4433 wxRichTextApplyStyle(attr
, contentStyle
);
4437 /// Get combined attributes of the base style and paragraph style.
4438 wxTextAttr
wxRichTextParagraph::GetCombinedAttributes() const
4441 wxRichTextBuffer
* buf
= wxDynamicCast(GetParent(), wxRichTextBuffer
);
4444 attr
= buf
->GetBasicStyle();
4445 wxRichTextApplyStyle(attr
, GetAttributes());
4448 attr
= GetAttributes();
4453 /// Create default tabstop array
4454 void wxRichTextParagraph::InitDefaultTabs()
4456 // create a default tab list at 10 mm each.
4457 for (int i
= 0; i
< 20; ++i
)
4459 sm_defaultTabs
.Add(i
*100);
4463 /// Clear default tabstop array
4464 void wxRichTextParagraph::ClearDefaultTabs()
4466 sm_defaultTabs
.Clear();
4469 /// Get the first position from pos that has a line break character.
4470 long wxRichTextParagraph::GetFirstLineBreakPosition(long pos
)
4472 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
4475 wxRichTextObject
* obj
= node
->GetData();
4476 if (pos
>= obj
->GetRange().GetStart() && pos
<= obj
->GetRange().GetEnd())
4478 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
4481 long breakPos
= textObj
->GetFirstLineBreakPosition(pos
);
4486 node
= node
->GetNext();
4493 * This object represents a line in a paragraph, and stores
4494 * offsets from the start of the paragraph representing the
4495 * start and end positions of the line.
4498 wxRichTextLine::wxRichTextLine(wxRichTextParagraph
* parent
)
4504 void wxRichTextLine::Init(wxRichTextParagraph
* parent
)
4507 m_range
.SetRange(-1, -1);
4508 m_pos
= wxPoint(0, 0);
4509 m_size
= wxSize(0, 0);
4511 #if wxRICHTEXT_USE_OPTIMIZED_LINE_DRAWING
4512 m_objectSizes
.Clear();
4517 void wxRichTextLine::Copy(const wxRichTextLine
& obj
)
4519 m_range
= obj
.m_range
;
4520 #if wxRICHTEXT_USE_OPTIMIZED_LINE_DRAWING
4521 m_objectSizes
= obj
.m_objectSizes
;
4525 /// Get the absolute object position
4526 wxPoint
wxRichTextLine::GetAbsolutePosition() const
4528 return m_parent
->GetPosition() + m_pos
;
4531 /// Get the absolute range
4532 wxRichTextRange
wxRichTextLine::GetAbsoluteRange() const
4534 wxRichTextRange
range(m_range
.GetStart() + m_parent
->GetRange().GetStart(), 0);
4535 range
.SetEnd(range
.GetStart() + m_range
.GetLength()-1);
4540 * wxRichTextPlainText
4541 * This object represents a single piece of text.
4544 IMPLEMENT_DYNAMIC_CLASS(wxRichTextPlainText
, wxRichTextObject
)
4546 wxRichTextPlainText::wxRichTextPlainText(const wxString
& text
, wxRichTextObject
* parent
, wxTextAttr
* style
):
4547 wxRichTextObject(parent
)
4550 SetAttributes(*style
);
4555 #define USE_KERNING_FIX 1
4557 // If insufficient tabs are defined, this is the tab width used
4558 #define WIDTH_FOR_DEFAULT_TABS 50
4561 bool wxRichTextPlainText::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int descent
, int WXUNUSED(style
))
4563 wxRichTextParagraph
* para
= wxDynamicCast(GetParent(), wxRichTextParagraph
);
4564 wxASSERT (para
!= NULL
);
4566 wxTextAttr
textAttr(para
? para
->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4568 int offset
= GetRange().GetStart();
4570 // Replace line break characters with spaces
4571 wxString str
= m_text
;
4572 wxString toRemove
= wxRichTextLineBreakChar
;
4573 str
.Replace(toRemove
, wxT(" "));
4574 if (textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
4577 long len
= range
.GetLength();
4578 wxString stringChunk
= str
.Mid(range
.GetStart() - offset
, (size_t) len
);
4580 // Test for the optimized situations where all is selected, or none
4583 wxFont
textFont(GetBuffer()->GetFontTable().FindFont(textAttr
));
4584 wxCheckSetFont(dc
, textFont
);
4585 int charHeight
= dc
.GetCharHeight();
4588 if ( textFont
.Ok() )
4590 if ( textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUPERSCRIPT
) )
4592 double size
= static_cast<double>(textFont
.GetPointSize()) / wxSCRIPT_MUL_FACTOR
;
4593 textFont
.SetPointSize( static_cast<int>(size
) );
4596 wxCheckSetFont(dc
, textFont
);
4598 else if ( textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUBSCRIPT
) )
4600 double size
= static_cast<double>(textFont
.GetPointSize()) / wxSCRIPT_MUL_FACTOR
;
4601 textFont
.SetPointSize( static_cast<int>(size
) );
4603 int sub_height
= static_cast<int>( static_cast<double>(charHeight
) / wxSCRIPT_MUL_FACTOR
);
4604 y
= rect
.y
+ (rect
.height
- sub_height
+ (descent
- m_descent
));
4605 wxCheckSetFont(dc
, textFont
);
4610 y
= rect
.y
+ (rect
.height
- charHeight
- (descent
- m_descent
));
4616 y
= rect
.y
+ (rect
.height
- charHeight
- (descent
- m_descent
));
4619 // (a) All selected.
4620 if (selectionRange
.GetStart() <= range
.GetStart() && selectionRange
.GetEnd() >= range
.GetEnd())
4622 DrawTabbedString(dc
, textAttr
, rect
, stringChunk
, x
, y
, true);
4624 // (b) None selected.
4625 else if (selectionRange
.GetEnd() < range
.GetStart() || selectionRange
.GetStart() > range
.GetEnd())
4627 // Draw all unselected
4628 DrawTabbedString(dc
, textAttr
, rect
, stringChunk
, x
, y
, false);
4632 // (c) Part selected, part not
4633 // Let's draw unselected chunk, selected chunk, then unselected chunk.
4635 dc
.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT
);
4637 // 1. Initial unselected chunk, if any, up until start of selection.
4638 if (selectionRange
.GetStart() > range
.GetStart() && selectionRange
.GetStart() <= range
.GetEnd())
4640 int r1
= range
.GetStart();
4641 int s1
= selectionRange
.GetStart()-1;
4642 int fragmentLen
= s1
- r1
+ 1;
4643 if (fragmentLen
< 0)
4644 wxLogDebug(wxT("Mid(%d, %d"), (int)(r1
- offset
), (int)fragmentLen
);
4645 wxString stringFragment
= str
.Mid(r1
- offset
, fragmentLen
);
4647 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, false);
4650 if (stringChunk
.Find(wxT("\t")) == wxNOT_FOUND
)
4652 // Compensate for kerning difference
4653 wxString
stringFragment2(str
.Mid(r1
- offset
, fragmentLen
+1));
4654 wxString
stringFragment3(str
.Mid(r1
- offset
+ fragmentLen
, 1));
4656 wxCoord w1
, h1
, w2
, h2
, w3
, h3
;
4657 dc
.GetTextExtent(stringFragment
, & w1
, & h1
);
4658 dc
.GetTextExtent(stringFragment2
, & w2
, & h2
);
4659 dc
.GetTextExtent(stringFragment3
, & w3
, & h3
);
4661 int kerningDiff
= (w1
+ w3
) - w2
;
4662 x
= x
- kerningDiff
;
4667 // 2. Selected chunk, if any.
4668 if (selectionRange
.GetEnd() >= range
.GetStart())
4670 int s1
= wxMax(selectionRange
.GetStart(), range
.GetStart());
4671 int s2
= wxMin(selectionRange
.GetEnd(), range
.GetEnd());
4673 int fragmentLen
= s2
- s1
+ 1;
4674 if (fragmentLen
< 0)
4675 wxLogDebug(wxT("Mid(%d, %d"), (int)(s1
- offset
), (int)fragmentLen
);
4676 wxString stringFragment
= str
.Mid(s1
- offset
, fragmentLen
);
4678 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, true);
4681 if (stringChunk
.Find(wxT("\t")) == wxNOT_FOUND
)
4683 // Compensate for kerning difference
4684 wxString
stringFragment2(str
.Mid(s1
- offset
, fragmentLen
+1));
4685 wxString
stringFragment3(str
.Mid(s1
- offset
+ fragmentLen
, 1));
4687 wxCoord w1
, h1
, w2
, h2
, w3
, h3
;
4688 dc
.GetTextExtent(stringFragment
, & w1
, & h1
);
4689 dc
.GetTextExtent(stringFragment2
, & w2
, & h2
);
4690 dc
.GetTextExtent(stringFragment3
, & w3
, & h3
);
4692 int kerningDiff
= (w1
+ w3
) - w2
;
4693 x
= x
- kerningDiff
;
4698 // 3. Remaining unselected chunk, if any
4699 if (selectionRange
.GetEnd() < range
.GetEnd())
4701 int s2
= wxMin(selectionRange
.GetEnd()+1, range
.GetEnd());
4702 int r2
= range
.GetEnd();
4704 int fragmentLen
= r2
- s2
+ 1;
4705 if (fragmentLen
< 0)
4706 wxLogDebug(wxT("Mid(%d, %d"), (int)(s2
- offset
), (int)fragmentLen
);
4707 wxString stringFragment
= str
.Mid(s2
- offset
, fragmentLen
);
4709 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, false);
4716 bool wxRichTextPlainText::DrawTabbedString(wxDC
& dc
, const wxTextAttr
& attr
, const wxRect
& rect
,wxString
& str
, wxCoord
& x
, wxCoord
& y
, bool selected
)
4718 bool hasTabs
= (str
.Find(wxT('\t')) != wxNOT_FOUND
);
4720 wxArrayInt tabArray
;
4724 if (attr
.GetTabs().IsEmpty())
4725 tabArray
= wxRichTextParagraph::GetDefaultTabs();
4727 tabArray
= attr
.GetTabs();
4728 tabCount
= tabArray
.GetCount();
4730 for (int i
= 0; i
< tabCount
; ++i
)
4732 int pos
= tabArray
[i
];
4733 pos
= ConvertTenthsMMToPixels(dc
, pos
);
4740 int nextTabPos
= -1;
4746 wxColour
highlightColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT
));
4747 wxColour
highlightTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT
));
4749 wxCheckSetBrush(dc
, wxBrush(highlightColour
));
4750 wxCheckSetPen(dc
, wxPen(highlightColour
));
4751 dc
.SetTextForeground(highlightTextColour
);
4752 dc
.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT
);
4756 dc
.SetTextForeground(attr
.GetTextColour());
4758 if (attr
.HasFlag(wxTEXT_ATTR_BACKGROUND_COLOUR
) && attr
.GetBackgroundColour().IsOk())
4760 dc
.SetBackgroundMode(wxBRUSHSTYLE_SOLID
);
4761 dc
.SetTextBackground(attr
.GetBackgroundColour());
4764 dc
.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT
);
4769 // the string has a tab
4770 // break up the string at the Tab
4771 wxString stringChunk
= str
.BeforeFirst(wxT('\t'));
4772 str
= str
.AfterFirst(wxT('\t'));
4773 dc
.GetTextExtent(stringChunk
, & w
, & h
);
4775 bool not_found
= true;
4776 for (int i
= 0; i
< tabCount
&& not_found
; ++i
)
4778 nextTabPos
= tabArray
.Item(i
);
4780 // Find the next tab position.
4781 // Even if we're at the end of the tab array, we must still draw the chunk.
4783 if (nextTabPos
> tabPos
|| (i
== (tabCount
- 1)))
4785 if (nextTabPos
<= tabPos
)
4787 int defaultTabWidth
= ConvertTenthsMMToPixels(dc
, WIDTH_FOR_DEFAULT_TABS
);
4788 nextTabPos
= tabPos
+ defaultTabWidth
;
4795 wxRect
selRect(x
, rect
.y
, w
, rect
.GetHeight());
4796 dc
.DrawRectangle(selRect
);
4798 dc
.DrawText(stringChunk
, x
, y
);
4800 if (attr
.HasTextEffects() && (attr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH
))
4802 wxPen oldPen
= dc
.GetPen();
4803 wxCheckSetPen(dc
, wxPen(attr
.GetTextColour(), 1));
4804 dc
.DrawLine(x
, (int) (y
+(h
/2)+0.5), x
+w
, (int) (y
+(h
/2)+0.5));
4805 wxCheckSetPen(dc
, oldPen
);
4811 hasTabs
= (str
.Find(wxT('\t')) != wxNOT_FOUND
);
4816 dc
.GetTextExtent(str
, & w
, & h
);
4819 wxRect
selRect(x
, rect
.y
, w
, rect
.GetHeight());
4820 dc
.DrawRectangle(selRect
);
4822 dc
.DrawText(str
, x
, y
);
4824 if (attr
.HasTextEffects() && (attr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH
))
4826 wxPen oldPen
= dc
.GetPen();
4827 wxCheckSetPen(dc
, wxPen(attr
.GetTextColour(), 1));
4828 dc
.DrawLine(x
, (int) (y
+(h
/2)+0.5), x
+w
, (int) (y
+(h
/2)+0.5));
4829 wxCheckSetPen(dc
, oldPen
);
4838 /// Lay the item out
4839 bool wxRichTextPlainText::Layout(wxDC
& dc
, const wxRect
& WXUNUSED(rect
), int WXUNUSED(style
))
4841 // Only lay out if we haven't already cached the size
4843 GetRangeSize(GetRange(), m_size
, m_descent
, dc
, 0, wxPoint(0, 0));
4849 void wxRichTextPlainText::Copy(const wxRichTextPlainText
& obj
)
4851 wxRichTextObject::Copy(obj
);
4853 m_text
= obj
.m_text
;
4856 /// Get/set the object size for the given range. Returns false if the range
4857 /// is invalid for this object.
4858 bool wxRichTextPlainText::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int WXUNUSED(flags
), wxPoint position
, wxArrayInt
* partialExtents
) const
4860 if (!range
.IsWithin(GetRange()))
4863 wxRichTextParagraph
* para
= wxDynamicCast(GetParent(), wxRichTextParagraph
);
4864 wxASSERT (para
!= NULL
);
4866 wxTextAttr
textAttr(para
? para
->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4868 // Always assume unformatted text, since at this level we have no knowledge
4869 // of line breaks - and we don't need it, since we'll calculate size within
4870 // formatted text by doing it in chunks according to the line ranges
4872 bool bScript(false);
4873 wxFont
font(GetBuffer()->GetFontTable().FindFont(textAttr
));
4876 if ( textAttr
.HasTextEffects() && ( (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUPERSCRIPT
)
4877 || (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUBSCRIPT
) ) )
4879 wxFont textFont
= font
;
4880 double size
= static_cast<double>(textFont
.GetPointSize()) / wxSCRIPT_MUL_FACTOR
;
4881 textFont
.SetPointSize( static_cast<int>(size
) );
4882 wxCheckSetFont(dc
, textFont
);
4887 wxCheckSetFont(dc
, font
);
4891 bool haveDescent
= false;
4892 int startPos
= range
.GetStart() - GetRange().GetStart();
4893 long len
= range
.GetLength();
4895 wxString
str(m_text
);
4896 wxString toReplace
= wxRichTextLineBreakChar
;
4897 str
.Replace(toReplace
, wxT(" "));
4899 wxString stringChunk
= str
.Mid(startPos
, (size_t) len
);
4901 if (textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
4902 stringChunk
.MakeUpper();
4906 if (stringChunk
.Find(wxT('\t')) != wxNOT_FOUND
)
4908 // the string has a tab
4909 wxArrayInt tabArray
;
4910 if (textAttr
.GetTabs().IsEmpty())
4911 tabArray
= wxRichTextParagraph::GetDefaultTabs();
4913 tabArray
= textAttr
.GetTabs();
4915 int tabCount
= tabArray
.GetCount();
4917 for (int i
= 0; i
< tabCount
; ++i
)
4919 int pos
= tabArray
[i
];
4920 pos
= ((wxRichTextPlainText
*) this)->ConvertTenthsMMToPixels(dc
, pos
);
4924 int nextTabPos
= -1;
4926 while (stringChunk
.Find(wxT('\t')) >= 0)
4928 int absoluteWidth
= 0;
4930 // the string has a tab
4931 // break up the string at the Tab
4932 wxString stringFragment
= stringChunk
.BeforeFirst(wxT('\t'));
4933 stringChunk
= stringChunk
.AfterFirst(wxT('\t'));
4938 if (partialExtents
->GetCount() > 0)
4939 oldWidth
= (*partialExtents
)[partialExtents
->GetCount()-1];
4943 // Add these partial extents
4945 dc
.GetPartialTextExtents(stringFragment
, p
);
4947 for (j
= 0; j
< p
.GetCount(); j
++)
4948 partialExtents
->Add(oldWidth
+ p
[j
]);
4950 if (partialExtents
->GetCount() > 0)
4951 absoluteWidth
= (*partialExtents
)[(*partialExtents
).GetCount()-1] + position
.x
;
4953 absoluteWidth
= position
.x
;
4957 dc
.GetTextExtent(stringFragment
, & w
, & h
);
4959 absoluteWidth
= width
+ position
.x
;
4963 bool notFound
= true;
4964 for (int i
= 0; i
< tabCount
&& notFound
; ++i
)
4966 nextTabPos
= tabArray
.Item(i
);
4968 // Find the next tab position.
4969 // Even if we're at the end of the tab array, we must still process the chunk.
4971 if (nextTabPos
> absoluteWidth
|| (i
== (tabCount
- 1)))
4973 if (nextTabPos
<= absoluteWidth
)
4975 int defaultTabWidth
= ((wxRichTextPlainText
*) this)->ConvertTenthsMMToPixels(dc
, WIDTH_FOR_DEFAULT_TABS
);
4976 nextTabPos
= absoluteWidth
+ defaultTabWidth
;
4980 width
= nextTabPos
- position
.x
;
4983 partialExtents
->Add(width
);
4989 if (!stringChunk
.IsEmpty())
4994 if (partialExtents
->GetCount() > 0)
4995 oldWidth
= (*partialExtents
)[partialExtents
->GetCount()-1];
4999 // Add these partial extents
5001 dc
.GetPartialTextExtents(stringChunk
, p
);
5003 for (j
= 0; j
< p
.GetCount(); j
++)
5004 partialExtents
->Add(oldWidth
+ p
[j
]);
5008 dc
.GetTextExtent(stringChunk
, & w
, & h
, & descent
);
5016 int charHeight
= dc
.GetCharHeight();
5017 if ((*partialExtents
).GetCount() > 0)
5018 w
= (*partialExtents
)[partialExtents
->GetCount()-1];
5021 size
= wxSize(w
, charHeight
);
5025 size
= wxSize(width
, dc
.GetCharHeight());
5029 dc
.GetTextExtent(wxT("X"), & w
, & h
, & descent
);
5037 /// Do a split, returning an object containing the second part, and setting
5038 /// the first part in 'this'.
5039 wxRichTextObject
* wxRichTextPlainText::DoSplit(long pos
)
5041 long index
= pos
- GetRange().GetStart();
5043 if (index
< 0 || index
>= (int) m_text
.length())
5046 wxString firstPart
= m_text
.Mid(0, index
);
5047 wxString secondPart
= m_text
.Mid(index
);
5051 wxRichTextPlainText
* newObject
= new wxRichTextPlainText(secondPart
);
5052 newObject
->SetAttributes(GetAttributes());
5054 newObject
->SetRange(wxRichTextRange(pos
, GetRange().GetEnd()));
5055 GetRange().SetEnd(pos
-1);
5061 void wxRichTextPlainText::CalculateRange(long start
, long& end
)
5063 end
= start
+ m_text
.length() - 1;
5064 m_range
.SetRange(start
, end
);
5068 bool wxRichTextPlainText::DeleteRange(const wxRichTextRange
& range
)
5070 wxRichTextRange r
= range
;
5072 r
.LimitTo(GetRange());
5074 if (r
.GetStart() == GetRange().GetStart() && r
.GetEnd() == GetRange().GetEnd())
5080 long startIndex
= r
.GetStart() - GetRange().GetStart();
5081 long len
= r
.GetLength();
5083 m_text
= m_text
.Mid(0, startIndex
) + m_text
.Mid(startIndex
+len
);
5087 /// Get text for the given range.
5088 wxString
wxRichTextPlainText::GetTextForRange(const wxRichTextRange
& range
) const
5090 wxRichTextRange r
= range
;
5092 r
.LimitTo(GetRange());
5094 long startIndex
= r
.GetStart() - GetRange().GetStart();
5095 long len
= r
.GetLength();
5097 return m_text
.Mid(startIndex
, len
);
5100 /// Returns true if this object can merge itself with the given one.
5101 bool wxRichTextPlainText::CanMerge(wxRichTextObject
* object
) const
5103 return object
->GetClassInfo() == CLASSINFO(wxRichTextPlainText
) &&
5104 (m_text
.empty() || wxTextAttrEq(GetAttributes(), object
->GetAttributes()));
5107 /// Returns true if this object merged itself with the given one.
5108 /// The calling code will then delete the given object.
5109 bool wxRichTextPlainText::Merge(wxRichTextObject
* object
)
5111 wxRichTextPlainText
* textObject
= wxDynamicCast(object
, wxRichTextPlainText
);
5112 wxASSERT( textObject
!= NULL
);
5116 m_text
+= textObject
->GetText();
5117 wxRichTextApplyStyle(m_attributes
, textObject
->GetAttributes());
5124 /// Dump to output stream for debugging
5125 void wxRichTextPlainText::Dump(wxTextOutputStream
& stream
)
5127 wxRichTextObject::Dump(stream
);
5128 stream
<< m_text
<< wxT("\n");
5131 /// Get the first position from pos that has a line break character.
5132 long wxRichTextPlainText::GetFirstLineBreakPosition(long pos
)
5135 int len
= m_text
.length();
5136 int startPos
= pos
- m_range
.GetStart();
5137 for (i
= startPos
; i
< len
; i
++)
5139 wxChar ch
= m_text
[i
];
5140 if (ch
== wxRichTextLineBreakChar
)
5142 return i
+ m_range
.GetStart();
5150 * This is a kind of box, used to represent the whole buffer
5153 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBuffer
, wxRichTextParagraphLayoutBox
)
5155 wxList
wxRichTextBuffer::sm_handlers
;
5156 wxRichTextRenderer
* wxRichTextBuffer::sm_renderer
= NULL
;
5157 int wxRichTextBuffer::sm_bulletRightMargin
= 20;
5158 float wxRichTextBuffer::sm_bulletProportion
= (float) 0.3;
5161 void wxRichTextBuffer::Init()
5163 m_commandProcessor
= new wxCommandProcessor
;
5164 m_styleSheet
= NULL
;
5166 m_batchedCommandDepth
= 0;
5167 m_batchedCommand
= NULL
;
5174 wxRichTextBuffer::~wxRichTextBuffer()
5176 delete m_commandProcessor
;
5177 delete m_batchedCommand
;
5180 ClearEventHandlers();
5183 void wxRichTextBuffer::ResetAndClearCommands()
5187 GetCommandProcessor()->ClearCommands();
5190 Invalidate(wxRICHTEXT_ALL
);
5193 void wxRichTextBuffer::Copy(const wxRichTextBuffer
& obj
)
5195 wxRichTextParagraphLayoutBox::Copy(obj
);
5197 m_styleSheet
= obj
.m_styleSheet
;
5198 m_modified
= obj
.m_modified
;
5199 m_batchedCommandDepth
= obj
.m_batchedCommandDepth
;
5200 m_batchedCommand
= obj
.m_batchedCommand
;
5201 m_suppressUndo
= obj
.m_suppressUndo
;
5204 /// Push style sheet to top of stack
5205 bool wxRichTextBuffer::PushStyleSheet(wxRichTextStyleSheet
* styleSheet
)
5208 styleSheet
->InsertSheet(m_styleSheet
);
5210 SetStyleSheet(styleSheet
);
5215 /// Pop style sheet from top of stack
5216 wxRichTextStyleSheet
* wxRichTextBuffer::PopStyleSheet()
5220 wxRichTextStyleSheet
* oldSheet
= m_styleSheet
;
5221 m_styleSheet
= oldSheet
->GetNextSheet();
5230 /// Submit command to insert paragraphs
5231 bool wxRichTextBuffer::InsertParagraphsWithUndo(long pos
, const wxRichTextParagraphLayoutBox
& paragraphs
, wxRichTextCtrl
* ctrl
, int flags
)
5233 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
5235 wxTextAttr
attr(GetDefaultStyle());
5237 wxTextAttr
* p
= NULL
;
5238 wxTextAttr paraAttr
;
5239 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
5241 paraAttr
= GetStyleForNewParagraph(pos
);
5242 if (!paraAttr
.IsDefault())
5248 action
->GetNewParagraphs() = paragraphs
;
5250 if (p
&& !p
->IsDefault())
5252 for (wxRichTextObjectList::compatibility_iterator node
= action
->GetNewParagraphs().GetChildren().GetFirst(); node
; node
= node
->GetNext())
5254 wxRichTextObject
* child
= node
->GetData();
5255 child
->SetAttributes(*p
);
5259 action
->SetPosition(pos
);
5261 wxRichTextRange range
= wxRichTextRange(pos
, pos
+ paragraphs
.GetRange().GetEnd() - 1);
5262 if (!paragraphs
.GetPartialParagraph())
5263 range
.SetEnd(range
.GetEnd()+1);
5265 // Set the range we'll need to delete in Undo
5266 action
->SetRange(range
);
5268 SubmitAction(action
);
5273 /// Submit command to insert the given text
5274 bool wxRichTextBuffer::InsertTextWithUndo(long pos
, const wxString
& text
, wxRichTextCtrl
* ctrl
, int flags
)
5276 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
5278 wxTextAttr
* p
= NULL
;
5279 wxTextAttr paraAttr
;
5280 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
5282 // Get appropriate paragraph style
5283 paraAttr
= GetStyleForNewParagraph(pos
, false, false);
5284 if (!paraAttr
.IsDefault())
5288 action
->GetNewParagraphs().AddParagraphs(text
, p
);
5290 int length
= action
->GetNewParagraphs().GetRange().GetLength();
5292 if (text
.length() > 0 && text
.Last() != wxT('\n'))
5294 // Don't count the newline when undoing
5296 action
->GetNewParagraphs().SetPartialParagraph(true);
5298 else if (text
.length() > 0 && text
.Last() == wxT('\n'))
5301 action
->SetPosition(pos
);
5303 // Set the range we'll need to delete in Undo
5304 action
->SetRange(wxRichTextRange(pos
, pos
+ length
- 1));
5306 SubmitAction(action
);
5311 /// Submit command to insert the given text
5312 bool wxRichTextBuffer::InsertNewlineWithUndo(long pos
, wxRichTextCtrl
* ctrl
, int flags
)
5314 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
5316 wxTextAttr
* p
= NULL
;
5317 wxTextAttr paraAttr
;
5318 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
5320 paraAttr
= GetStyleForNewParagraph(pos
, false, true /* look for next paragraph style */);
5321 if (!paraAttr
.IsDefault())
5325 wxTextAttr
attr(GetDefaultStyle());
5327 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(wxEmptyString
, this, & attr
);
5328 action
->GetNewParagraphs().AppendChild(newPara
);
5329 action
->GetNewParagraphs().UpdateRanges();
5330 action
->GetNewParagraphs().SetPartialParagraph(false);
5331 wxRichTextParagraph
* para
= GetParagraphAtPosition(pos
, false);
5335 newPara
->SetAttributes(*p
);
5337 if (flags
& wxRICHTEXT_INSERT_INTERACTIVE
)
5339 if (para
&& para
->GetRange().GetEnd() == pos
)
5341 if (newPara
->GetAttributes().HasBulletNumber())
5342 newPara
->GetAttributes().SetBulletNumber(newPara
->GetAttributes().GetBulletNumber()+1);
5345 action
->SetPosition(pos
);
5347 // Use the default character style
5348 // Use the default character style
5349 if (!GetDefaultStyle().IsDefault() && newPara
->GetChildren().GetFirst())
5351 // Check whether the default style merely reflects the paragraph/basic style,
5352 // in which case don't apply it.
5353 wxTextAttrEx
defaultStyle(GetDefaultStyle());
5354 wxTextAttrEx toApply
;
5357 wxRichTextAttr combinedAttr
= para
->GetCombinedAttributes();
5358 wxTextAttrEx newAttr
;
5359 // This filters out attributes that are accounted for by the current
5360 // paragraph/basic style
5361 wxRichTextApplyStyle(toApply
, defaultStyle
, & combinedAttr
);
5364 toApply
= defaultStyle
;
5366 if (!toApply
.IsDefault())
5367 newPara
->GetChildren().GetFirst()->GetData()->SetAttributes(toApply
);
5370 // Set the range we'll need to delete in Undo
5371 action
->SetRange(wxRichTextRange(pos1
, pos1
));
5373 SubmitAction(action
);
5378 /// Submit command to insert the given image
5379 bool wxRichTextBuffer::InsertImageWithUndo(long pos
, const wxRichTextImageBlock
& imageBlock
, wxRichTextCtrl
* ctrl
, int flags
)
5381 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Image"), wxRICHTEXT_INSERT
, this, ctrl
, false);
5383 wxTextAttr
* p
= NULL
;
5384 wxTextAttr paraAttr
;
5385 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
5387 paraAttr
= GetStyleForNewParagraph(pos
);
5388 if (!paraAttr
.IsDefault())
5392 wxTextAttr
attr(GetDefaultStyle());
5394 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(this, & attr
);
5396 newPara
->SetAttributes(*p
);
5398 wxRichTextImage
* imageObject
= new wxRichTextImage(imageBlock
, newPara
);
5399 newPara
->AppendChild(imageObject
);
5400 action
->GetNewParagraphs().AppendChild(newPara
);
5401 action
->GetNewParagraphs().UpdateRanges();
5403 action
->GetNewParagraphs().SetPartialParagraph(true);
5405 action
->SetPosition(pos
);
5407 // Set the range we'll need to delete in Undo
5408 action
->SetRange(wxRichTextRange(pos
, pos
));
5410 SubmitAction(action
);
5415 /// Get the style that is appropriate for a new paragraph at this position.
5416 /// If the previous paragraph has a paragraph style name, look up the next-paragraph
5418 wxTextAttr
wxRichTextBuffer::GetStyleForNewParagraph(long pos
, bool caretPosition
, bool lookUpNewParaStyle
) const
5420 wxRichTextParagraph
* para
= GetParagraphAtPosition(pos
, caretPosition
);
5424 bool foundAttributes
= false;
5426 // Look for a matching paragraph style
5427 if (lookUpNewParaStyle
&& !para
->GetAttributes().GetParagraphStyleName().IsEmpty() && GetStyleSheet())
5429 wxRichTextParagraphStyleDefinition
* paraDef
= GetStyleSheet()->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
5432 // If we're not at the end of the paragraph, then we apply THIS style, and not the designated next style.
5433 if (para
->GetRange().GetEnd() == pos
&& !paraDef
->GetNextStyle().IsEmpty())
5435 wxRichTextParagraphStyleDefinition
* nextParaDef
= GetStyleSheet()->FindParagraphStyle(paraDef
->GetNextStyle());
5438 foundAttributes
= true;
5439 attr
= nextParaDef
->GetStyleMergedWithBase(GetStyleSheet());
5443 // If we didn't find the 'next style', use this style instead.
5444 if (!foundAttributes
)
5446 foundAttributes
= true;
5447 attr
= paraDef
->GetStyleMergedWithBase(GetStyleSheet());
5451 if (!foundAttributes
)
5453 attr
= para
->GetAttributes();
5454 int flags
= attr
.GetFlags();
5456 // Eliminate character styles
5457 flags
&= ( (~ wxTEXT_ATTR_FONT
) |
5458 (~ wxTEXT_ATTR_TEXT_COLOUR
) |
5459 (~ wxTEXT_ATTR_BACKGROUND_COLOUR
) );
5460 attr
.SetFlags(flags
);
5463 // Now see if we need to number the paragraph.
5464 if (attr
.HasBulletStyle())
5466 wxTextAttr numberingAttr
;
5467 if (FindNextParagraphNumber(para
, numberingAttr
))
5468 wxRichTextApplyStyle(attr
, (const wxTextAttr
&) numberingAttr
);
5474 return wxTextAttr();
5477 /// Submit command to delete this range
5478 bool wxRichTextBuffer::DeleteRangeWithUndo(const wxRichTextRange
& range
, wxRichTextCtrl
* ctrl
)
5480 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Delete"), wxRICHTEXT_DELETE
, this, ctrl
);
5482 action
->SetPosition(ctrl
->GetCaretPosition());
5484 // Set the range to delete
5485 action
->SetRange(range
);
5487 // Copy the fragment that we'll need to restore in Undo
5488 CopyFragment(range
, action
->GetOldParagraphs());
5490 // See if we're deleting a paragraph marker, in which case we need to
5491 // make a note not to copy the attributes from the 2nd paragraph to the 1st.
5492 if (range
.GetStart() == range
.GetEnd())
5494 wxRichTextParagraph
* para
= GetParagraphAtPosition(range
.GetStart());
5495 if (para
&& para
->GetRange().GetEnd() == range
.GetEnd())
5497 wxRichTextParagraph
* nextPara
= GetParagraphAtPosition(range
.GetStart()+1);
5498 if (nextPara
&& nextPara
!= para
)
5500 action
->GetOldParagraphs().GetChildren().GetFirst()->GetData()->SetAttributes(nextPara
->GetAttributes());
5501 action
->GetOldParagraphs().GetAttributes().SetFlags(action
->GetOldParagraphs().GetAttributes().GetFlags() | wxTEXT_ATTR_KEEP_FIRST_PARA_STYLE
);
5506 SubmitAction(action
);
5511 /// Collapse undo/redo commands
5512 bool wxRichTextBuffer::BeginBatchUndo(const wxString
& cmdName
)
5514 if (m_batchedCommandDepth
== 0)
5516 wxASSERT(m_batchedCommand
== NULL
);
5517 if (m_batchedCommand
)
5519 GetCommandProcessor()->Store(m_batchedCommand
);
5521 m_batchedCommand
= new wxRichTextCommand(cmdName
);
5524 m_batchedCommandDepth
++;
5529 /// Collapse undo/redo commands
5530 bool wxRichTextBuffer::EndBatchUndo()
5532 m_batchedCommandDepth
--;
5534 wxASSERT(m_batchedCommandDepth
>= 0);
5535 wxASSERT(m_batchedCommand
!= NULL
);
5537 if (m_batchedCommandDepth
== 0)
5539 GetCommandProcessor()->Store(m_batchedCommand
);
5540 m_batchedCommand
= NULL
;
5546 /// Submit immediately, or delay according to whether collapsing is on
5547 bool wxRichTextBuffer::SubmitAction(wxRichTextAction
* action
)
5549 if (BatchingUndo() && m_batchedCommand
&& !SuppressingUndo())
5551 wxRichTextCommand
* cmd
= new wxRichTextCommand(action
->GetName());
5552 cmd
->AddAction(action
);
5554 cmd
->GetActions().Clear();
5557 m_batchedCommand
->AddAction(action
);
5561 wxRichTextCommand
* cmd
= new wxRichTextCommand(action
->GetName());
5562 cmd
->AddAction(action
);
5564 // Only store it if we're not suppressing undo.
5565 return GetCommandProcessor()->Submit(cmd
, !SuppressingUndo());
5571 /// Begin suppressing undo/redo commands.
5572 bool wxRichTextBuffer::BeginSuppressUndo()
5579 /// End suppressing undo/redo commands.
5580 bool wxRichTextBuffer::EndSuppressUndo()
5587 /// Begin using a style
5588 bool wxRichTextBuffer::BeginStyle(const wxTextAttr
& style
)
5590 wxTextAttr
newStyle(GetDefaultStyle());
5592 // Save the old default style
5593 m_attributeStack
.Append((wxObject
*) new wxTextAttr(GetDefaultStyle()));
5595 wxRichTextApplyStyle(newStyle
, style
);
5596 newStyle
.SetFlags(style
.GetFlags()|newStyle
.GetFlags());
5598 SetDefaultStyle(newStyle
);
5604 bool wxRichTextBuffer::EndStyle()
5606 if (!m_attributeStack
.GetFirst())
5608 wxLogDebug(_("Too many EndStyle calls!"));
5612 wxList::compatibility_iterator node
= m_attributeStack
.GetLast();
5613 wxTextAttr
* attr
= (wxTextAttr
*)node
->GetData();
5614 m_attributeStack
.Erase(node
);
5616 SetDefaultStyle(*attr
);
5623 bool wxRichTextBuffer::EndAllStyles()
5625 while (m_attributeStack
.GetCount() != 0)
5630 /// Clear the style stack
5631 void wxRichTextBuffer::ClearStyleStack()
5633 for (wxList::compatibility_iterator node
= m_attributeStack
.GetFirst(); node
; node
= node
->GetNext())
5634 delete (wxTextAttr
*) node
->GetData();
5635 m_attributeStack
.Clear();
5638 /// Begin using bold
5639 bool wxRichTextBuffer::BeginBold()
5642 attr
.SetFontWeight(wxBOLD
);
5644 return BeginStyle(attr
);
5647 /// Begin using italic
5648 bool wxRichTextBuffer::BeginItalic()
5651 attr
.SetFontStyle(wxITALIC
);
5653 return BeginStyle(attr
);
5656 /// Begin using underline
5657 bool wxRichTextBuffer::BeginUnderline()
5660 attr
.SetFontUnderlined(true);
5662 return BeginStyle(attr
);
5665 /// Begin using point size
5666 bool wxRichTextBuffer::BeginFontSize(int pointSize
)
5669 attr
.SetFontSize(pointSize
);
5671 return BeginStyle(attr
);
5674 /// Begin using this font
5675 bool wxRichTextBuffer::BeginFont(const wxFont
& font
)
5680 return BeginStyle(attr
);
5683 /// Begin using this colour
5684 bool wxRichTextBuffer::BeginTextColour(const wxColour
& colour
)
5687 attr
.SetFlags(wxTEXT_ATTR_TEXT_COLOUR
);
5688 attr
.SetTextColour(colour
);
5690 return BeginStyle(attr
);
5693 /// Begin using alignment
5694 bool wxRichTextBuffer::BeginAlignment(wxTextAttrAlignment alignment
)
5697 attr
.SetFlags(wxTEXT_ATTR_ALIGNMENT
);
5698 attr
.SetAlignment(alignment
);
5700 return BeginStyle(attr
);
5703 /// Begin left indent
5704 bool wxRichTextBuffer::BeginLeftIndent(int leftIndent
, int leftSubIndent
)
5707 attr
.SetFlags(wxTEXT_ATTR_LEFT_INDENT
);
5708 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5710 return BeginStyle(attr
);
5713 /// Begin right indent
5714 bool wxRichTextBuffer::BeginRightIndent(int rightIndent
)
5717 attr
.SetFlags(wxTEXT_ATTR_RIGHT_INDENT
);
5718 attr
.SetRightIndent(rightIndent
);
5720 return BeginStyle(attr
);
5723 /// Begin paragraph spacing
5724 bool wxRichTextBuffer::BeginParagraphSpacing(int before
, int after
)
5728 flags
|= wxTEXT_ATTR_PARA_SPACING_BEFORE
;
5730 flags
|= wxTEXT_ATTR_PARA_SPACING_AFTER
;
5733 attr
.SetFlags(flags
);
5734 attr
.SetParagraphSpacingBefore(before
);
5735 attr
.SetParagraphSpacingAfter(after
);
5737 return BeginStyle(attr
);
5740 /// Begin line spacing
5741 bool wxRichTextBuffer::BeginLineSpacing(int lineSpacing
)
5744 attr
.SetFlags(wxTEXT_ATTR_LINE_SPACING
);
5745 attr
.SetLineSpacing(lineSpacing
);
5747 return BeginStyle(attr
);
5750 /// Begin numbered bullet
5751 bool wxRichTextBuffer::BeginNumberedBullet(int bulletNumber
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5754 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5755 attr
.SetBulletStyle(bulletStyle
);
5756 attr
.SetBulletNumber(bulletNumber
);
5757 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5759 return BeginStyle(attr
);
5762 /// Begin symbol bullet
5763 bool wxRichTextBuffer::BeginSymbolBullet(const wxString
& symbol
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5766 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5767 attr
.SetBulletStyle(bulletStyle
);
5768 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5769 attr
.SetBulletText(symbol
);
5771 return BeginStyle(attr
);
5774 /// Begin standard bullet
5775 bool wxRichTextBuffer::BeginStandardBullet(const wxString
& bulletName
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5778 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5779 attr
.SetBulletStyle(bulletStyle
);
5780 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5781 attr
.SetBulletName(bulletName
);
5783 return BeginStyle(attr
);
5786 /// Begin named character style
5787 bool wxRichTextBuffer::BeginCharacterStyle(const wxString
& characterStyle
)
5789 if (GetStyleSheet())
5791 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterStyle
);
5794 wxTextAttr attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5795 return BeginStyle(attr
);
5801 /// Begin named paragraph style
5802 bool wxRichTextBuffer::BeginParagraphStyle(const wxString
& paragraphStyle
)
5804 if (GetStyleSheet())
5806 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(paragraphStyle
);
5809 wxTextAttr attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5810 return BeginStyle(attr
);
5816 /// Begin named list style
5817 bool wxRichTextBuffer::BeginListStyle(const wxString
& listStyle
, int level
, int number
)
5819 if (GetStyleSheet())
5821 wxRichTextListStyleDefinition
* def
= GetStyleSheet()->FindListStyle(listStyle
);
5824 wxTextAttr
attr(def
->GetCombinedStyleForLevel(level
));
5826 attr
.SetBulletNumber(number
);
5828 return BeginStyle(attr
);
5835 bool wxRichTextBuffer::BeginURL(const wxString
& url
, const wxString
& characterStyle
)
5839 if (!characterStyle
.IsEmpty() && GetStyleSheet())
5841 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterStyle
);
5844 attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5849 return BeginStyle(attr
);
5852 /// Adds a handler to the end
5853 void wxRichTextBuffer::AddHandler(wxRichTextFileHandler
*handler
)
5855 sm_handlers
.Append(handler
);
5858 /// Inserts a handler at the front
5859 void wxRichTextBuffer::InsertHandler(wxRichTextFileHandler
*handler
)
5861 sm_handlers
.Insert( handler
);
5864 /// Removes a handler
5865 bool wxRichTextBuffer::RemoveHandler(const wxString
& name
)
5867 wxRichTextFileHandler
*handler
= FindHandler(name
);
5870 sm_handlers
.DeleteObject(handler
);
5878 /// Finds a handler by filename or, if supplied, type
5879 wxRichTextFileHandler
*wxRichTextBuffer::FindHandlerFilenameOrType(const wxString
& filename
,
5880 wxRichTextFileType imageType
)
5882 if (imageType
!= wxRICHTEXT_TYPE_ANY
)
5883 return FindHandler(imageType
);
5884 else if (!filename
.IsEmpty())
5886 wxString path
, file
, ext
;
5887 wxSplitPath(filename
, & path
, & file
, & ext
);
5888 return FindHandler(ext
, imageType
);
5895 /// Finds a handler by name
5896 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(const wxString
& name
)
5898 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5901 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5902 if (handler
->GetName().Lower() == name
.Lower()) return handler
;
5904 node
= node
->GetNext();
5909 /// Finds a handler by extension and type
5910 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(const wxString
& extension
, wxRichTextFileType type
)
5912 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5915 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5916 if ( handler
->GetExtension().Lower() == extension
.Lower() &&
5917 (type
== wxRICHTEXT_TYPE_ANY
|| handler
->GetType() == type
) )
5919 node
= node
->GetNext();
5924 /// Finds a handler by type
5925 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(wxRichTextFileType type
)
5927 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5930 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5931 if (handler
->GetType() == type
) return handler
;
5932 node
= node
->GetNext();
5937 void wxRichTextBuffer::InitStandardHandlers()
5939 if (!FindHandler(wxRICHTEXT_TYPE_TEXT
))
5940 AddHandler(new wxRichTextPlainTextHandler
);
5943 void wxRichTextBuffer::CleanUpHandlers()
5945 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5948 wxRichTextFileHandler
* handler
= (wxRichTextFileHandler
*)node
->GetData();
5949 wxList::compatibility_iterator next
= node
->GetNext();
5954 sm_handlers
.Clear();
5957 wxString
wxRichTextBuffer::GetExtWildcard(bool combine
, bool save
, wxArrayInt
* types
)
5964 wxList::compatibility_iterator node
= GetHandlers().GetFirst();
5968 wxRichTextFileHandler
* handler
= (wxRichTextFileHandler
*) node
->GetData();
5969 if (handler
->IsVisible() && ((save
&& handler
->CanSave()) || (!save
&& handler
->CanLoad())))
5974 wildcard
+= wxT(";");
5975 wildcard
+= wxT("*.") + handler
->GetExtension();
5980 wildcard
+= wxT("|");
5981 wildcard
+= handler
->GetName();
5982 wildcard
+= wxT(" ");
5983 wildcard
+= _("files");
5984 wildcard
+= wxT(" (*.");
5985 wildcard
+= handler
->GetExtension();
5986 wildcard
+= wxT(")|*.");
5987 wildcard
+= handler
->GetExtension();
5989 types
->Add(handler
->GetType());
5994 node
= node
->GetNext();
5998 wildcard
= wxT("(") + wildcard
+ wxT(")|") + wildcard
;
6003 bool wxRichTextBuffer::LoadFile(const wxString
& filename
, wxRichTextFileType type
)
6005 wxRichTextFileHandler
* handler
= FindHandlerFilenameOrType(filename
, type
);
6008 SetDefaultStyle(wxTextAttr());
6009 handler
->SetFlags(GetHandlerFlags());
6010 bool success
= handler
->LoadFile(this, filename
);
6011 Invalidate(wxRICHTEXT_ALL
);
6019 bool wxRichTextBuffer::SaveFile(const wxString
& filename
, wxRichTextFileType type
)
6021 wxRichTextFileHandler
* handler
= FindHandlerFilenameOrType(filename
, type
);
6024 handler
->SetFlags(GetHandlerFlags());
6025 return handler
->SaveFile(this, filename
);
6031 /// Load from a stream
6032 bool wxRichTextBuffer::LoadFile(wxInputStream
& stream
, wxRichTextFileType type
)
6034 wxRichTextFileHandler
* handler
= FindHandler(type
);
6037 SetDefaultStyle(wxTextAttr());
6038 handler
->SetFlags(GetHandlerFlags());
6039 bool success
= handler
->LoadFile(this, stream
);
6040 Invalidate(wxRICHTEXT_ALL
);
6047 /// Save to a stream
6048 bool wxRichTextBuffer::SaveFile(wxOutputStream
& stream
, wxRichTextFileType type
)
6050 wxRichTextFileHandler
* handler
= FindHandler(type
);
6053 handler
->SetFlags(GetHandlerFlags());
6054 return handler
->SaveFile(this, stream
);
6060 /// Copy the range to the clipboard
6061 bool wxRichTextBuffer::CopyToClipboard(const wxRichTextRange
& range
)
6063 bool success
= false;
6064 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
6066 if (!wxTheClipboard
->IsOpened() && wxTheClipboard
->Open())
6068 wxTheClipboard
->Clear();
6070 // Add composite object
6072 wxDataObjectComposite
* compositeObject
= new wxDataObjectComposite();
6075 wxString text
= GetTextForRange(range
);
6078 text
= wxTextFile::Translate(text
, wxTextFileType_Dos
);
6081 compositeObject
->Add(new wxTextDataObject(text
), false /* not preferred */);
6084 // Add rich text buffer data object. This needs the XML handler to be present.
6086 if (FindHandler(wxRICHTEXT_TYPE_XML
))
6088 wxRichTextBuffer
* richTextBuf
= new wxRichTextBuffer
;
6089 CopyFragment(range
, *richTextBuf
);
6091 compositeObject
->Add(new wxRichTextBufferDataObject(richTextBuf
), true /* preferred */);
6094 if (wxTheClipboard
->SetData(compositeObject
))
6097 wxTheClipboard
->Close();
6106 /// Paste the clipboard content to the buffer
6107 bool wxRichTextBuffer::PasteFromClipboard(long position
)
6109 bool success
= false;
6110 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
6111 if (CanPasteFromClipboard())
6113 if (wxTheClipboard
->Open())
6115 if (wxTheClipboard
->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())))
6117 wxRichTextBufferDataObject data
;
6118 wxTheClipboard
->GetData(data
);
6119 wxRichTextBuffer
* richTextBuffer
= data
.GetRichTextBuffer();
6122 InsertParagraphsWithUndo(position
+1, *richTextBuffer
, GetRichTextCtrl(), 0);
6123 if (GetRichTextCtrl())
6124 GetRichTextCtrl()->ShowPosition(position
+ richTextBuffer
->GetRange().GetEnd());
6125 delete richTextBuffer
;
6128 else if (wxTheClipboard
->IsSupported(wxDF_TEXT
) || wxTheClipboard
->IsSupported(wxDF_UNICODETEXT
))
6130 wxTextDataObject data
;
6131 wxTheClipboard
->GetData(data
);
6132 wxString
text(data
.GetText());
6135 text2
.Alloc(text
.Length()+1);
6137 for (i
= 0; i
< text
.Length(); i
++)
6139 wxChar ch
= text
[i
];
6140 if (ch
!= wxT('\r'))
6144 wxString text2
= text
;
6146 InsertTextWithUndo(position
+1, text2
, GetRichTextCtrl(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
);
6148 if (GetRichTextCtrl())
6149 GetRichTextCtrl()->ShowPosition(position
+ text2
.Length());
6153 else if (wxTheClipboard
->IsSupported(wxDF_BITMAP
))
6155 wxBitmapDataObject data
;
6156 wxTheClipboard
->GetData(data
);
6157 wxBitmap
bitmap(data
.GetBitmap());
6158 wxImage
image(bitmap
.ConvertToImage());
6160 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Image"), wxRICHTEXT_INSERT
, this, GetRichTextCtrl(), false);
6162 action
->GetNewParagraphs().AddImage(image
);
6164 if (action
->GetNewParagraphs().GetChildCount() == 1)
6165 action
->GetNewParagraphs().SetPartialParagraph(true);
6167 action
->SetPosition(position
+1);
6169 // Set the range we'll need to delete in Undo
6170 action
->SetRange(wxRichTextRange(position
+1, position
+1));
6172 SubmitAction(action
);
6176 wxTheClipboard
->Close();
6180 wxUnusedVar(position
);
6185 /// Can we paste from the clipboard?
6186 bool wxRichTextBuffer::CanPasteFromClipboard() const
6188 bool canPaste
= false;
6189 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
6190 if (!wxTheClipboard
->IsOpened() && wxTheClipboard
->Open())
6192 if (wxTheClipboard
->IsSupported(wxDF_TEXT
) || wxTheClipboard
->IsSupported(wxDF_UNICODETEXT
) ||
6193 wxTheClipboard
->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())) ||
6194 wxTheClipboard
->IsSupported(wxDF_BITMAP
))
6198 wxTheClipboard
->Close();
6204 /// Dumps contents of buffer for debugging purposes
6205 void wxRichTextBuffer::Dump()
6209 wxStringOutputStream
stream(& text
);
6210 wxTextOutputStream
textStream(stream
);
6217 /// Add an event handler
6218 bool wxRichTextBuffer::AddEventHandler(wxEvtHandler
* handler
)
6220 m_eventHandlers
.Append(handler
);
6224 /// Remove an event handler
6225 bool wxRichTextBuffer::RemoveEventHandler(wxEvtHandler
* handler
, bool deleteHandler
)
6227 wxList::compatibility_iterator node
= m_eventHandlers
.Find(handler
);
6230 m_eventHandlers
.Erase(node
);
6240 /// Clear event handlers
6241 void wxRichTextBuffer::ClearEventHandlers()
6243 m_eventHandlers
.Clear();
6246 /// Send event to event handlers. If sendToAll is true, will send to all event handlers,
6247 /// otherwise will stop at the first successful one.
6248 bool wxRichTextBuffer::SendEvent(wxEvent
& event
, bool sendToAll
)
6250 bool success
= false;
6251 for (wxList::compatibility_iterator node
= m_eventHandlers
.GetFirst(); node
; node
= node
->GetNext())
6253 wxEvtHandler
* handler
= (wxEvtHandler
*) node
->GetData();
6254 if (handler
->ProcessEvent(event
))
6264 /// Set style sheet and notify of the change
6265 bool wxRichTextBuffer::SetStyleSheetAndNotify(wxRichTextStyleSheet
* sheet
)
6267 wxRichTextStyleSheet
* oldSheet
= GetStyleSheet();
6269 wxWindowID id
= wxID_ANY
;
6270 if (GetRichTextCtrl())
6271 id
= GetRichTextCtrl()->GetId();
6273 wxRichTextEvent
event(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING
, id
);
6274 event
.SetEventObject(GetRichTextCtrl());
6275 event
.SetOldStyleSheet(oldSheet
);
6276 event
.SetNewStyleSheet(sheet
);
6279 if (SendEvent(event
) && !event
.IsAllowed())
6281 if (sheet
!= oldSheet
)
6287 if (oldSheet
&& oldSheet
!= sheet
)
6290 SetStyleSheet(sheet
);
6292 event
.SetEventType(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED
);
6293 event
.SetOldStyleSheet(NULL
);
6296 return SendEvent(event
);
6299 /// Set renderer, deleting old one
6300 void wxRichTextBuffer::SetRenderer(wxRichTextRenderer
* renderer
)
6304 sm_renderer
= renderer
;
6307 bool wxRichTextStdRenderer::DrawStandardBullet(wxRichTextParagraph
* paragraph
, wxDC
& dc
, const wxTextAttr
& bulletAttr
, const wxRect
& rect
)
6309 if (bulletAttr
.GetTextColour().Ok())
6311 wxCheckSetPen(dc
, wxPen(bulletAttr
.GetTextColour()));
6312 wxCheckSetBrush(dc
, wxBrush(bulletAttr
.GetTextColour()));
6316 wxCheckSetPen(dc
, *wxBLACK_PEN
);
6317 wxCheckSetBrush(dc
, *wxBLACK_BRUSH
);
6321 if (bulletAttr
.HasFont())
6323 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(bulletAttr
);
6326 font
= (*wxNORMAL_FONT
);
6328 wxCheckSetFont(dc
, font
);
6330 int charHeight
= dc
.GetCharHeight();
6332 int bulletWidth
= (int) (((float) charHeight
) * wxRichTextBuffer::GetBulletProportion());
6333 int bulletHeight
= bulletWidth
;
6337 // Calculate the top position of the character (as opposed to the whole line height)
6338 int y
= rect
.y
+ (rect
.height
- charHeight
);
6340 // Calculate where the bullet should be positioned
6341 y
= y
+ (charHeight
+1)/2 - (bulletHeight
+1)/2;
6343 // The margin between a bullet and text.
6344 int margin
= paragraph
->ConvertTenthsMMToPixels(dc
, wxRichTextBuffer::GetBulletRightMargin());
6346 if (bulletAttr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT
)
6347 x
= rect
.x
+ rect
.width
- bulletWidth
- margin
;
6348 else if (bulletAttr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE
)
6349 x
= x
+ (rect
.width
)/2 - bulletWidth
/2;
6351 if (bulletAttr
.GetBulletName() == wxT("standard/square"))
6353 dc
.DrawRectangle(x
, y
, bulletWidth
, bulletHeight
);
6355 else if (bulletAttr
.GetBulletName() == wxT("standard/diamond"))
6358 pts
[0].x
= x
; pts
[0].y
= y
+ bulletHeight
/2;
6359 pts
[1].x
= x
+ bulletWidth
/2; pts
[1].y
= y
;
6360 pts
[2].x
= x
+ bulletWidth
; pts
[2].y
= y
+ bulletHeight
/2;
6361 pts
[3].x
= x
+ bulletWidth
/2; pts
[3].y
= y
+ bulletHeight
;
6363 dc
.DrawPolygon(4, pts
);
6365 else if (bulletAttr
.GetBulletName() == wxT("standard/triangle"))
6368 pts
[0].x
= x
; pts
[0].y
= y
;
6369 pts
[1].x
= x
+ bulletWidth
; pts
[1].y
= y
+ bulletHeight
/2;
6370 pts
[2].x
= x
; pts
[2].y
= y
+ bulletHeight
;
6372 dc
.DrawPolygon(3, pts
);
6374 else // "standard/circle", and catch-all
6376 dc
.DrawEllipse(x
, y
, bulletWidth
, bulletHeight
);
6382 bool wxRichTextStdRenderer::DrawTextBullet(wxRichTextParagraph
* paragraph
, wxDC
& dc
, const wxTextAttr
& attr
, const wxRect
& rect
, const wxString
& text
)
6387 if ((attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL
) && !attr
.GetBulletFont().IsEmpty() && attr
.HasFont())
6389 wxTextAttr fontAttr
;
6390 fontAttr
.SetFontSize(attr
.GetFontSize());
6391 fontAttr
.SetFontStyle(attr
.GetFontStyle());
6392 fontAttr
.SetFontWeight(attr
.GetFontWeight());
6393 fontAttr
.SetFontUnderlined(attr
.GetFontUnderlined());
6394 fontAttr
.SetFontFaceName(attr
.GetBulletFont());
6395 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(fontAttr
);
6397 else if (attr
.HasFont())
6398 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(attr
);
6400 font
= (*wxNORMAL_FONT
);
6402 wxCheckSetFont(dc
, font
);
6404 if (attr
.GetTextColour().Ok())
6405 dc
.SetTextForeground(attr
.GetTextColour());
6407 dc
.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT
);
6409 int charHeight
= dc
.GetCharHeight();
6411 dc
.GetTextExtent(text
, & tw
, & th
);
6415 // Calculate the top position of the character (as opposed to the whole line height)
6416 int y
= rect
.y
+ (rect
.height
- charHeight
);
6418 // The margin between a bullet and text.
6419 int margin
= paragraph
->ConvertTenthsMMToPixels(dc
, wxRichTextBuffer::GetBulletRightMargin());
6421 if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT
)
6422 x
= (rect
.x
+ rect
.width
) - tw
- margin
;
6423 else if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE
)
6424 x
= x
+ (rect
.width
)/2 - tw
/2;
6426 dc
.DrawText(text
, x
, y
);
6434 bool wxRichTextStdRenderer::DrawBitmapBullet(wxRichTextParagraph
* WXUNUSED(paragraph
), wxDC
& WXUNUSED(dc
), const wxTextAttr
& WXUNUSED(attr
), const wxRect
& WXUNUSED(rect
))
6436 // Currently unimplemented. The intention is to store bitmaps by name in a media store associated
6437 // with the buffer. The store will allow retrieval from memory, disk or other means.
6441 /// Enumerate the standard bullet names currently supported
6442 bool wxRichTextStdRenderer::EnumerateStandardBulletNames(wxArrayString
& bulletNames
)
6444 bulletNames
.Add(wxT("standard/circle"));
6445 bulletNames
.Add(wxT("standard/square"));
6446 bulletNames
.Add(wxT("standard/diamond"));
6447 bulletNames
.Add(wxT("standard/triangle"));
6453 * Module to initialise and clean up handlers
6456 class wxRichTextModule
: public wxModule
6458 DECLARE_DYNAMIC_CLASS(wxRichTextModule
)
6460 wxRichTextModule() {}
6463 wxRichTextBuffer::SetRenderer(new wxRichTextStdRenderer
);
6464 wxRichTextBuffer::InitStandardHandlers();
6465 wxRichTextParagraph::InitDefaultTabs();
6470 wxRichTextBuffer::CleanUpHandlers();
6471 wxRichTextDecimalToRoman(-1);
6472 wxRichTextParagraph::ClearDefaultTabs();
6473 wxRichTextCtrl::ClearAvailableFontNames();
6474 wxRichTextBuffer::SetRenderer(NULL
);
6478 IMPLEMENT_DYNAMIC_CLASS(wxRichTextModule
, wxModule
)
6481 // If the richtext lib is dynamically loaded after the app has already started
6482 // (such as from wxPython) then the built-in module system will not init this
6483 // module. Provide this function to do it manually.
6484 void wxRichTextModuleInit()
6486 wxModule
* module = new wxRichTextModule
;
6488 wxModule::RegisterModule(module);
6493 * Commands for undo/redo
6497 wxRichTextCommand::wxRichTextCommand(const wxString
& name
, wxRichTextCommandId id
, wxRichTextBuffer
* buffer
,
6498 wxRichTextCtrl
* ctrl
, bool ignoreFirstTime
): wxCommand(true, name
)
6500 /* wxRichTextAction* action = */ new wxRichTextAction(this, name
, id
, buffer
, ctrl
, ignoreFirstTime
);
6503 wxRichTextCommand::wxRichTextCommand(const wxString
& name
): wxCommand(true, name
)
6507 wxRichTextCommand::~wxRichTextCommand()
6512 void wxRichTextCommand::AddAction(wxRichTextAction
* action
)
6514 if (!m_actions
.Member(action
))
6515 m_actions
.Append(action
);
6518 bool wxRichTextCommand::Do()
6520 for (wxList::compatibility_iterator node
= m_actions
.GetFirst(); node
; node
= node
->GetNext())
6522 wxRichTextAction
* action
= (wxRichTextAction
*) node
->GetData();
6529 bool wxRichTextCommand::Undo()
6531 for (wxList::compatibility_iterator node
= m_actions
.GetLast(); node
; node
= node
->GetPrevious())
6533 wxRichTextAction
* action
= (wxRichTextAction
*) node
->GetData();
6540 void wxRichTextCommand::ClearActions()
6542 WX_CLEAR_LIST(wxList
, m_actions
);
6550 wxRichTextAction::wxRichTextAction(wxRichTextCommand
* cmd
, const wxString
& name
, wxRichTextCommandId id
, wxRichTextBuffer
* buffer
,
6551 wxRichTextCtrl
* ctrl
, bool ignoreFirstTime
)
6554 m_ignoreThis
= ignoreFirstTime
;
6559 m_newParagraphs
.SetDefaultStyle(buffer
->GetDefaultStyle());
6560 m_newParagraphs
.SetBasicStyle(buffer
->GetBasicStyle());
6562 cmd
->AddAction(this);
6565 wxRichTextAction::~wxRichTextAction()
6569 void wxRichTextAction::CalculateRefreshOptimizations(wxArrayInt
& optimizationLineCharPositions
, wxArrayInt
& optimizationLineYPositions
)
6571 // Store a list of line start character and y positions so we can figure out which area
6572 // we need to refresh
6574 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6575 // NOTE: we're assuming that the buffer is laid out correctly at this point.
6576 // If we had several actions, which only invalidate and leave layout until the
6577 // paint handler is called, then this might not be true. So we may need to switch
6578 // optimisation on only when we're simply adding text and not simultaneously
6579 // deleting a selection, for example. Or, we make sure the buffer is laid out correctly
6580 // first, but of course this means we'll be doing it twice.
6581 if (!m_buffer
->GetDirty() && m_ctrl
) // can only do optimisation if the buffer is already laid out correctly
6583 wxSize clientSize
= m_ctrl
->GetClientSize();
6584 wxPoint firstVisiblePt
= m_ctrl
->GetFirstVisiblePoint();
6585 int lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6587 wxRichTextParagraph
* para
= m_buffer
->GetParagraphAtPosition(GetRange().GetStart());
6588 wxRichTextObjectList::compatibility_iterator node
= m_buffer
->GetChildren().Find(para
);
6591 wxRichTextParagraph
* child
= (wxRichTextParagraph
*) node
->GetData();
6592 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
6595 wxRichTextLine
* line
= node2
->GetData();
6596 wxPoint pt
= line
->GetAbsolutePosition();
6597 wxRichTextRange range
= line
->GetAbsoluteRange();
6601 node2
= wxRichTextLineList::compatibility_iterator();
6602 node
= wxRichTextObjectList::compatibility_iterator();
6604 else if (range
.GetStart() > GetPosition() && pt
.y
>= firstVisiblePt
.y
)
6606 optimizationLineCharPositions
.Add(range
.GetStart());
6607 optimizationLineYPositions
.Add(pt
.y
);
6611 node2
= node2
->GetNext();
6615 node
= node
->GetNext();
6621 bool wxRichTextAction::Do()
6623 m_buffer
->Modify(true);
6627 case wxRICHTEXT_INSERT
:
6629 // Store a list of line start character and y positions so we can figure out which area
6630 // we need to refresh
6631 wxArrayInt optimizationLineCharPositions
;
6632 wxArrayInt optimizationLineYPositions
;
6634 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6635 CalculateRefreshOptimizations(optimizationLineCharPositions
, optimizationLineYPositions
);
6638 m_buffer
->InsertFragment(GetRange().GetStart(), m_newParagraphs
);
6639 m_buffer
->UpdateRanges();
6640 m_buffer
->Invalidate(wxRichTextRange(wxMax(0, GetRange().GetStart()-1), GetRange().GetEnd()));
6642 long newCaretPosition
= GetPosition() + m_newParagraphs
.GetRange().GetLength();
6644 // Character position to caret position
6645 newCaretPosition
--;
6647 // Don't take into account the last newline
6648 if (m_newParagraphs
.GetPartialParagraph())
6649 newCaretPosition
--;
6651 if (m_newParagraphs
.GetChildren().GetCount() > 1)
6653 wxRichTextObject
* p
= (wxRichTextObject
*) m_newParagraphs
.GetChildren().GetLast()->GetData();
6654 if (p
->GetRange().GetLength() == 1)
6655 newCaretPosition
--;
6658 newCaretPosition
= wxMin(newCaretPosition
, (m_buffer
->GetRange().GetEnd()-1));
6660 UpdateAppearance(newCaretPosition
, true /* send update event */, & optimizationLineCharPositions
, & optimizationLineYPositions
, true /* do */);
6662 wxRichTextEvent
cmdEvent(
6663 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED
,
6664 m_ctrl
? m_ctrl
->GetId() : -1);
6665 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6666 cmdEvent
.SetRange(GetRange());
6667 cmdEvent
.SetPosition(GetRange().GetStart());
6669 m_buffer
->SendEvent(cmdEvent
);
6673 case wxRICHTEXT_DELETE
:
6675 wxArrayInt optimizationLineCharPositions
;
6676 wxArrayInt optimizationLineYPositions
;
6678 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6679 CalculateRefreshOptimizations(optimizationLineCharPositions
, optimizationLineYPositions
);
6682 m_buffer
->DeleteRange(GetRange());
6683 m_buffer
->UpdateRanges();
6684 m_buffer
->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6686 long caretPos
= GetRange().GetStart()-1;
6687 if (caretPos
>= m_buffer
->GetRange().GetEnd())
6690 UpdateAppearance(caretPos
, true /* send update event */, & optimizationLineCharPositions
, & optimizationLineYPositions
, true /* do */);
6692 wxRichTextEvent
cmdEvent(
6693 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED
,
6694 m_ctrl
? m_ctrl
->GetId() : -1);
6695 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6696 cmdEvent
.SetRange(GetRange());
6697 cmdEvent
.SetPosition(GetRange().GetStart());
6699 m_buffer
->SendEvent(cmdEvent
);
6703 case wxRICHTEXT_CHANGE_STYLE
:
6705 ApplyParagraphs(GetNewParagraphs());
6706 m_buffer
->Invalidate(GetRange());
6708 UpdateAppearance(GetPosition());
6710 wxRichTextEvent
cmdEvent(
6711 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED
,
6712 m_ctrl
? m_ctrl
->GetId() : -1);
6713 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6714 cmdEvent
.SetRange(GetRange());
6715 cmdEvent
.SetPosition(GetRange().GetStart());
6717 m_buffer
->SendEvent(cmdEvent
);
6728 bool wxRichTextAction::Undo()
6730 m_buffer
->Modify(true);
6734 case wxRICHTEXT_INSERT
:
6736 wxArrayInt optimizationLineCharPositions
;
6737 wxArrayInt optimizationLineYPositions
;
6739 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6740 CalculateRefreshOptimizations(optimizationLineCharPositions
, optimizationLineYPositions
);
6743 m_buffer
->DeleteRange(GetRange());
6744 m_buffer
->UpdateRanges();
6745 m_buffer
->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6747 long newCaretPosition
= GetPosition() - 1;
6749 UpdateAppearance(newCaretPosition
, true, /* send update event */ & optimizationLineCharPositions
, & optimizationLineYPositions
, false /* undo */);
6751 wxRichTextEvent
cmdEvent(
6752 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED
,
6753 m_ctrl
? m_ctrl
->GetId() : -1);
6754 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6755 cmdEvent
.SetRange(GetRange());
6756 cmdEvent
.SetPosition(GetRange().GetStart());
6758 m_buffer
->SendEvent(cmdEvent
);
6762 case wxRICHTEXT_DELETE
:
6764 wxArrayInt optimizationLineCharPositions
;
6765 wxArrayInt optimizationLineYPositions
;
6767 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6768 CalculateRefreshOptimizations(optimizationLineCharPositions
, optimizationLineYPositions
);
6771 m_buffer
->InsertFragment(GetRange().GetStart(), m_oldParagraphs
);
6772 m_buffer
->UpdateRanges();
6773 m_buffer
->Invalidate(GetRange());
6775 UpdateAppearance(GetPosition(), true, /* send update event */ & optimizationLineCharPositions
, & optimizationLineYPositions
, false /* undo */);
6777 wxRichTextEvent
cmdEvent(
6778 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED
,
6779 m_ctrl
? m_ctrl
->GetId() : -1);
6780 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6781 cmdEvent
.SetRange(GetRange());
6782 cmdEvent
.SetPosition(GetRange().GetStart());
6784 m_buffer
->SendEvent(cmdEvent
);
6788 case wxRICHTEXT_CHANGE_STYLE
:
6790 ApplyParagraphs(GetOldParagraphs());
6791 m_buffer
->Invalidate(GetRange());
6793 UpdateAppearance(GetPosition());
6795 wxRichTextEvent
cmdEvent(
6796 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED
,
6797 m_ctrl
? m_ctrl
->GetId() : -1);
6798 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6799 cmdEvent
.SetRange(GetRange());
6800 cmdEvent
.SetPosition(GetRange().GetStart());
6802 m_buffer
->SendEvent(cmdEvent
);
6813 /// Update the control appearance
6814 void wxRichTextAction::UpdateAppearance(long caretPosition
, bool sendUpdateEvent
, wxArrayInt
* optimizationLineCharPositions
, wxArrayInt
* optimizationLineYPositions
, bool isDoCmd
)
6818 m_ctrl
->SetCaretPosition(caretPosition
);
6819 if (!m_ctrl
->IsFrozen())
6821 m_ctrl
->LayoutContent();
6823 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6824 // Find refresh rectangle if we are in a position to optimise refresh
6825 if ((m_cmdId
== wxRICHTEXT_INSERT
|| m_cmdId
== wxRICHTEXT_DELETE
) && optimizationLineCharPositions
)
6829 wxSize clientSize
= m_ctrl
->GetClientSize();
6830 wxPoint firstVisiblePt
= m_ctrl
->GetFirstVisiblePoint();
6832 // Start/end positions
6834 int lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6836 bool foundEnd
= false;
6838 // position offset - how many characters were inserted
6839 int positionOffset
= GetRange().GetLength();
6841 // Determine whether this is Do or Undo, and adjust positionOffset accordingly
6842 if ((m_cmdId
== wxRICHTEXT_DELETE
&& isDoCmd
) || (m_cmdId
== wxRICHTEXT_INSERT
&& !isDoCmd
))
6843 positionOffset
= - positionOffset
;
6845 // find the first line which is being drawn at the same position as it was
6846 // before. Since we're talking about a simple insertion, we can assume
6847 // that the rest of the window does not need to be redrawn.
6849 wxRichTextParagraph
* para
= m_buffer
->GetParagraphAtPosition(GetPosition());
6852 // Find line containing GetPosition().
6853 wxRichTextLine
* line
= NULL
;
6854 wxRichTextLineList::compatibility_iterator node2
= para
->GetLines().GetFirst();
6857 wxRichTextLine
* l
= node2
->GetData();
6858 wxRichTextRange range
= l
->GetAbsoluteRange();
6859 if (range
.Contains(GetRange().GetStart()-1))
6864 node2
= node2
->GetNext();
6869 // Step back a couple of lines to where we can be sure of reformatting correctly
6870 wxRichTextLineList::compatibility_iterator lineNode
= para
->GetLines().Find(line
);
6873 lineNode
= lineNode
->GetPrevious();
6876 line
= (wxRichTextLine
*) lineNode
->GetData();
6877 lineNode
= lineNode
->GetPrevious();
6879 line
= (wxRichTextLine
*) lineNode
->GetData();
6883 firstY
= line
->GetAbsolutePosition().y
;
6887 wxRichTextObjectList::compatibility_iterator node
= m_buffer
->GetChildren().Find(para
);
6890 wxRichTextParagraph
* child
= (wxRichTextParagraph
*) node
->GetData();
6891 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
6894 wxRichTextLine
* line
= node2
->GetData();
6895 wxPoint pt
= line
->GetAbsolutePosition();
6896 wxRichTextRange range
= line
->GetAbsoluteRange();
6898 // we want to find the first line that is in the same position
6899 // as before. This will mean we're at the end of the changed text.
6901 if (pt
.y
> lastY
) // going past the end of the window, no more info
6903 node2
= wxRichTextLineList::compatibility_iterator();
6904 node
= wxRichTextObjectList::compatibility_iterator();
6906 // Detect last line in the buffer
6907 else if (!node2
->GetNext() && para
->GetRange().Contains(m_buffer
->GetRange().GetEnd()))
6910 lastY
= pt
.y
+ line
->GetSize().y
;
6912 node2
= wxRichTextLineList::compatibility_iterator();
6913 node
= wxRichTextObjectList::compatibility_iterator();
6919 // search for this line being at the same position as before
6920 for (i
= 0; i
< optimizationLineCharPositions
->GetCount(); i
++)
6922 if (((*optimizationLineCharPositions
)[i
] + positionOffset
== range
.GetStart()) &&
6923 ((*optimizationLineYPositions
)[i
] == pt
.y
))
6925 // Stop, we're now the same as we were
6930 node2
= wxRichTextLineList::compatibility_iterator();
6931 node
= wxRichTextObjectList::compatibility_iterator();
6939 node2
= node2
->GetNext();
6943 node
= node
->GetNext();
6946 firstY
= wxMax(firstVisiblePt
.y
, firstY
);
6948 lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6950 // Convert to device coordinates
6951 wxRect
rect(m_ctrl
->GetPhysicalPoint(wxPoint(firstVisiblePt
.x
, firstY
)), wxSize(clientSize
.x
, lastY
- firstY
));
6952 m_ctrl
->RefreshRect(rect
);
6956 m_ctrl
->Refresh(false);
6958 #if wxRICHTEXT_USE_OWN_CARET
6959 m_ctrl
->PositionCaret();
6961 if (sendUpdateEvent
)
6962 wxTextCtrl::SendTextUpdatedEvent(m_ctrl
);
6967 /// Replace the buffer paragraphs with the new ones.
6968 void wxRichTextAction::ApplyParagraphs(const wxRichTextParagraphLayoutBox
& fragment
)
6970 wxRichTextObjectList::compatibility_iterator node
= fragment
.GetChildren().GetFirst();
6973 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
6974 wxASSERT (para
!= NULL
);
6976 // We'll replace the existing paragraph by finding the paragraph at this position,
6977 // delete its node data, and setting a copy as the new node data.
6978 // TODO: make more efficient by simply swapping old and new paragraph objects.
6980 wxRichTextParagraph
* existingPara
= m_buffer
->GetParagraphAtPosition(para
->GetRange().GetStart());
6983 wxRichTextObjectList::compatibility_iterator bufferParaNode
= m_buffer
->GetChildren().Find(existingPara
);
6986 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(*para
);
6987 newPara
->SetParent(m_buffer
);
6989 bufferParaNode
->SetData(newPara
);
6991 delete existingPara
;
6995 node
= node
->GetNext();
7002 * This stores beginning and end positions for a range of data.
7005 /// Limit this range to be within 'range'
7006 bool wxRichTextRange::LimitTo(const wxRichTextRange
& range
)
7008 if (m_start
< range
.m_start
)
7009 m_start
= range
.m_start
;
7011 if (m_end
> range
.m_end
)
7012 m_end
= range
.m_end
;
7018 * wxRichTextImage implementation
7019 * This object represents an image.
7022 IMPLEMENT_DYNAMIC_CLASS(wxRichTextImage
, wxRichTextObject
)
7024 wxRichTextImage::wxRichTextImage(const wxImage
& image
, wxRichTextObject
* parent
, wxTextAttr
* charStyle
):
7025 wxRichTextObject(parent
)
7029 SetAttributes(*charStyle
);
7032 wxRichTextImage::wxRichTextImage(const wxRichTextImageBlock
& imageBlock
, wxRichTextObject
* parent
, wxTextAttr
* charStyle
):
7033 wxRichTextObject(parent
)
7035 m_imageBlock
= imageBlock
;
7036 m_imageBlock
.Load(m_image
);
7038 SetAttributes(*charStyle
);
7041 /// Load wxImage from the block
7042 bool wxRichTextImage::LoadFromBlock()
7044 m_imageBlock
.Load(m_image
);
7045 return m_imageBlock
.Ok();
7048 /// Make block from the wxImage
7049 bool wxRichTextImage::MakeBlock()
7051 if (m_imageBlock
.GetImageType() == wxBITMAP_TYPE_ANY
|| m_imageBlock
.GetImageType() == -1)
7052 m_imageBlock
.SetImageType(wxBITMAP_TYPE_PNG
);
7054 m_imageBlock
.MakeImageBlock(m_image
, m_imageBlock
.GetImageType());
7055 return m_imageBlock
.Ok();
7060 bool wxRichTextImage::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int WXUNUSED(descent
), int WXUNUSED(style
))
7062 if (!m_image
.Ok() && m_imageBlock
.Ok())
7068 if (m_image
.Ok() && !m_bitmap
.Ok())
7069 m_bitmap
= wxBitmap(m_image
);
7071 int y
= rect
.y
+ (rect
.height
- m_image
.GetHeight());
7074 dc
.DrawBitmap(m_bitmap
, rect
.x
, y
, true);
7076 if (selectionRange
.Contains(range
.GetStart()))
7078 wxCheckSetBrush(dc
, *wxBLACK_BRUSH
);
7079 wxCheckSetPen(dc
, *wxBLACK_PEN
);
7080 dc
.SetLogicalFunction(wxINVERT
);
7081 dc
.DrawRectangle(rect
);
7082 dc
.SetLogicalFunction(wxCOPY
);
7088 /// Lay the item out
7089 bool wxRichTextImage::Layout(wxDC
& WXUNUSED(dc
), const wxRect
& rect
, int WXUNUSED(style
))
7096 SetCachedSize(wxSize(m_image
.GetWidth(), m_image
.GetHeight()));
7097 SetPosition(rect
.GetPosition());
7103 /// Get/set the object size for the given range. Returns false if the range
7104 /// is invalid for this object.
7105 bool wxRichTextImage::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& WXUNUSED(descent
), wxDC
& WXUNUSED(dc
), int WXUNUSED(flags
), wxPoint
WXUNUSED(position
), wxArrayInt
* partialExtents
) const
7107 if (!range
.IsWithin(GetRange()))
7111 ((wxRichTextImage
*) this)->LoadFromBlock();
7116 partialExtents
->Add(m_image
.GetWidth());
7118 partialExtents
->Add(0);
7124 size
.x
= m_image
.GetWidth();
7125 size
.y
= m_image
.GetHeight();
7131 void wxRichTextImage::Copy(const wxRichTextImage
& obj
)
7133 wxRichTextObject::Copy(obj
);
7135 m_image
= obj
.m_image
;
7136 m_imageBlock
= obj
.m_imageBlock
;
7144 /// Compare two attribute objects
7145 bool wxTextAttrEq(const wxTextAttr
& attr1
, const wxTextAttr
& attr2
)
7147 return (attr1
== attr2
);
7150 // Partial equality test taking flags into account
7151 bool wxTextAttrEqPartial(const wxTextAttr
& attr1
, const wxTextAttr
& attr2
, int flags
)
7153 return attr1
.EqPartial(attr2
, flags
);
7157 bool wxRichTextTabsEq(const wxArrayInt
& tabs1
, const wxArrayInt
& tabs2
)
7159 if (tabs1
.GetCount() != tabs2
.GetCount())
7163 for (i
= 0; i
< tabs1
.GetCount(); i
++)
7165 if (tabs1
[i
] != tabs2
[i
])
7171 bool wxRichTextApplyStyle(wxTextAttr
& destStyle
, const wxTextAttr
& style
, wxTextAttr
* compareWith
)
7173 return destStyle
.Apply(style
, compareWith
);
7176 // Remove attributes
7177 bool wxRichTextRemoveStyle(wxTextAttr
& destStyle
, const wxTextAttr
& style
)
7179 return wxTextAttr::RemoveStyle(destStyle
, style
);
7182 /// Combine two bitlists, specifying the bits of interest with separate flags.
7183 bool wxRichTextCombineBitlists(int& valueA
, int valueB
, int& flagsA
, int flagsB
)
7185 return wxTextAttr::CombineBitlists(valueA
, valueB
, flagsA
, flagsB
);
7188 /// Compare two bitlists
7189 bool wxRichTextBitlistsEqPartial(int valueA
, int valueB
, int flags
)
7191 return wxTextAttr::BitlistsEqPartial(valueA
, valueB
, flags
);
7194 /// Split into paragraph and character styles
7195 bool wxRichTextSplitParaCharStyles(const wxTextAttr
& style
, wxTextAttr
& parStyle
, wxTextAttr
& charStyle
)
7197 return wxTextAttr::SplitParaCharStyles(style
, parStyle
, charStyle
);
7200 /// Convert a decimal to Roman numerals
7201 wxString
wxRichTextDecimalToRoman(long n
)
7203 static wxArrayInt decimalNumbers
;
7204 static wxArrayString romanNumbers
;
7209 decimalNumbers
.Clear();
7210 romanNumbers
.Clear();
7211 return wxEmptyString
;
7214 if (decimalNumbers
.GetCount() == 0)
7216 #define wxRichTextAddDecRom(n, r) decimalNumbers.Add(n); romanNumbers.Add(r);
7218 wxRichTextAddDecRom(1000, wxT("M"));
7219 wxRichTextAddDecRom(900, wxT("CM"));
7220 wxRichTextAddDecRom(500, wxT("D"));
7221 wxRichTextAddDecRom(400, wxT("CD"));
7222 wxRichTextAddDecRom(100, wxT("C"));
7223 wxRichTextAddDecRom(90, wxT("XC"));
7224 wxRichTextAddDecRom(50, wxT("L"));
7225 wxRichTextAddDecRom(40, wxT("XL"));
7226 wxRichTextAddDecRom(10, wxT("X"));
7227 wxRichTextAddDecRom(9, wxT("IX"));
7228 wxRichTextAddDecRom(5, wxT("V"));
7229 wxRichTextAddDecRom(4, wxT("IV"));
7230 wxRichTextAddDecRom(1, wxT("I"));
7236 while (n
> 0 && i
< 13)
7238 if (n
>= decimalNumbers
[i
])
7240 n
-= decimalNumbers
[i
];
7241 roman
+= romanNumbers
[i
];
7248 if (roman
.IsEmpty())
7254 * wxRichTextFileHandler
7255 * Base class for file handlers
7258 IMPLEMENT_CLASS(wxRichTextFileHandler
, wxObject
)
7260 #if wxUSE_FFILE && wxUSE_STREAMS
7261 bool wxRichTextFileHandler::LoadFile(wxRichTextBuffer
*buffer
, const wxString
& filename
)
7263 wxFFileInputStream
stream(filename
);
7265 return LoadFile(buffer
, stream
);
7270 bool wxRichTextFileHandler::SaveFile(wxRichTextBuffer
*buffer
, const wxString
& filename
)
7272 wxFFileOutputStream
stream(filename
);
7274 return SaveFile(buffer
, stream
);
7278 #endif // wxUSE_FFILE && wxUSE_STREAMS
7280 /// Can we handle this filename (if using files)? By default, checks the extension.
7281 bool wxRichTextFileHandler::CanHandle(const wxString
& filename
) const
7283 wxString path
, file
, ext
;
7284 wxSplitPath(filename
, & path
, & file
, & ext
);
7286 return (ext
.Lower() == GetExtension());
7290 * wxRichTextTextHandler
7291 * Plain text handler
7294 IMPLEMENT_CLASS(wxRichTextPlainTextHandler
, wxRichTextFileHandler
)
7297 bool wxRichTextPlainTextHandler::DoLoadFile(wxRichTextBuffer
*buffer
, wxInputStream
& stream
)
7305 while (!stream
.Eof())
7307 int ch
= stream
.GetC();
7311 if (ch
== 10 && lastCh
!= 13)
7314 if (ch
> 0 && ch
!= 10)
7321 buffer
->ResetAndClearCommands();
7323 buffer
->AddParagraphs(str
);
7324 buffer
->UpdateRanges();
7329 bool wxRichTextPlainTextHandler::DoSaveFile(wxRichTextBuffer
*buffer
, wxOutputStream
& stream
)
7334 wxString text
= buffer
->GetText();
7336 wxString newLine
= wxRichTextLineBreakChar
;
7337 text
.Replace(newLine
, wxT("\n"));
7339 wxCharBuffer buf
= text
.ToAscii();
7341 stream
.Write((const char*) buf
, text
.length());
7344 #endif // wxUSE_STREAMS
7347 * Stores information about an image, in binary in-memory form
7350 wxRichTextImageBlock::wxRichTextImageBlock()
7355 wxRichTextImageBlock::wxRichTextImageBlock(const wxRichTextImageBlock
& block
):wxObject()
7361 wxRichTextImageBlock::~wxRichTextImageBlock()
7370 void wxRichTextImageBlock::Init()
7374 m_imageType
= wxBITMAP_TYPE_INVALID
;
7377 void wxRichTextImageBlock::Clear()
7382 m_imageType
= wxBITMAP_TYPE_INVALID
;
7386 // Load the original image into a memory block.
7387 // If the image is not a JPEG, we must convert it into a JPEG
7388 // to conserve space.
7389 // If it's not a JPEG we can make use of 'image', already scaled, so we don't have to
7390 // load the image a 2nd time.
7392 bool wxRichTextImageBlock::MakeImageBlock(const wxString
& filename
, wxBitmapType imageType
,
7393 wxImage
& image
, bool convertToJPEG
)
7395 m_imageType
= imageType
;
7397 wxString
filenameToRead(filename
);
7398 bool removeFile
= false;
7400 if (imageType
== -1)
7401 return false; // Could not determine image type
7403 if ((imageType
!= wxBITMAP_TYPE_JPEG
) && convertToJPEG
)
7406 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
7410 wxUnusedVar(success
);
7412 image
.SaveFile(tempFile
, wxBITMAP_TYPE_JPEG
);
7413 filenameToRead
= tempFile
;
7416 m_imageType
= wxBITMAP_TYPE_JPEG
;
7419 if (!file
.Open(filenameToRead
))
7422 m_dataSize
= (size_t) file
.Length();
7427 m_data
= ReadBlock(filenameToRead
, m_dataSize
);
7430 wxRemoveFile(filenameToRead
);
7432 return (m_data
!= NULL
);
7435 // Make an image block from the wxImage in the given
7437 bool wxRichTextImageBlock::MakeImageBlock(wxImage
& image
, wxBitmapType imageType
, int quality
)
7439 m_imageType
= imageType
;
7440 image
.SetOption(wxT("quality"), quality
);
7442 if (imageType
== -1)
7443 return false; // Could not determine image type
7446 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
7449 wxUnusedVar(success
);
7451 if (!image
.SaveFile(tempFile
, m_imageType
))
7453 if (wxFileExists(tempFile
))
7454 wxRemoveFile(tempFile
);
7459 if (!file
.Open(tempFile
))
7462 m_dataSize
= (size_t) file
.Length();
7467 m_data
= ReadBlock(tempFile
, m_dataSize
);
7469 wxRemoveFile(tempFile
);
7471 return (m_data
!= NULL
);
7476 bool wxRichTextImageBlock::Write(const wxString
& filename
)
7478 return WriteBlock(filename
, m_data
, m_dataSize
);
7481 void wxRichTextImageBlock::Copy(const wxRichTextImageBlock
& block
)
7483 m_imageType
= block
.m_imageType
;
7489 m_dataSize
= block
.m_dataSize
;
7490 if (m_dataSize
== 0)
7493 m_data
= new unsigned char[m_dataSize
];
7495 for (i
= 0; i
< m_dataSize
; i
++)
7496 m_data
[i
] = block
.m_data
[i
];
7500 void wxRichTextImageBlock::operator=(const wxRichTextImageBlock
& block
)
7505 // Load a wxImage from the block
7506 bool wxRichTextImageBlock::Load(wxImage
& image
)
7511 // Read in the image.
7513 wxMemoryInputStream
mstream(m_data
, m_dataSize
);
7514 bool success
= image
.LoadFile(mstream
, GetImageType());
7517 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
7520 if (!WriteBlock(tempFile
, m_data
, m_dataSize
))
7524 success
= image
.LoadFile(tempFile
, GetImageType());
7525 wxRemoveFile(tempFile
);
7531 // Write data in hex to a stream
7532 bool wxRichTextImageBlock::WriteHex(wxOutputStream
& stream
)
7534 const int bufSize
= 512;
7535 char buf
[bufSize
+1];
7537 int left
= m_dataSize
;
7542 if (left
*2 > bufSize
)
7544 n
= bufSize
; left
-= (bufSize
/2);
7548 n
= left
*2; left
= 0;
7552 for (i
= 0; i
< (n
/2); i
++)
7554 wxDecToHex(m_data
[j
], b
, b
+1);
7559 stream
.Write((const char*) buf
, n
);
7564 // Read data in hex from a stream
7565 bool wxRichTextImageBlock::ReadHex(wxInputStream
& stream
, int length
, wxBitmapType imageType
)
7567 int dataSize
= length
/2;
7573 m_data
= new unsigned char[dataSize
];
7575 for (i
= 0; i
< dataSize
; i
++)
7577 str
[0] = (char)stream
.GetC();
7578 str
[1] = (char)stream
.GetC();
7580 m_data
[i
] = (unsigned char)wxHexToDec(str
);
7583 m_dataSize
= dataSize
;
7584 m_imageType
= imageType
;
7589 // Allocate and read from stream as a block of memory
7590 unsigned char* wxRichTextImageBlock::ReadBlock(wxInputStream
& stream
, size_t size
)
7592 unsigned char* block
= new unsigned char[size
];
7596 stream
.Read(block
, size
);
7601 unsigned char* wxRichTextImageBlock::ReadBlock(const wxString
& filename
, size_t size
)
7603 wxFileInputStream
stream(filename
);
7607 return ReadBlock(stream
, size
);
7610 // Write memory block to stream
7611 bool wxRichTextImageBlock::WriteBlock(wxOutputStream
& stream
, unsigned char* block
, size_t size
)
7613 stream
.Write((void*) block
, size
);
7614 return stream
.IsOk();
7618 // Write memory block to file
7619 bool wxRichTextImageBlock::WriteBlock(const wxString
& filename
, unsigned char* block
, size_t size
)
7621 wxFileOutputStream
outStream(filename
);
7622 if (!outStream
.Ok())
7625 return WriteBlock(outStream
, block
, size
);
7628 // Gets the extension for the block's type
7629 wxString
wxRichTextImageBlock::GetExtension() const
7631 wxImageHandler
* handler
= wxImage::FindHandler(GetImageType());
7633 return handler
->GetExtension();
7635 return wxEmptyString
;
7641 * The data object for a wxRichTextBuffer
7644 const wxChar
*wxRichTextBufferDataObject::ms_richTextBufferFormatId
= wxT("wxShape");
7646 wxRichTextBufferDataObject::wxRichTextBufferDataObject(wxRichTextBuffer
* richTextBuffer
)
7648 m_richTextBuffer
= richTextBuffer
;
7650 // this string should uniquely identify our format, but is otherwise
7652 m_formatRichTextBuffer
.SetId(GetRichTextBufferFormatId());
7654 SetFormat(m_formatRichTextBuffer
);
7657 wxRichTextBufferDataObject::~wxRichTextBufferDataObject()
7659 delete m_richTextBuffer
;
7662 // after a call to this function, the richTextBuffer is owned by the caller and it
7663 // is responsible for deleting it!
7664 wxRichTextBuffer
* wxRichTextBufferDataObject::GetRichTextBuffer()
7666 wxRichTextBuffer
* richTextBuffer
= m_richTextBuffer
;
7667 m_richTextBuffer
= NULL
;
7669 return richTextBuffer
;
7672 wxDataFormat
wxRichTextBufferDataObject::GetPreferredFormat(Direction
WXUNUSED(dir
)) const
7674 return m_formatRichTextBuffer
;
7677 size_t wxRichTextBufferDataObject::GetDataSize() const
7679 if (!m_richTextBuffer
)
7685 wxStringOutputStream
stream(& bufXML
);
7686 if (!m_richTextBuffer
->SaveFile(stream
, wxRICHTEXT_TYPE_XML
))
7688 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
7694 wxCharBuffer buffer
= bufXML
.mb_str(wxConvUTF8
);
7695 return strlen(buffer
) + 1;
7697 return bufXML
.Length()+1;
7701 bool wxRichTextBufferDataObject::GetDataHere(void *pBuf
) const
7703 if (!pBuf
|| !m_richTextBuffer
)
7709 wxStringOutputStream
stream(& bufXML
);
7710 if (!m_richTextBuffer
->SaveFile(stream
, wxRICHTEXT_TYPE_XML
))
7712 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
7718 wxCharBuffer buffer
= bufXML
.mb_str(wxConvUTF8
);
7719 size_t len
= strlen(buffer
);
7720 memcpy((char*) pBuf
, (const char*) buffer
, len
);
7721 ((char*) pBuf
)[len
] = 0;
7723 size_t len
= bufXML
.Length();
7724 memcpy((char*) pBuf
, (const char*) bufXML
.c_str(), len
);
7725 ((char*) pBuf
)[len
] = 0;
7731 bool wxRichTextBufferDataObject::SetData(size_t WXUNUSED(len
), const void *buf
)
7733 delete m_richTextBuffer
;
7734 m_richTextBuffer
= NULL
;
7736 wxString
bufXML((const char*) buf
, wxConvUTF8
);
7738 m_richTextBuffer
= new wxRichTextBuffer
;
7740 wxStringInputStream
stream(bufXML
);
7741 if (!m_richTextBuffer
->LoadFile(stream
, wxRICHTEXT_TYPE_XML
))
7743 wxLogError(wxT("Could not read the buffer from an XML stream.\nYou may have forgotten to add the XML file handler."));
7745 delete m_richTextBuffer
;
7746 m_richTextBuffer
= NULL
;
7758 * wxRichTextFontTable
7759 * Manages quick access to a pool of fonts for rendering rich text
7762 WX_DECLARE_STRING_HASH_MAP_WITH_DECL(wxFont
, wxRichTextFontTableHashMap
, class WXDLLIMPEXP_RICHTEXT
);
7764 class wxRichTextFontTableData
: public wxObjectRefData
7767 wxRichTextFontTableData() {}
7769 wxFont
FindFont(const wxTextAttr
& fontSpec
);
7771 wxRichTextFontTableHashMap m_hashMap
;
7774 wxFont
wxRichTextFontTableData::FindFont(const wxTextAttr
& fontSpec
)
7776 wxString
facename(fontSpec
.GetFontFaceName());
7777 wxString
spec(wxString::Format(wxT("%d-%d-%d-%d-%s-%d"), fontSpec
.GetFontSize(), fontSpec
.GetFontStyle(), fontSpec
.GetFontWeight(), (int) fontSpec
.GetFontUnderlined(), facename
.c_str(), (int) fontSpec
.GetFontEncoding()));
7778 wxRichTextFontTableHashMap::iterator entry
= m_hashMap
.find(spec
);
7780 if ( entry
== m_hashMap
.end() )
7782 wxFont
font(fontSpec
.GetFontSize(), wxDEFAULT
, fontSpec
.GetFontStyle(), fontSpec
.GetFontWeight(), fontSpec
.GetFontUnderlined(), facename
.c_str());
7783 m_hashMap
[spec
] = font
;
7788 return entry
->second
;
7792 IMPLEMENT_DYNAMIC_CLASS(wxRichTextFontTable
, wxObject
)
7794 wxRichTextFontTable::wxRichTextFontTable()
7796 m_refData
= new wxRichTextFontTableData
;
7799 wxRichTextFontTable::wxRichTextFontTable(const wxRichTextFontTable
& table
)
7805 wxRichTextFontTable::~wxRichTextFontTable()
7810 bool wxRichTextFontTable::operator == (const wxRichTextFontTable
& table
) const
7812 return (m_refData
== table
.m_refData
);
7815 void wxRichTextFontTable::operator= (const wxRichTextFontTable
& table
)
7820 wxFont
wxRichTextFontTable::FindFont(const wxTextAttr
& fontSpec
)
7822 wxRichTextFontTableData
* data
= (wxRichTextFontTableData
*) m_refData
;
7824 return data
->FindFont(fontSpec
);
7829 void wxRichTextFontTable::Clear()
7831 wxRichTextFontTableData
* data
= (wxRichTextFontTableData
*) m_refData
;
7833 data
->m_hashMap
.clear();