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()
430 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
433 wxRichTextObject
* child
= node
->GetData();
434 wxRichTextCompositeObject
* composite
= wxDynamicCast(child
, wxRichTextCompositeObject
);
436 composite
->Defragment();
440 wxRichTextObject
* nextChild
= node
->GetNext()->GetData();
441 if (child
->CanMerge(nextChild
) && child
->Merge(nextChild
))
443 nextChild
->Dereference();
444 m_children
.Erase(node
->GetNext());
446 // Don't set node -- we'll see if we can merge again with the next
450 node
= node
->GetNext();
453 node
= node
->GetNext();
459 /// Dump to output stream for debugging
460 void wxRichTextCompositeObject::Dump(wxTextOutputStream
& stream
)
462 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
465 wxRichTextObject
* child
= node
->GetData();
467 node
= node
->GetNext();
474 * This defines a 2D space to lay out objects
477 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBox
, wxRichTextCompositeObject
)
479 wxRichTextBox::wxRichTextBox(wxRichTextObject
* parent
):
480 wxRichTextCompositeObject(parent
)
485 bool wxRichTextBox::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& WXUNUSED(rect
), int descent
, int style
)
487 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
490 wxRichTextObject
* child
= node
->GetData();
492 wxRect childRect
= wxRect(child
->GetPosition(), child
->GetCachedSize());
493 child
->Draw(dc
, range
, selectionRange
, childRect
, descent
, style
);
495 node
= node
->GetNext();
501 bool wxRichTextBox::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
503 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
506 wxRichTextObject
* child
= node
->GetData();
507 child
->Layout(dc
, rect
, style
);
509 node
= node
->GetNext();
515 /// Get/set the size for the given range. Assume only has one child.
516 bool wxRichTextBox::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
, wxArrayInt
* partialExtents
) const
518 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
521 wxRichTextObject
* child
= node
->GetData();
522 return child
->GetRangeSize(range
, size
, descent
, dc
, flags
, position
, partialExtents
);
529 void wxRichTextBox::Copy(const wxRichTextBox
& obj
)
531 wxRichTextCompositeObject::Copy(obj
);
536 * wxRichTextParagraphLayoutBox
537 * This box knows how to lay out paragraphs.
540 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraphLayoutBox
, wxRichTextBox
)
542 wxRichTextParagraphLayoutBox::wxRichTextParagraphLayoutBox(wxRichTextObject
* parent
):
543 wxRichTextBox(parent
)
548 /// Initialize the object.
549 void wxRichTextParagraphLayoutBox::Init()
553 // For now, assume is the only box and has no initial size.
554 m_range
= wxRichTextRange(0, -1);
556 m_invalidRange
.SetRange(-1, -1);
561 m_partialParagraph
= false;
565 bool wxRichTextParagraphLayoutBox::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int descent
, int style
)
567 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
570 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
571 wxASSERT (child
!= NULL
);
573 if (child
&& !child
->GetRange().IsOutside(range
))
575 wxRect
childRect(child
->GetPosition(), child
->GetCachedSize());
577 if (((style
& wxRICHTEXT_DRAW_IGNORE_CACHE
) == 0) && childRect
.GetTop() > rect
.GetBottom())
582 else if (((style
& wxRICHTEXT_DRAW_IGNORE_CACHE
) == 0) && childRect
.GetBottom() < rect
.GetTop())
587 child
->Draw(dc
, range
, selectionRange
, childRect
, descent
, style
);
590 node
= node
->GetNext();
596 bool wxRichTextParagraphLayoutBox::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
598 wxRect availableSpace
;
599 bool formatRect
= (style
& wxRICHTEXT_LAYOUT_SPECIFIED_RECT
) == wxRICHTEXT_LAYOUT_SPECIFIED_RECT
;
601 // If only laying out a specific area, the passed rect has a different meaning:
602 // the visible part of the buffer. This is used in wxRichTextCtrl::OnSize,
603 // so that during a size, only the visible part will be relaid out, or
604 // it would take too long causing flicker. As an approximation, we assume that
605 // everything up to the start of the visible area is laid out correctly.
608 availableSpace
= wxRect(0 + m_leftMargin
,
610 rect
.width
- m_leftMargin
- m_rightMargin
,
613 // Invalidate the part of the buffer from the first visible line
614 // to the end. If other parts of the buffer are currently invalid,
615 // then they too will be taken into account if they are above
616 // the visible point.
618 wxRichTextLine
* line
= GetLineAtYPosition(rect
.y
);
620 startPos
= line
->GetAbsoluteRange().GetStart();
622 Invalidate(wxRichTextRange(startPos
, GetRange().GetEnd()));
625 availableSpace
= wxRect(rect
.x
+ m_leftMargin
,
626 rect
.y
+ m_topMargin
,
627 rect
.width
- m_leftMargin
- m_rightMargin
,
628 rect
.height
- m_topMargin
- m_bottomMargin
);
632 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
634 bool layoutAll
= true;
636 // Get invalid range, rounding to paragraph start/end.
637 wxRichTextRange invalidRange
= GetInvalidRange(true);
639 if (invalidRange
== wxRICHTEXT_NONE
&& !formatRect
)
642 if (invalidRange
== wxRICHTEXT_ALL
)
644 else // If we know what range is affected, start laying out from that point on.
645 if (invalidRange
.GetStart() >= GetRange().GetStart())
647 wxRichTextParagraph
* firstParagraph
= GetParagraphAtPosition(invalidRange
.GetStart());
650 wxRichTextObjectList::compatibility_iterator firstNode
= m_children
.Find(firstParagraph
);
651 wxRichTextObjectList::compatibility_iterator previousNode
;
653 previousNode
= firstNode
->GetPrevious();
658 wxRichTextParagraph
* previousParagraph
= wxDynamicCast(previousNode
->GetData(), wxRichTextParagraph
);
659 availableSpace
.y
= previousParagraph
->GetPosition().y
+ previousParagraph
->GetCachedSize().y
;
662 // Now we're going to start iterating from the first affected paragraph.
670 // A way to force speedy rest-of-buffer layout (the 'else' below)
671 bool forceQuickLayout
= false;
675 // Assume this box only contains paragraphs
677 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
678 wxCHECK_MSG( child
, false, _T("Unknown object in layout") );
680 // TODO: what if the child hasn't been laid out (e.g. involved in Undo) but still has 'old' lines
681 if ( !forceQuickLayout
&&
683 child
->GetLines().IsEmpty() ||
684 !child
->GetRange().IsOutside(invalidRange
)) )
686 child
->Layout(dc
, availableSpace
, style
);
688 // Layout must set the cached size
689 availableSpace
.y
+= child
->GetCachedSize().y
;
690 maxWidth
= wxMax(maxWidth
, child
->GetCachedSize().x
);
692 // If we're just formatting the visible part of the buffer,
693 // and we're now past the bottom of the window, start quick
695 if (formatRect
&& child
->GetPosition().y
> rect
.GetBottom())
696 forceQuickLayout
= true;
700 // We're outside the immediately affected range, so now let's just
701 // move everything up or down. This assumes that all the children have previously
702 // been laid out and have wrapped line lists associated with them.
703 // TODO: check all paragraphs before the affected range.
705 int inc
= availableSpace
.y
- child
->GetPosition().y
;
709 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
712 if (child
->GetLines().GetCount() == 0)
713 child
->Layout(dc
, availableSpace
, style
);
715 child
->SetPosition(wxPoint(child
->GetPosition().x
, child
->GetPosition().y
+ inc
));
717 availableSpace
.y
+= child
->GetCachedSize().y
;
718 maxWidth
= wxMax(maxWidth
, child
->GetCachedSize().x
);
721 node
= node
->GetNext();
726 node
= node
->GetNext();
729 SetCachedSize(wxSize(maxWidth
, availableSpace
.y
));
732 m_invalidRange
= wxRICHTEXT_NONE
;
738 void wxRichTextParagraphLayoutBox::Copy(const wxRichTextParagraphLayoutBox
& obj
)
740 wxRichTextBox::Copy(obj
);
742 m_partialParagraph
= obj
.m_partialParagraph
;
743 m_defaultAttributes
= obj
.m_defaultAttributes
;
746 /// Get/set the size for the given range.
747 bool wxRichTextParagraphLayoutBox::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
, wxArrayInt
* WXUNUSED(partialExtents
)) const
751 wxRichTextObjectList::compatibility_iterator startPara
= wxRichTextObjectList::compatibility_iterator();
752 wxRichTextObjectList::compatibility_iterator endPara
= wxRichTextObjectList::compatibility_iterator();
754 // First find the first paragraph whose starting position is within the range.
755 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
758 // child is a paragraph
759 wxRichTextObject
* child
= node
->GetData();
760 const wxRichTextRange
& r
= child
->GetRange();
762 if (r
.GetStart() <= range
.GetStart() && r
.GetEnd() >= range
.GetStart())
768 node
= node
->GetNext();
771 // Next find the last paragraph containing part of the range
772 node
= m_children
.GetFirst();
775 // child is a paragraph
776 wxRichTextObject
* child
= node
->GetData();
777 const wxRichTextRange
& r
= child
->GetRange();
779 if (r
.GetStart() <= range
.GetEnd() && r
.GetEnd() >= range
.GetEnd())
785 node
= node
->GetNext();
788 if (!startPara
|| !endPara
)
791 // Now we can add up the sizes
792 for (node
= startPara
; node
; node
= node
->GetNext())
794 // child is a paragraph
795 wxRichTextObject
* child
= node
->GetData();
796 const wxRichTextRange
& childRange
= child
->GetRange();
797 wxRichTextRange rangeToFind
= range
;
798 rangeToFind
.LimitTo(childRange
);
802 int childDescent
= 0;
803 child
->GetRangeSize(rangeToFind
, childSize
, childDescent
, dc
, flags
, position
);
805 descent
= wxMax(childDescent
, descent
);
807 sz
.x
= wxMax(sz
.x
, childSize
.x
);
819 /// Get the paragraph at the given position
820 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphAtPosition(long pos
, bool caretPosition
) const
825 // First find the first paragraph whose starting position is within the range.
826 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
829 // child is a paragraph
830 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
831 wxASSERT (child
!= NULL
);
833 // Return first child in buffer if position is -1
837 if (child
->GetRange().Contains(pos
))
840 node
= node
->GetNext();
845 /// Get the line at the given position
846 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineAtPosition(long pos
, bool caretPosition
) const
851 // First find the first paragraph whose starting position is within the range.
852 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
855 // child is a paragraph
856 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
857 wxASSERT (child
!= NULL
);
859 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
862 wxRichTextLine
* line
= node2
->GetData();
864 wxRichTextRange range
= line
->GetAbsoluteRange();
866 if (range
.Contains(pos
) ||
868 // If the position is end-of-paragraph, then return the last line of
870 (range
.GetEnd() == child
->GetRange().GetEnd()-1) && (pos
== child
->GetRange().GetEnd()))
873 node2
= node2
->GetNext();
876 node
= node
->GetNext();
879 int lineCount
= GetLineCount();
881 return GetLineForVisibleLineNumber(lineCount
-1);
886 /// Get the line at the given y pixel position, or the last line.
887 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineAtYPosition(int y
) const
889 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
892 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
893 wxASSERT (child
!= NULL
);
895 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
898 wxRichTextLine
* line
= node2
->GetData();
900 wxRect
rect(line
->GetRect());
902 if (y
<= rect
.GetBottom())
905 node2
= node2
->GetNext();
908 node
= node
->GetNext();
912 int lineCount
= GetLineCount();
914 return GetLineForVisibleLineNumber(lineCount
-1);
919 /// Get the number of visible lines
920 int wxRichTextParagraphLayoutBox::GetLineCount() const
924 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
927 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
928 wxASSERT (child
!= NULL
);
930 count
+= child
->GetLines().GetCount();
931 node
= node
->GetNext();
937 /// Get the paragraph for a given line
938 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphForLine(wxRichTextLine
* line
) const
940 return GetParagraphAtPosition(line
->GetAbsoluteRange().GetStart());
943 /// Get the line size at the given position
944 wxSize
wxRichTextParagraphLayoutBox::GetLineSizeAtPosition(long pos
, bool caretPosition
) const
946 wxRichTextLine
* line
= GetLineAtPosition(pos
, caretPosition
);
949 return line
->GetSize();
956 /// Convenience function to add a paragraph of text
957 wxRichTextRange
wxRichTextParagraphLayoutBox::AddParagraph(const wxString
& text
, wxTextAttr
* paraStyle
)
959 // Don't use the base style, just the default style, and the base style will
960 // be combined at display time.
961 // Divide into paragraph and character styles.
963 wxTextAttr defaultCharStyle
;
964 wxTextAttr defaultParaStyle
;
966 // If the default style is a named paragraph style, don't apply any character formatting
967 // to the initial text string.
968 if (GetDefaultStyle().HasParagraphStyleName() && GetStyleSheet())
970 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(GetDefaultStyle().GetParagraphStyleName());
972 defaultParaStyle
= def
->GetStyleMergedWithBase(GetStyleSheet());
975 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
977 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
978 wxTextAttr
* cStyle
= & defaultCharStyle
;
980 wxRichTextParagraph
* para
= new wxRichTextParagraph(text
, this, pStyle
, cStyle
);
987 return para
->GetRange();
990 /// Adds multiple paragraphs, based on newlines.
991 wxRichTextRange
wxRichTextParagraphLayoutBox::AddParagraphs(const wxString
& text
, wxTextAttr
* paraStyle
)
993 // Don't use the base style, just the default style, and the base style will
994 // be combined at display time.
995 // Divide into paragraph and character styles.
997 wxTextAttr defaultCharStyle
;
998 wxTextAttr defaultParaStyle
;
1000 // If the default style is a named paragraph style, don't apply any character formatting
1001 // to the initial text string.
1002 if (GetDefaultStyle().HasParagraphStyleName() && GetStyleSheet())
1004 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(GetDefaultStyle().GetParagraphStyleName());
1006 defaultParaStyle
= def
->GetStyleMergedWithBase(GetStyleSheet());
1009 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
1011 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
1012 wxTextAttr
* cStyle
= & defaultCharStyle
;
1014 wxRichTextParagraph
* firstPara
= NULL
;
1015 wxRichTextParagraph
* lastPara
= NULL
;
1017 wxRichTextRange
range(-1, -1);
1020 size_t len
= text
.length();
1022 wxRichTextParagraph
* para
= new wxRichTextParagraph(wxEmptyString
, this, pStyle
, cStyle
);
1031 wxChar ch
= text
[i
];
1032 if (ch
== wxT('\n') || ch
== wxT('\r'))
1036 wxRichTextPlainText
* plainText
= (wxRichTextPlainText
*) para
->GetChildren().GetFirst()->GetData();
1037 plainText
->SetText(line
);
1039 para
= new wxRichTextParagraph(wxEmptyString
, this, pStyle
, cStyle
);
1044 line
= wxEmptyString
;
1055 wxRichTextPlainText
* plainText
= (wxRichTextPlainText
*) para
->GetChildren().GetFirst()->GetData();
1056 plainText
->SetText(line
);
1063 return wxRichTextRange(firstPara
->GetRange().GetStart(), lastPara
->GetRange().GetEnd());
1066 /// Convenience function to add an image
1067 wxRichTextRange
wxRichTextParagraphLayoutBox::AddImage(const wxImage
& image
, wxTextAttr
* paraStyle
)
1069 // Don't use the base style, just the default style, and the base style will
1070 // be combined at display time.
1071 // Divide into paragraph and character styles.
1073 wxTextAttr defaultCharStyle
;
1074 wxTextAttr defaultParaStyle
;
1076 // If the default style is a named paragraph style, don't apply any character formatting
1077 // to the initial text string.
1078 if (GetDefaultStyle().HasParagraphStyleName() && GetStyleSheet())
1080 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(GetDefaultStyle().GetParagraphStyleName());
1082 defaultParaStyle
= def
->GetStyleMergedWithBase(GetStyleSheet());
1085 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
1087 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
1088 wxTextAttr
* cStyle
= & defaultCharStyle
;
1090 wxRichTextParagraph
* para
= new wxRichTextParagraph(this, pStyle
);
1092 para
->AppendChild(new wxRichTextImage(image
, this, cStyle
));
1097 return para
->GetRange();
1101 /// Insert fragment into this box at the given position. If partialParagraph is true,
1102 /// it is assumed that the last (or only) paragraph is just a piece of data with no paragraph
1105 bool wxRichTextParagraphLayoutBox::InsertFragment(long position
, wxRichTextParagraphLayoutBox
& fragment
)
1109 // First, find the first paragraph whose starting position is within the range.
1110 wxRichTextParagraph
* para
= GetParagraphAtPosition(position
);
1113 wxTextAttrEx originalAttr
= para
->GetAttributes();
1115 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(para
);
1117 // Now split at this position, returning the object to insert the new
1118 // ones in front of.
1119 wxRichTextObject
* nextObject
= para
->SplitAt(position
);
1121 // Special case: partial paragraph, just one paragraph. Might be a small amount of
1122 // text, for example, so let's optimize.
1124 if (fragment
.GetPartialParagraph() && fragment
.GetChildren().GetCount() == 1)
1126 // Add the first para to this para...
1127 wxRichTextObjectList::compatibility_iterator firstParaNode
= fragment
.GetChildren().GetFirst();
1131 // Iterate through the fragment paragraph inserting the content into this paragraph.
1132 wxRichTextParagraph
* firstPara
= wxDynamicCast(firstParaNode
->GetData(), wxRichTextParagraph
);
1133 wxASSERT (firstPara
!= NULL
);
1135 wxRichTextObjectList::compatibility_iterator objectNode
= firstPara
->GetChildren().GetFirst();
1138 wxRichTextObject
* newObj
= objectNode
->GetData()->Clone();
1143 para
->AppendChild(newObj
);
1147 // Insert before nextObject
1148 para
->InsertChild(newObj
, nextObject
);
1151 objectNode
= objectNode
->GetNext();
1158 // Procedure for inserting a fragment consisting of a number of
1161 // 1. Remove and save the content that's after the insertion point, for adding
1162 // back once we've added the fragment.
1163 // 2. Add the content from the first fragment paragraph to the current
1165 // 3. Add remaining fragment paragraphs after the current paragraph.
1166 // 4. Add back the saved content from the first paragraph. If partialParagraph
1167 // is true, add it to the last paragraph added and not a new one.
1169 // 1. Remove and save objects after split point.
1170 wxList savedObjects
;
1172 para
->MoveToList(nextObject
, savedObjects
);
1174 // 2. Add the content from the 1st fragment paragraph.
1175 wxRichTextObjectList::compatibility_iterator firstParaNode
= fragment
.GetChildren().GetFirst();
1179 wxRichTextParagraph
* firstPara
= wxDynamicCast(firstParaNode
->GetData(), wxRichTextParagraph
);
1180 wxASSERT(firstPara
!= NULL
);
1182 if (!(fragment
.GetAttributes().GetFlags() & wxTEXT_ATTR_KEEP_FIRST_PARA_STYLE
))
1183 para
->SetAttributes(firstPara
->GetAttributes());
1185 // Save empty paragraph attributes for appending later
1186 // These are character attributes deliberately set for a new paragraph. Without this,
1187 // we couldn't pass default attributes when appending a new paragraph.
1188 wxTextAttrEx emptyParagraphAttributes
;
1190 wxRichTextObjectList::compatibility_iterator objectNode
= firstPara
->GetChildren().GetFirst();
1192 if (objectNode
&& firstPara
->GetChildren().GetCount() == 1 && objectNode
->GetData()->IsEmpty())
1193 emptyParagraphAttributes
= objectNode
->GetData()->GetAttributes();
1197 wxRichTextObject
* newObj
= objectNode
->GetData()->Clone();
1200 para
->AppendChild(newObj
);
1202 objectNode
= objectNode
->GetNext();
1205 // 3. Add remaining fragment paragraphs after the current paragraph.
1206 wxRichTextObjectList::compatibility_iterator nextParagraphNode
= node
->GetNext();
1207 wxRichTextObject
* nextParagraph
= NULL
;
1208 if (nextParagraphNode
)
1209 nextParagraph
= nextParagraphNode
->GetData();
1211 wxRichTextObjectList::compatibility_iterator i
= fragment
.GetChildren().GetFirst()->GetNext();
1212 wxRichTextParagraph
* finalPara
= para
;
1214 bool needExtraPara
= (!i
|| !fragment
.GetPartialParagraph());
1216 // If there was only one paragraph, we need to insert a new one.
1219 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1220 wxASSERT( para
!= NULL
);
1222 finalPara
= (wxRichTextParagraph
*) para
->Clone();
1225 InsertChild(finalPara
, nextParagraph
);
1227 AppendChild(finalPara
);
1232 // If there was only one paragraph, or we have full paragraphs in our fragment,
1233 // we need to insert a new one.
1236 finalPara
= new wxRichTextParagraph
;
1239 InsertChild(finalPara
, nextParagraph
);
1241 AppendChild(finalPara
);
1244 // 4. Add back the remaining content.
1248 finalPara
->MoveFromList(savedObjects
);
1250 // Ensure there's at least one object
1251 if (finalPara
->GetChildCount() == 0)
1253 wxRichTextPlainText
* text
= new wxRichTextPlainText(wxEmptyString
);
1254 text
->SetAttributes(emptyParagraphAttributes
);
1256 finalPara
->AppendChild(text
);
1260 if ((fragment
.GetAttributes().GetFlags() & wxTEXT_ATTR_KEEP_FIRST_PARA_STYLE
) && firstPara
)
1261 finalPara
->SetAttributes(firstPara
->GetAttributes());
1262 else if (finalPara
&& finalPara
!= para
)
1263 finalPara
->SetAttributes(originalAttr
);
1271 wxRichTextObjectList::compatibility_iterator i
= fragment
.GetChildren().GetFirst();
1274 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1275 wxASSERT( para
!= NULL
);
1277 AppendChild(para
->Clone());
1286 /// Make a copy of the fragment corresponding to the given range, putting it in 'fragment'.
1287 /// If there was an incomplete paragraph at the end, partialParagraph is set to true.
1288 bool wxRichTextParagraphLayoutBox::CopyFragment(const wxRichTextRange
& range
, wxRichTextParagraphLayoutBox
& fragment
)
1290 wxRichTextObjectList::compatibility_iterator i
= GetChildren().GetFirst();
1293 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1294 wxASSERT( para
!= NULL
);
1296 if (!para
->GetRange().IsOutside(range
))
1298 fragment
.AppendChild(para
->Clone());
1303 // Now top and tail the first and last paragraphs in our new fragment (which might be the same).
1304 if (!fragment
.IsEmpty())
1306 wxRichTextRange
topTailRange(range
);
1308 wxRichTextParagraph
* firstPara
= wxDynamicCast(fragment
.GetChildren().GetFirst()->GetData(), wxRichTextParagraph
);
1309 wxASSERT( firstPara
!= NULL
);
1311 // Chop off the start of the paragraph
1312 if (topTailRange
.GetStart() > firstPara
->GetRange().GetStart())
1314 wxRichTextRange
r(firstPara
->GetRange().GetStart(), topTailRange
.GetStart()-1);
1315 firstPara
->DeleteRange(r
);
1317 // Make sure the numbering is correct
1319 fragment
.CalculateRange(firstPara
->GetRange().GetStart(), end
);
1321 // Now, we've deleted some positions, so adjust the range
1323 topTailRange
.SetEnd(topTailRange
.GetEnd() - r
.GetLength());
1326 wxRichTextParagraph
* lastPara
= wxDynamicCast(fragment
.GetChildren().GetLast()->GetData(), wxRichTextParagraph
);
1327 wxASSERT( lastPara
!= NULL
);
1329 if (topTailRange
.GetEnd() < (lastPara
->GetRange().GetEnd()-1))
1331 wxRichTextRange
r(topTailRange
.GetEnd()+1, lastPara
->GetRange().GetEnd()-1); /* -1 since actual text ends 1 position before end of para marker */
1332 lastPara
->DeleteRange(r
);
1334 // Make sure the numbering is correct
1336 fragment
.CalculateRange(firstPara
->GetRange().GetStart(), end
);
1338 // We only have part of a paragraph at the end
1339 fragment
.SetPartialParagraph(true);
1343 if (topTailRange
.GetEnd() == (lastPara
->GetRange().GetEnd() - 1))
1344 // We have a partial paragraph (don't save last new paragraph marker)
1345 fragment
.SetPartialParagraph(true);
1347 // We have a complete paragraph
1348 fragment
.SetPartialParagraph(false);
1355 /// Given a position, get the number of the visible line (potentially many to a paragraph),
1356 /// starting from zero at the start of the buffer.
1357 long wxRichTextParagraphLayoutBox::GetVisibleLineNumber(long pos
, bool caretPosition
, bool startOfLine
) const
1364 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1367 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1368 wxASSERT( child
!= NULL
);
1370 if (child
->GetRange().Contains(pos
))
1372 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
1375 wxRichTextLine
* line
= node2
->GetData();
1376 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
1378 if (lineRange
.Contains(pos
))
1380 // If the caret is displayed at the end of the previous wrapped line,
1381 // we want to return the line it's _displayed_ at (not the actual line
1382 // containing the position).
1383 if (lineRange
.GetStart() == pos
&& !startOfLine
&& child
->GetRange().GetStart() != pos
)
1384 return lineCount
- 1;
1391 node2
= node2
->GetNext();
1393 // If we didn't find it in the lines, it must be
1394 // the last position of the paragraph. So return the last line.
1398 lineCount
+= child
->GetLines().GetCount();
1400 node
= node
->GetNext();
1407 /// Given a line number, get the corresponding wxRichTextLine object.
1408 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineForVisibleLineNumber(long lineNumber
) const
1412 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1415 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1416 wxASSERT(child
!= NULL
);
1418 if (lineNumber
< (int) (child
->GetLines().GetCount() + lineCount
))
1420 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
1423 wxRichTextLine
* line
= node2
->GetData();
1425 if (lineCount
== lineNumber
)
1430 node2
= node2
->GetNext();
1434 lineCount
+= child
->GetLines().GetCount();
1436 node
= node
->GetNext();
1443 /// Delete range from layout.
1444 bool wxRichTextParagraphLayoutBox::DeleteRange(const wxRichTextRange
& range
)
1446 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1448 wxRichTextParagraph
* firstPara
= NULL
;
1451 wxRichTextParagraph
* obj
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1452 wxASSERT (obj
!= NULL
);
1454 wxRichTextObjectList::compatibility_iterator next
= node
->GetNext();
1456 // Delete the range in each paragraph
1458 if (!obj
->GetRange().IsOutside(range
))
1460 // Deletes the content of this object within the given range
1461 obj
->DeleteRange(range
);
1463 wxRichTextRange thisRange
= obj
->GetRange();
1464 wxTextAttrEx thisAttr
= obj
->GetAttributes();
1466 // If the whole paragraph is within the range to delete,
1467 // delete the whole thing.
1468 if (range
.GetStart() <= thisRange
.GetStart() && range
.GetEnd() >= thisRange
.GetEnd())
1470 // Delete the whole object
1471 RemoveChild(obj
, true);
1474 else if (!firstPara
)
1477 // If the range includes the paragraph end, we need to join this
1478 // and the next paragraph.
1479 if (range
.GetEnd() <= thisRange
.GetEnd())
1481 // We need to move the objects from the next paragraph
1482 // to this paragraph
1484 wxRichTextParagraph
* nextParagraph
= NULL
;
1485 if ((range
.GetEnd() < thisRange
.GetEnd()) && obj
)
1486 nextParagraph
= obj
;
1489 // We're ending at the end of the paragraph, so merge the _next_ paragraph.
1491 nextParagraph
= wxDynamicCast(next
->GetData(), wxRichTextParagraph
);
1494 bool applyFinalParagraphStyle
= firstPara
&& nextParagraph
&& nextParagraph
!= firstPara
;
1496 wxTextAttrEx nextParaAttr
;
1497 if (applyFinalParagraphStyle
)
1499 // Special case when deleting the end of a paragraph - use _this_ paragraph's style,
1500 // not the next one.
1501 if (range
.GetStart() == range
.GetEnd() && range
.GetStart() == thisRange
.GetEnd())
1502 nextParaAttr
= thisAttr
;
1504 nextParaAttr
= nextParagraph
->GetAttributes();
1507 if (firstPara
&& nextParagraph
&& firstPara
!= nextParagraph
)
1509 // Move the objects to the previous para
1510 wxRichTextObjectList::compatibility_iterator node1
= nextParagraph
->GetChildren().GetFirst();
1514 wxRichTextObject
* obj1
= node1
->GetData();
1516 firstPara
->AppendChild(obj1
);
1518 wxRichTextObjectList::compatibility_iterator next1
= node1
->GetNext();
1519 nextParagraph
->GetChildren().Erase(node1
);
1524 // Delete the paragraph
1525 RemoveChild(nextParagraph
, true);
1528 // Avoid empty paragraphs
1529 if (firstPara
&& firstPara
->GetChildren().GetCount() == 0)
1531 wxRichTextPlainText
* text
= new wxRichTextPlainText(wxEmptyString
);
1532 firstPara
->AppendChild(text
);
1535 if (applyFinalParagraphStyle
)
1536 firstPara
->SetAttributes(nextParaAttr
);
1548 /// Get any text in this object for the given range
1549 wxString
wxRichTextParagraphLayoutBox::GetTextForRange(const wxRichTextRange
& range
) const
1553 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1556 wxRichTextObject
* child
= node
->GetData();
1557 if (!child
->GetRange().IsOutside(range
))
1559 wxRichTextRange childRange
= range
;
1560 childRange
.LimitTo(child
->GetRange());
1562 wxString childText
= child
->GetTextForRange(childRange
);
1566 if ((childRange
.GetEnd() == child
->GetRange().GetEnd()) && node
->GetNext())
1571 node
= node
->GetNext();
1577 /// Get all the text
1578 wxString
wxRichTextParagraphLayoutBox::GetText() const
1580 return GetTextForRange(GetRange());
1583 /// Get the paragraph by number
1584 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphAtLine(long paragraphNumber
) const
1586 if ((size_t) paragraphNumber
>= GetChildCount())
1589 return (wxRichTextParagraph
*) GetChild((size_t) paragraphNumber
);
1592 /// Get the length of the paragraph
1593 int wxRichTextParagraphLayoutBox::GetParagraphLength(long paragraphNumber
) const
1595 wxRichTextParagraph
* para
= GetParagraphAtLine(paragraphNumber
);
1597 return para
->GetRange().GetLength() - 1; // don't include newline
1602 /// Get the text of the paragraph
1603 wxString
wxRichTextParagraphLayoutBox::GetParagraphText(long paragraphNumber
) const
1605 wxRichTextParagraph
* para
= GetParagraphAtLine(paragraphNumber
);
1607 return para
->GetTextForRange(para
->GetRange());
1609 return wxEmptyString
;
1612 /// Convert zero-based line column and paragraph number to a position.
1613 long wxRichTextParagraphLayoutBox::XYToPosition(long x
, long y
) const
1615 wxRichTextParagraph
* para
= GetParagraphAtLine(y
);
1618 return para
->GetRange().GetStart() + x
;
1624 /// Convert zero-based position to line column and paragraph number
1625 bool wxRichTextParagraphLayoutBox::PositionToXY(long pos
, long* x
, long* y
) const
1627 wxRichTextParagraph
* para
= GetParagraphAtPosition(pos
);
1631 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1634 wxRichTextObject
* child
= node
->GetData();
1638 node
= node
->GetNext();
1642 *x
= pos
- para
->GetRange().GetStart();
1650 /// Get the leaf object in a paragraph at this position.
1651 /// Given a line number, get the corresponding wxRichTextLine object.
1652 wxRichTextObject
* wxRichTextParagraphLayoutBox::GetLeafObjectAtPosition(long position
) const
1654 wxRichTextParagraph
* para
= GetParagraphAtPosition(position
);
1657 wxRichTextObjectList::compatibility_iterator node
= para
->GetChildren().GetFirst();
1661 wxRichTextObject
* child
= node
->GetData();
1662 if (child
->GetRange().Contains(position
))
1665 node
= node
->GetNext();
1667 if (position
== para
->GetRange().GetEnd() && para
->GetChildCount() > 0)
1668 return para
->GetChildren().GetLast()->GetData();
1673 /// Set character or paragraph text attributes: apply character styles only to immediate text nodes
1674 bool wxRichTextParagraphLayoutBox::SetStyle(const wxRichTextRange
& range
, const wxTextAttr
& style
, int flags
)
1676 bool characterStyle
= false;
1677 bool paragraphStyle
= false;
1679 if (style
.IsCharacterStyle())
1680 characterStyle
= true;
1681 if (style
.IsParagraphStyle())
1682 paragraphStyle
= true;
1684 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
1685 bool applyMinimal
= ((flags
& wxRICHTEXT_SETSTYLE_OPTIMIZE
) != 0);
1686 bool parasOnly
= ((flags
& wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY
) != 0);
1687 bool charactersOnly
= ((flags
& wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY
) != 0);
1688 bool resetExistingStyle
= ((flags
& wxRICHTEXT_SETSTYLE_RESET
) != 0);
1689 bool removeStyle
= ((flags
& wxRICHTEXT_SETSTYLE_REMOVE
) != 0);
1691 // Apply paragraph style first, if any
1692 wxTextAttr
wholeStyle(style
);
1694 if (!removeStyle
&& wholeStyle
.HasParagraphStyleName() && GetStyleSheet())
1696 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(wholeStyle
.GetParagraphStyleName());
1698 wxRichTextApplyStyle(wholeStyle
, def
->GetStyleMergedWithBase(GetStyleSheet()));
1701 // Limit the attributes to be set to the content to only character attributes.
1702 wxTextAttr
characterAttributes(wholeStyle
);
1703 characterAttributes
.SetFlags(characterAttributes
.GetFlags() & (wxTEXT_ATTR_CHARACTER
));
1705 if (!removeStyle
&& characterAttributes
.HasCharacterStyleName() && GetStyleSheet())
1707 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterAttributes
.GetCharacterStyleName());
1709 wxRichTextApplyStyle(characterAttributes
, def
->GetStyleMergedWithBase(GetStyleSheet()));
1712 // If we are associated with a control, make undoable; otherwise, apply immediately
1715 bool haveControl
= (GetRichTextCtrl() != NULL
);
1717 wxRichTextAction
* action
= NULL
;
1719 if (haveControl
&& withUndo
)
1721 action
= new wxRichTextAction(NULL
, _("Change Style"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
1722 action
->SetRange(range
);
1723 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
1726 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1729 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1730 wxASSERT (para
!= NULL
);
1732 if (para
&& para
->GetChildCount() > 0)
1734 // Stop searching if we're beyond the range of interest
1735 if (para
->GetRange().GetStart() > range
.GetEnd())
1738 if (!para
->GetRange().IsOutside(range
))
1740 // We'll be using a copy of the paragraph to make style changes,
1741 // not updating the buffer directly.
1742 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
1744 if (haveControl
&& withUndo
)
1746 newPara
= new wxRichTextParagraph(*para
);
1747 action
->GetNewParagraphs().AppendChild(newPara
);
1749 // Also store the old ones for Undo
1750 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
1755 // If we're specifying paragraphs only, then we really mean character formatting
1756 // to be included in the paragraph style
1757 if ((paragraphStyle
|| parasOnly
) && !charactersOnly
)
1761 // Removes the given style from the paragraph
1762 wxRichTextRemoveStyle(newPara
->GetAttributes(), style
);
1764 else if (resetExistingStyle
)
1765 newPara
->GetAttributes() = wholeStyle
;
1770 // Only apply attributes that will make a difference to the combined
1771 // style as seen on the display
1772 wxTextAttr
combinedAttr(para
->GetCombinedAttributes());
1773 wxRichTextApplyStyle(newPara
->GetAttributes(), wholeStyle
, & combinedAttr
);
1776 wxRichTextApplyStyle(newPara
->GetAttributes(), wholeStyle
);
1780 // When applying paragraph styles dynamically, don't change the text objects' attributes
1781 // since they will computed as needed. Only apply the character styling if it's _only_
1782 // character styling. This policy is subject to change and might be put under user control.
1784 // Hm. we might well be applying a mix of paragraph and character styles, in which
1785 // case we _do_ want to apply character styles regardless of what para styles are set.
1786 // But if we're applying a paragraph style, which has some character attributes, but
1787 // we only want the paragraphs to hold this character style, then we _don't_ want to
1788 // apply the character style. So we need to be able to choose.
1790 // if (!paragraphStyle && characterStyle && range.GetStart() != newPara->GetRange().GetEnd())
1791 if (!parasOnly
&& characterStyle
&& range
.GetStart() != newPara
->GetRange().GetEnd())
1793 wxRichTextRange
childRange(range
);
1794 childRange
.LimitTo(newPara
->GetRange());
1796 // Find the starting position and if necessary split it so
1797 // we can start applying a different style.
1798 // TODO: check that the style actually changes or is different
1799 // from style outside of range
1800 wxRichTextObject
* firstObject
wxDUMMY_INITIALIZE(NULL
);
1801 wxRichTextObject
* lastObject
wxDUMMY_INITIALIZE(NULL
);
1803 if (childRange
.GetStart() == newPara
->GetRange().GetStart())
1804 firstObject
= newPara
->GetChildren().GetFirst()->GetData();
1806 firstObject
= newPara
->SplitAt(range
.GetStart());
1808 // Increment by 1 because we're apply the style one _after_ the split point
1809 long splitPoint
= childRange
.GetEnd();
1810 if (splitPoint
!= newPara
->GetRange().GetEnd())
1814 if (splitPoint
== newPara
->GetRange().GetEnd())
1815 lastObject
= newPara
->GetChildren().GetLast()->GetData();
1817 // lastObject is set as a side-effect of splitting. It's
1818 // returned as the object before the new object.
1819 (void) newPara
->SplitAt(splitPoint
, & lastObject
);
1821 wxASSERT(firstObject
!= NULL
);
1822 wxASSERT(lastObject
!= NULL
);
1824 if (!firstObject
|| !lastObject
)
1827 wxRichTextObjectList::compatibility_iterator firstNode
= newPara
->GetChildren().Find(firstObject
);
1828 wxRichTextObjectList::compatibility_iterator lastNode
= newPara
->GetChildren().Find(lastObject
);
1830 wxASSERT(firstNode
);
1833 wxRichTextObjectList::compatibility_iterator node2
= firstNode
;
1837 wxRichTextObject
* child
= node2
->GetData();
1841 // Removes the given style from the paragraph
1842 wxRichTextRemoveStyle(child
->GetAttributes(), style
);
1844 else if (resetExistingStyle
)
1845 child
->GetAttributes() = characterAttributes
;
1850 // Only apply attributes that will make a difference to the combined
1851 // style as seen on the display
1852 wxTextAttr
combinedAttr(newPara
->GetCombinedAttributes(child
->GetAttributes()));
1853 wxRichTextApplyStyle(child
->GetAttributes(), characterAttributes
, & combinedAttr
);
1856 wxRichTextApplyStyle(child
->GetAttributes(), characterAttributes
);
1859 if (node2
== lastNode
)
1862 node2
= node2
->GetNext();
1868 node
= node
->GetNext();
1871 // Do action, or delay it until end of batch.
1872 if (haveControl
&& withUndo
)
1873 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
1878 /// Get the text attributes for this position.
1879 bool wxRichTextParagraphLayoutBox::GetStyle(long position
, wxTextAttr
& style
)
1881 return DoGetStyle(position
, style
, true);
1884 bool wxRichTextParagraphLayoutBox::GetUncombinedStyle(long position
, wxTextAttr
& style
)
1886 return DoGetStyle(position
, style
, false);
1889 /// Implementation helper for GetStyle. If combineStyles is true, combine base, paragraph and
1890 /// context attributes.
1891 bool wxRichTextParagraphLayoutBox::DoGetStyle(long position
, wxTextAttr
& style
, bool combineStyles
)
1893 wxRichTextObject
* obj
wxDUMMY_INITIALIZE(NULL
);
1895 if (style
.IsParagraphStyle())
1897 obj
= GetParagraphAtPosition(position
);
1902 // Start with the base style
1903 style
= GetAttributes();
1905 // Apply the paragraph style
1906 wxRichTextApplyStyle(style
, obj
->GetAttributes());
1909 style
= obj
->GetAttributes();
1916 obj
= GetLeafObjectAtPosition(position
);
1921 wxRichTextParagraph
* para
= wxDynamicCast(obj
->GetParent(), wxRichTextParagraph
);
1922 style
= para
? para
->GetCombinedAttributes(obj
->GetAttributes()) : obj
->GetAttributes();
1925 style
= obj
->GetAttributes();
1933 static bool wxHasStyle(long flags
, long style
)
1935 return (flags
& style
) != 0;
1938 /// Combines 'style' with 'currentStyle' for the purpose of summarising the attributes of a range of
1940 bool wxRichTextParagraphLayoutBox::CollectStyle(wxTextAttr
& currentStyle
, const wxTextAttr
& style
, long& multipleStyleAttributes
, int& multipleTextEffectAttributes
)
1942 if (style
.HasFont())
1944 if (style
.HasFontSize() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_SIZE
))
1946 if (currentStyle
.HasFontSize())
1948 if (currentStyle
.GetFontSize() != style
.GetFontSize())
1950 // Clash of style - mark as such
1951 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_SIZE
;
1952 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_SIZE
);
1957 currentStyle
.SetFontSize(style
.GetFontSize());
1961 if (style
.HasFontItalic() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_ITALIC
))
1963 if (currentStyle
.HasFontItalic())
1965 if (currentStyle
.GetFontStyle() != style
.GetFontStyle())
1967 // Clash of style - mark as such
1968 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_ITALIC
;
1969 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_ITALIC
);
1974 currentStyle
.SetFontStyle(style
.GetFontStyle());
1978 if (style
.HasFontWeight() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_WEIGHT
))
1980 if (currentStyle
.HasFontWeight())
1982 if (currentStyle
.GetFontWeight() != style
.GetFontWeight())
1984 // Clash of style - mark as such
1985 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_WEIGHT
;
1986 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_WEIGHT
);
1991 currentStyle
.SetFontWeight(style
.GetFontWeight());
1995 if (style
.HasFontFaceName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_FACE
))
1997 if (currentStyle
.HasFontFaceName())
1999 wxString
faceName1(currentStyle
.GetFontFaceName());
2000 wxString
faceName2(style
.GetFontFaceName());
2002 if (faceName1
!= faceName2
)
2004 // Clash of style - mark as such
2005 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_FACE
;
2006 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_FACE
);
2011 currentStyle
.SetFontFaceName(style
.GetFontFaceName());
2015 if (style
.HasFontUnderlined() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_UNDERLINE
))
2017 if (currentStyle
.HasFontUnderlined())
2019 if (currentStyle
.GetFontUnderlined() != style
.GetFontUnderlined())
2021 // Clash of style - mark as such
2022 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_UNDERLINE
;
2023 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_UNDERLINE
);
2028 currentStyle
.SetFontUnderlined(style
.GetFontUnderlined());
2033 if (style
.HasTextColour() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_TEXT_COLOUR
))
2035 if (currentStyle
.HasTextColour())
2037 if (currentStyle
.GetTextColour() != style
.GetTextColour())
2039 // Clash of style - mark as such
2040 multipleStyleAttributes
|= wxTEXT_ATTR_TEXT_COLOUR
;
2041 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_TEXT_COLOUR
);
2045 currentStyle
.SetTextColour(style
.GetTextColour());
2048 if (style
.HasBackgroundColour() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BACKGROUND_COLOUR
))
2050 if (currentStyle
.HasBackgroundColour())
2052 if (currentStyle
.GetBackgroundColour() != style
.GetBackgroundColour())
2054 // Clash of style - mark as such
2055 multipleStyleAttributes
|= wxTEXT_ATTR_BACKGROUND_COLOUR
;
2056 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BACKGROUND_COLOUR
);
2060 currentStyle
.SetBackgroundColour(style
.GetBackgroundColour());
2063 if (style
.HasAlignment() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_ALIGNMENT
))
2065 if (currentStyle
.HasAlignment())
2067 if (currentStyle
.GetAlignment() != style
.GetAlignment())
2069 // Clash of style - mark as such
2070 multipleStyleAttributes
|= wxTEXT_ATTR_ALIGNMENT
;
2071 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_ALIGNMENT
);
2075 currentStyle
.SetAlignment(style
.GetAlignment());
2078 if (style
.HasTabs() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_TABS
))
2080 if (currentStyle
.HasTabs())
2082 if (!wxRichTextTabsEq(currentStyle
.GetTabs(), style
.GetTabs()))
2084 // Clash of style - mark as such
2085 multipleStyleAttributes
|= wxTEXT_ATTR_TABS
;
2086 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_TABS
);
2090 currentStyle
.SetTabs(style
.GetTabs());
2093 if (style
.HasLeftIndent() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_LEFT_INDENT
))
2095 if (currentStyle
.HasLeftIndent())
2097 if (currentStyle
.GetLeftIndent() != style
.GetLeftIndent() || currentStyle
.GetLeftSubIndent() != style
.GetLeftSubIndent())
2099 // Clash of style - mark as such
2100 multipleStyleAttributes
|= wxTEXT_ATTR_LEFT_INDENT
;
2101 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LEFT_INDENT
);
2105 currentStyle
.SetLeftIndent(style
.GetLeftIndent(), style
.GetLeftSubIndent());
2108 if (style
.HasRightIndent() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_RIGHT_INDENT
))
2110 if (currentStyle
.HasRightIndent())
2112 if (currentStyle
.GetRightIndent() != style
.GetRightIndent())
2114 // Clash of style - mark as such
2115 multipleStyleAttributes
|= wxTEXT_ATTR_RIGHT_INDENT
;
2116 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_RIGHT_INDENT
);
2120 currentStyle
.SetRightIndent(style
.GetRightIndent());
2123 if (style
.HasParagraphSpacingAfter() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_PARA_SPACING_AFTER
))
2125 if (currentStyle
.HasParagraphSpacingAfter())
2127 if (currentStyle
.GetParagraphSpacingAfter() != style
.GetParagraphSpacingAfter())
2129 // Clash of style - mark as such
2130 multipleStyleAttributes
|= wxTEXT_ATTR_PARA_SPACING_AFTER
;
2131 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARA_SPACING_AFTER
);
2135 currentStyle
.SetParagraphSpacingAfter(style
.GetParagraphSpacingAfter());
2138 if (style
.HasParagraphSpacingBefore() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_PARA_SPACING_BEFORE
))
2140 if (currentStyle
.HasParagraphSpacingBefore())
2142 if (currentStyle
.GetParagraphSpacingBefore() != style
.GetParagraphSpacingBefore())
2144 // Clash of style - mark as such
2145 multipleStyleAttributes
|= wxTEXT_ATTR_PARA_SPACING_BEFORE
;
2146 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARA_SPACING_BEFORE
);
2150 currentStyle
.SetParagraphSpacingBefore(style
.GetParagraphSpacingBefore());
2153 if (style
.HasLineSpacing() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_LINE_SPACING
))
2155 if (currentStyle
.HasLineSpacing())
2157 if (currentStyle
.GetLineSpacing() != style
.GetLineSpacing())
2159 // Clash of style - mark as such
2160 multipleStyleAttributes
|= wxTEXT_ATTR_LINE_SPACING
;
2161 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LINE_SPACING
);
2165 currentStyle
.SetLineSpacing(style
.GetLineSpacing());
2168 if (style
.HasCharacterStyleName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_CHARACTER_STYLE_NAME
))
2170 if (currentStyle
.HasCharacterStyleName())
2172 if (currentStyle
.GetCharacterStyleName() != style
.GetCharacterStyleName())
2174 // Clash of style - mark as such
2175 multipleStyleAttributes
|= wxTEXT_ATTR_CHARACTER_STYLE_NAME
;
2176 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_CHARACTER_STYLE_NAME
);
2180 currentStyle
.SetCharacterStyleName(style
.GetCharacterStyleName());
2183 if (style
.HasParagraphStyleName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
))
2185 if (currentStyle
.HasParagraphStyleName())
2187 if (currentStyle
.GetParagraphStyleName() != style
.GetParagraphStyleName())
2189 // Clash of style - mark as such
2190 multipleStyleAttributes
|= wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
;
2191 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
);
2195 currentStyle
.SetParagraphStyleName(style
.GetParagraphStyleName());
2198 if (style
.HasListStyleName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_LIST_STYLE_NAME
))
2200 if (currentStyle
.HasListStyleName())
2202 if (currentStyle
.GetListStyleName() != style
.GetListStyleName())
2204 // Clash of style - mark as such
2205 multipleStyleAttributes
|= wxTEXT_ATTR_LIST_STYLE_NAME
;
2206 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LIST_STYLE_NAME
);
2210 currentStyle
.SetListStyleName(style
.GetListStyleName());
2213 if (style
.HasBulletStyle() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_STYLE
))
2215 if (currentStyle
.HasBulletStyle())
2217 if (currentStyle
.GetBulletStyle() != style
.GetBulletStyle())
2219 // Clash of style - mark as such
2220 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_STYLE
;
2221 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_STYLE
);
2225 currentStyle
.SetBulletStyle(style
.GetBulletStyle());
2228 if (style
.HasBulletNumber() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_NUMBER
))
2230 if (currentStyle
.HasBulletNumber())
2232 if (currentStyle
.GetBulletNumber() != style
.GetBulletNumber())
2234 // Clash of style - mark as such
2235 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_NUMBER
;
2236 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_NUMBER
);
2240 currentStyle
.SetBulletNumber(style
.GetBulletNumber());
2243 if (style
.HasBulletText() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_TEXT
))
2245 if (currentStyle
.HasBulletText())
2247 if (currentStyle
.GetBulletText() != style
.GetBulletText())
2249 // Clash of style - mark as such
2250 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_TEXT
;
2251 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_TEXT
);
2256 currentStyle
.SetBulletText(style
.GetBulletText());
2257 currentStyle
.SetBulletFont(style
.GetBulletFont());
2261 if (style
.HasBulletName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_NAME
))
2263 if (currentStyle
.HasBulletName())
2265 if (currentStyle
.GetBulletName() != style
.GetBulletName())
2267 // Clash of style - mark as such
2268 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_NAME
;
2269 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_NAME
);
2274 currentStyle
.SetBulletName(style
.GetBulletName());
2278 if (style
.HasURL() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_URL
))
2280 if (currentStyle
.HasURL())
2282 if (currentStyle
.GetURL() != style
.GetURL())
2284 // Clash of style - mark as such
2285 multipleStyleAttributes
|= wxTEXT_ATTR_URL
;
2286 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_URL
);
2291 currentStyle
.SetURL(style
.GetURL());
2295 if (style
.HasTextEffects() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_EFFECTS
))
2297 if (currentStyle
.HasTextEffects())
2299 // We need to find the bits in the new style that are different:
2300 // just look at those bits that are specified by the new style.
2302 int currentRelevantTextEffects
= currentStyle
.GetTextEffects() & style
.GetTextEffectFlags();
2303 int newRelevantTextEffects
= style
.GetTextEffects() & style
.GetTextEffectFlags();
2305 if (currentRelevantTextEffects
!= newRelevantTextEffects
)
2307 // Find the text effects that were different, using XOR
2308 int differentEffects
= currentRelevantTextEffects
^ newRelevantTextEffects
;
2310 // Clash of style - mark as such
2311 multipleTextEffectAttributes
|= differentEffects
;
2312 currentStyle
.SetTextEffectFlags(currentStyle
.GetTextEffectFlags() & ~differentEffects
);
2317 currentStyle
.SetTextEffects(style
.GetTextEffects());
2318 currentStyle
.SetTextEffectFlags(style
.GetTextEffectFlags());
2322 if (style
.HasOutlineLevel() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_OUTLINE_LEVEL
))
2324 if (currentStyle
.HasOutlineLevel())
2326 if (currentStyle
.GetOutlineLevel() != style
.GetOutlineLevel())
2328 // Clash of style - mark as such
2329 multipleStyleAttributes
|= wxTEXT_ATTR_OUTLINE_LEVEL
;
2330 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_OUTLINE_LEVEL
);
2334 currentStyle
.SetOutlineLevel(style
.GetOutlineLevel());
2340 /// Get the combined style for a range - if any attribute is different within the range,
2341 /// that attribute is not present within the flags.
2342 /// *** Note that this is not recursive, and so assumes that content inside a paragraph is not itself
2344 bool wxRichTextParagraphLayoutBox::GetStyleForRange(const wxRichTextRange
& range
, wxTextAttr
& style
)
2346 style
= wxTextAttr();
2348 // The attributes that aren't valid because of multiple styles within the range
2349 long multipleStyleAttributes
= 0;
2350 int multipleTextEffectAttributes
= 0;
2352 wxRichTextObjectList::compatibility_iterator node
= GetChildren().GetFirst();
2355 wxRichTextParagraph
* para
= (wxRichTextParagraph
*) node
->GetData();
2356 if (!(para
->GetRange().GetStart() > range
.GetEnd() || para
->GetRange().GetEnd() < range
.GetStart()))
2358 if (para
->GetChildren().GetCount() == 0)
2360 wxTextAttr paraStyle
= para
->GetCombinedAttributes();
2362 CollectStyle(style
, paraStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
);
2366 wxRichTextRange
paraRange(para
->GetRange());
2367 paraRange
.LimitTo(range
);
2369 // First collect paragraph attributes only
2370 wxTextAttr paraStyle
= para
->GetCombinedAttributes();
2371 paraStyle
.SetFlags(paraStyle
.GetFlags() & wxTEXT_ATTR_PARAGRAPH
);
2372 CollectStyle(style
, paraStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
);
2374 wxRichTextObjectList::compatibility_iterator childNode
= para
->GetChildren().GetFirst();
2378 wxRichTextObject
* child
= childNode
->GetData();
2379 if (!(child
->GetRange().GetStart() > range
.GetEnd() || child
->GetRange().GetEnd() < range
.GetStart()))
2381 wxTextAttr childStyle
= para
->GetCombinedAttributes(child
->GetAttributes());
2383 // Now collect character attributes only
2384 childStyle
.SetFlags(childStyle
.GetFlags() & wxTEXT_ATTR_CHARACTER
);
2386 CollectStyle(style
, childStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
);
2389 childNode
= childNode
->GetNext();
2393 node
= node
->GetNext();
2398 /// Set default style
2399 bool wxRichTextParagraphLayoutBox::SetDefaultStyle(const wxTextAttr
& style
)
2401 m_defaultAttributes
= style
;
2405 /// Test if this whole range has character attributes of the specified kind. If any
2406 /// of the attributes are different within the range, the test fails. You
2407 /// can use this to implement, for example, bold button updating. style must have
2408 /// flags indicating which attributes are of interest.
2409 bool wxRichTextParagraphLayoutBox::HasCharacterAttributes(const wxRichTextRange
& range
, const wxTextAttr
& style
) const
2412 int matchingCount
= 0;
2414 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2417 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2418 wxASSERT (para
!= NULL
);
2422 // Stop searching if we're beyond the range of interest
2423 if (para
->GetRange().GetStart() > range
.GetEnd())
2424 return foundCount
== matchingCount
;
2426 if (!para
->GetRange().IsOutside(range
))
2428 wxRichTextObjectList::compatibility_iterator node2
= para
->GetChildren().GetFirst();
2432 wxRichTextObject
* child
= node2
->GetData();
2433 if (!child
->GetRange().IsOutside(range
) && child
->IsKindOf(CLASSINFO(wxRichTextPlainText
)))
2436 wxTextAttr textAttr
= para
->GetCombinedAttributes(child
->GetAttributes());
2438 if (wxTextAttrEqPartial(textAttr
, style
, style
.GetFlags()))
2442 node2
= node2
->GetNext();
2447 node
= node
->GetNext();
2450 return foundCount
== matchingCount
;
2453 /// Test if this whole range has paragraph attributes of the specified kind. If any
2454 /// of the attributes are different within the range, the test fails. You
2455 /// can use this to implement, for example, centering button updating. style must have
2456 /// flags indicating which attributes are of interest.
2457 bool wxRichTextParagraphLayoutBox::HasParagraphAttributes(const wxRichTextRange
& range
, const wxTextAttr
& style
) const
2460 int matchingCount
= 0;
2462 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2465 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2466 wxASSERT (para
!= NULL
);
2470 // Stop searching if we're beyond the range of interest
2471 if (para
->GetRange().GetStart() > range
.GetEnd())
2472 return foundCount
== matchingCount
;
2474 if (!para
->GetRange().IsOutside(range
))
2476 wxTextAttr textAttr
= GetAttributes();
2477 // Apply the paragraph style
2478 wxRichTextApplyStyle(textAttr
, para
->GetAttributes());
2481 if (wxTextAttrEqPartial(textAttr
, style
, style
.GetFlags()))
2486 node
= node
->GetNext();
2488 return foundCount
== matchingCount
;
2491 void wxRichTextParagraphLayoutBox::Clear()
2496 void wxRichTextParagraphLayoutBox::Reset()
2500 wxRichTextBuffer
* buffer
= wxDynamicCast(this, wxRichTextBuffer
);
2501 if (buffer
&& GetRichTextCtrl())
2503 wxRichTextEvent
event(wxEVT_COMMAND_RICHTEXT_BUFFER_RESET
, GetRichTextCtrl()->GetId());
2504 event
.SetEventObject(GetRichTextCtrl());
2506 buffer
->SendEvent(event
, true);
2509 AddParagraph(wxEmptyString
);
2511 Invalidate(wxRICHTEXT_ALL
);
2514 /// Invalidate the buffer. With no argument, invalidates whole buffer.
2515 void wxRichTextParagraphLayoutBox::Invalidate(const wxRichTextRange
& invalidRange
)
2519 if (invalidRange
== wxRICHTEXT_ALL
)
2521 m_invalidRange
= wxRICHTEXT_ALL
;
2525 // Already invalidating everything
2526 if (m_invalidRange
== wxRICHTEXT_ALL
)
2529 if ((invalidRange
.GetStart() < m_invalidRange
.GetStart()) || m_invalidRange
.GetStart() == -1)
2530 m_invalidRange
.SetStart(invalidRange
.GetStart());
2531 if (invalidRange
.GetEnd() > m_invalidRange
.GetEnd())
2532 m_invalidRange
.SetEnd(invalidRange
.GetEnd());
2535 /// Get invalid range, rounding to entire paragraphs if argument is true.
2536 wxRichTextRange
wxRichTextParagraphLayoutBox::GetInvalidRange(bool wholeParagraphs
) const
2538 if (m_invalidRange
== wxRICHTEXT_ALL
|| m_invalidRange
== wxRICHTEXT_NONE
)
2539 return m_invalidRange
;
2541 wxRichTextRange range
= m_invalidRange
;
2543 if (wholeParagraphs
)
2545 wxRichTextParagraph
* para1
= GetParagraphAtPosition(range
.GetStart());
2546 wxRichTextParagraph
* para2
= GetParagraphAtPosition(range
.GetEnd());
2548 range
.SetStart(para1
->GetRange().GetStart());
2550 range
.SetEnd(para2
->GetRange().GetEnd());
2555 /// Apply the style sheet to the buffer, for example if the styles have changed.
2556 bool wxRichTextParagraphLayoutBox::ApplyStyleSheet(wxRichTextStyleSheet
* styleSheet
)
2558 wxASSERT(styleSheet
!= NULL
);
2564 wxRichTextAttr
attr(GetBasicStyle());
2565 if (GetBasicStyle().HasParagraphStyleName())
2567 wxRichTextParagraphStyleDefinition
* paraDef
= styleSheet
->FindParagraphStyle(GetBasicStyle().GetParagraphStyleName());
2570 attr
.Apply(paraDef
->GetStyleMergedWithBase(styleSheet
));
2571 SetBasicStyle(attr
);
2576 if (GetBasicStyle().HasCharacterStyleName())
2578 wxRichTextCharacterStyleDefinition
* charDef
= styleSheet
->FindCharacterStyle(GetBasicStyle().GetCharacterStyleName());
2581 attr
.Apply(charDef
->GetStyleMergedWithBase(styleSheet
));
2582 SetBasicStyle(attr
);
2587 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2590 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2591 wxASSERT (para
!= NULL
);
2595 // Combine paragraph and list styles. If there is a list style in the original attributes,
2596 // the current indentation overrides anything else and is used to find the item indentation.
2597 // Also, for applying paragraph styles, consider having 2 modes: (1) we merge with what we have,
2598 // thereby taking into account all user changes, (2) reset the style completely (except for indentation/list
2599 // exception as above).
2600 // Problem: when changing from one list style to another, there's a danger that the level info will get lost.
2601 // So when changing a list style interactively, could retrieve level based on current style, then
2602 // set appropriate indent and apply new style.
2604 if (!para
->GetAttributes().GetParagraphStyleName().IsEmpty() && !para
->GetAttributes().GetListStyleName().IsEmpty())
2606 int currentIndent
= para
->GetAttributes().GetLeftIndent();
2608 wxRichTextParagraphStyleDefinition
* paraDef
= styleSheet
->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
2609 wxRichTextListStyleDefinition
* listDef
= styleSheet
->FindListStyle(para
->GetAttributes().GetListStyleName());
2610 if (paraDef
&& !listDef
)
2612 para
->GetAttributes() = paraDef
->GetStyleMergedWithBase(styleSheet
);
2615 else if (listDef
&& !paraDef
)
2617 // Set overall style defined for the list style definition
2618 para
->GetAttributes() = listDef
->GetStyleMergedWithBase(styleSheet
);
2620 // Apply the style for this level
2621 wxRichTextApplyStyle(para
->GetAttributes(), * listDef
->GetLevelAttributes(listDef
->FindLevelForIndent(currentIndent
)));
2624 else if (listDef
&& paraDef
)
2626 // Combines overall list style, style for level, and paragraph style
2627 para
->GetAttributes() = listDef
->CombineWithParagraphStyle(currentIndent
, paraDef
->GetStyleMergedWithBase(styleSheet
));
2631 else if (para
->GetAttributes().GetParagraphStyleName().IsEmpty() && !para
->GetAttributes().GetListStyleName().IsEmpty())
2633 int currentIndent
= para
->GetAttributes().GetLeftIndent();
2635 wxRichTextListStyleDefinition
* listDef
= styleSheet
->FindListStyle(para
->GetAttributes().GetListStyleName());
2637 // Overall list definition style
2638 para
->GetAttributes() = listDef
->GetStyleMergedWithBase(styleSheet
);
2640 // Style for this level
2641 wxRichTextApplyStyle(para
->GetAttributes(), * listDef
->GetLevelAttributes(listDef
->FindLevelForIndent(currentIndent
)));
2645 else if (!para
->GetAttributes().GetParagraphStyleName().IsEmpty() && para
->GetAttributes().GetListStyleName().IsEmpty())
2647 wxRichTextParagraphStyleDefinition
* def
= styleSheet
->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
2650 para
->GetAttributes() = def
->GetStyleMergedWithBase(styleSheet
);
2656 node
= node
->GetNext();
2658 return foundCount
!= 0;
2662 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2664 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2666 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
2667 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2668 bool specifyLevel
= ((flags
& wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL
) != 0);
2669 bool renumber
= ((flags
& wxRICHTEXT_SETSTYLE_RENUMBER
) != 0);
2671 // Current number, if numbering
2674 wxASSERT (!specifyLevel
|| (specifyLevel
&& (specifiedLevel
>= 0)));
2676 // If we are associated with a control, make undoable; otherwise, apply immediately
2679 bool haveControl
= (GetRichTextCtrl() != NULL
);
2681 wxRichTextAction
* action
= NULL
;
2683 if (haveControl
&& withUndo
)
2685 action
= new wxRichTextAction(NULL
, _("Change List Style"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2686 action
->SetRange(range
);
2687 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2690 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2693 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2694 wxASSERT (para
!= NULL
);
2696 if (para
&& para
->GetChildCount() > 0)
2698 // Stop searching if we're beyond the range of interest
2699 if (para
->GetRange().GetStart() > range
.GetEnd())
2702 if (!para
->GetRange().IsOutside(range
))
2704 // We'll be using a copy of the paragraph to make style changes,
2705 // not updating the buffer directly.
2706 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
2708 if (haveControl
&& withUndo
)
2710 newPara
= new wxRichTextParagraph(*para
);
2711 action
->GetNewParagraphs().AppendChild(newPara
);
2713 // Also store the old ones for Undo
2714 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
2721 int thisIndent
= newPara
->GetAttributes().GetLeftIndent();
2722 int thisLevel
= specifyLevel
? specifiedLevel
: def
->FindLevelForIndent(thisIndent
);
2724 // How is numbering going to work?
2725 // If we are renumbering, or numbering for the first time, we need to keep
2726 // track of the number for each level. But we might be simply applying a different
2728 // In Word, applying a style to several paragraphs, even if at different levels,
2729 // reverts the level back to the same one. So we could do the same here.
2730 // Renumbering will need to be done when we promote/demote a paragraph.
2732 // Apply the overall list style, and item style for this level
2733 wxTextAttr
listStyle(def
->GetCombinedStyleForLevel(thisLevel
, styleSheet
));
2734 wxRichTextApplyStyle(newPara
->GetAttributes(), listStyle
);
2736 // Now we need to do numbering
2739 newPara
->GetAttributes().SetBulletNumber(n
);
2744 else if (!newPara
->GetAttributes().GetListStyleName().IsEmpty())
2746 // if def is NULL, remove list style, applying any associated paragraph style
2747 // to restore the attributes
2749 newPara
->GetAttributes().SetListStyleName(wxEmptyString
);
2750 newPara
->GetAttributes().SetLeftIndent(0, 0);
2751 newPara
->GetAttributes().SetBulletText(wxEmptyString
);
2753 // Eliminate the main list-related attributes
2754 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
);
2756 if (styleSheet
&& !newPara
->GetAttributes().GetParagraphStyleName().IsEmpty())
2758 wxRichTextParagraphStyleDefinition
* def
= styleSheet
->FindParagraphStyle(newPara
->GetAttributes().GetParagraphStyleName());
2761 newPara
->GetAttributes() = def
->GetStyleMergedWithBase(styleSheet
);
2768 node
= node
->GetNext();
2771 // Do action, or delay it until end of batch.
2772 if (haveControl
&& withUndo
)
2773 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
2778 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int startFrom
, int specifiedLevel
)
2780 if (GetStyleSheet())
2782 wxRichTextListStyleDefinition
* def
= GetStyleSheet()->FindListStyle(defName
);
2784 return SetListStyle(range
, def
, flags
, startFrom
, specifiedLevel
);
2789 /// Clear list for given range
2790 bool wxRichTextParagraphLayoutBox::ClearListStyle(const wxRichTextRange
& range
, int flags
)
2792 return SetListStyle(range
, NULL
, flags
);
2795 /// Number/renumber any list elements in the given range
2796 bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2798 return DoNumberList(range
, range
, 0, def
, flags
, startFrom
, specifiedLevel
);
2801 /// Number/renumber any list elements in the given range. Also do promotion or demotion of items, if specified
2802 bool wxRichTextParagraphLayoutBox::DoNumberList(const wxRichTextRange
& range
, const wxRichTextRange
& promotionRange
, int promoteBy
,
2803 wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2805 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2807 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
2808 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2810 bool specifyLevel
= ((flags
& wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL
) != 0);
2813 bool renumber
= ((flags
& wxRICHTEXT_SETSTYLE_RENUMBER
) != 0);
2815 // Max number of levels
2816 const int maxLevels
= 10;
2818 // The level we're looking at now
2819 int currentLevel
= -1;
2821 // The item number for each level
2822 int levels
[maxLevels
];
2825 // Reset all numbering
2826 for (i
= 0; i
< maxLevels
; i
++)
2828 if (startFrom
!= -1)
2829 levels
[i
] = startFrom
-1;
2830 else if (renumber
) // start again
2833 levels
[i
] = -1; // start from the number we found, if any
2836 wxASSERT(!specifyLevel
|| (specifyLevel
&& (specifiedLevel
>= 0)));
2838 // If we are associated with a control, make undoable; otherwise, apply immediately
2841 bool haveControl
= (GetRichTextCtrl() != NULL
);
2843 wxRichTextAction
* action
= NULL
;
2845 if (haveControl
&& withUndo
)
2847 action
= new wxRichTextAction(NULL
, _("Renumber List"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2848 action
->SetRange(range
);
2849 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2852 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2855 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2856 wxASSERT (para
!= NULL
);
2858 if (para
&& para
->GetChildCount() > 0)
2860 // Stop searching if we're beyond the range of interest
2861 if (para
->GetRange().GetStart() > range
.GetEnd())
2864 if (!para
->GetRange().IsOutside(range
))
2866 // We'll be using a copy of the paragraph to make style changes,
2867 // not updating the buffer directly.
2868 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
2870 if (haveControl
&& withUndo
)
2872 newPara
= new wxRichTextParagraph(*para
);
2873 action
->GetNewParagraphs().AppendChild(newPara
);
2875 // Also store the old ones for Undo
2876 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
2881 wxRichTextListStyleDefinition
* defToUse
= def
;
2884 if (styleSheet
&& !newPara
->GetAttributes().GetListStyleName().IsEmpty())
2885 defToUse
= styleSheet
->FindListStyle(newPara
->GetAttributes().GetListStyleName());
2890 int thisIndent
= newPara
->GetAttributes().GetLeftIndent();
2891 int thisLevel
= defToUse
->FindLevelForIndent(thisIndent
);
2893 // If we've specified a level to apply to all, change the level.
2894 if (specifiedLevel
!= -1)
2895 thisLevel
= specifiedLevel
;
2897 // Do promotion if specified
2898 if ((promoteBy
!= 0) && !para
->GetRange().IsOutside(promotionRange
))
2900 thisLevel
= thisLevel
- promoteBy
;
2907 // Apply the overall list style, and item style for this level
2908 wxTextAttr
listStyle(defToUse
->GetCombinedStyleForLevel(thisLevel
, styleSheet
));
2909 wxRichTextApplyStyle(newPara
->GetAttributes(), listStyle
);
2911 // OK, we've (re)applied the style, now let's get the numbering right.
2913 if (currentLevel
== -1)
2914 currentLevel
= thisLevel
;
2916 // Same level as before, do nothing except increment level's number afterwards
2917 if (currentLevel
== thisLevel
)
2920 // A deeper level: start renumbering all levels after current level
2921 else if (thisLevel
> currentLevel
)
2923 for (i
= currentLevel
+1; i
<= thisLevel
; i
++)
2927 currentLevel
= thisLevel
;
2929 else if (thisLevel
< currentLevel
)
2931 currentLevel
= thisLevel
;
2934 // Use the current numbering if -1 and we have a bullet number already
2935 if (levels
[currentLevel
] == -1)
2937 if (newPara
->GetAttributes().HasBulletNumber())
2938 levels
[currentLevel
] = newPara
->GetAttributes().GetBulletNumber();
2940 levels
[currentLevel
] = 1;
2944 levels
[currentLevel
] ++;
2947 newPara
->GetAttributes().SetBulletNumber(levels
[currentLevel
]);
2949 // Create the bullet text if an outline list
2950 if (listStyle
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
)
2953 for (i
= 0; i
<= currentLevel
; i
++)
2955 if (!text
.IsEmpty())
2957 text
+= wxString::Format(wxT("%d"), levels
[i
]);
2959 newPara
->GetAttributes().SetBulletText(text
);
2965 node
= node
->GetNext();
2968 // Do action, or delay it until end of batch.
2969 if (haveControl
&& withUndo
)
2970 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
2975 bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int startFrom
, int specifiedLevel
)
2977 if (GetStyleSheet())
2979 wxRichTextListStyleDefinition
* def
= NULL
;
2980 if (!defName
.IsEmpty())
2981 def
= GetStyleSheet()->FindListStyle(defName
);
2982 return NumberList(range
, def
, flags
, startFrom
, specifiedLevel
);
2987 /// Promote the list items within the given range. promoteBy can be a positive or negative number, e.g. 1 or -1
2988 bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy
, const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int specifiedLevel
)
2991 // One strategy is to first work out the range within which renumbering must occur. Then could pass these two ranges
2992 // to NumberList with a flag indicating promotion is required within one of the ranges.
2993 // Find first and last paragraphs in range. Then for first, calculate new indentation and look back until we find
2994 // a paragraph that either has no list style, or has one that is different or whose indentation is less.
2995 // We start renumbering from the para after that different para we found. We specify that the numbering of that
2996 // list position will start from 1.
2997 // Similarly, we look after the last para in the promote range for an indentation that is less (or no list style).
2998 // We can end the renumbering at this point.
3000 // For now, only renumber within the promotion range.
3002 return DoNumberList(range
, range
, promoteBy
, def
, flags
, 1, specifiedLevel
);
3005 bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy
, const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int specifiedLevel
)
3007 if (GetStyleSheet())
3009 wxRichTextListStyleDefinition
* def
= NULL
;
3010 if (!defName
.IsEmpty())
3011 def
= GetStyleSheet()->FindListStyle(defName
);
3012 return PromoteList(promoteBy
, range
, def
, flags
, specifiedLevel
);
3017 /// Fills in the attributes for numbering a paragraph after previousParagraph. It also finds the
3018 /// position of the paragraph that it had to start looking from.
3019 bool wxRichTextParagraphLayoutBox::FindNextParagraphNumber(wxRichTextParagraph
* previousParagraph
, wxTextAttr
& attr
) const
3021 if (!previousParagraph
->GetAttributes().HasFlag(wxTEXT_ATTR_BULLET_STYLE
) || previousParagraph
->GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE
)
3024 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
3025 if (styleSheet
&& !previousParagraph
->GetAttributes().GetListStyleName().IsEmpty())
3027 wxRichTextListStyleDefinition
* def
= styleSheet
->FindListStyle(previousParagraph
->GetAttributes().GetListStyleName());
3030 // int thisIndent = previousParagraph->GetAttributes().GetLeftIndent();
3031 // int thisLevel = def->FindLevelForIndent(thisIndent);
3033 bool isOutline
= (previousParagraph
->GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
) != 0;
3035 attr
.SetFlags(previousParagraph
->GetAttributes().GetFlags() & (wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_BULLET_NUMBER
|wxTEXT_ATTR_BULLET_TEXT
|wxTEXT_ATTR_BULLET_NAME
));
3036 if (previousParagraph
->GetAttributes().HasBulletName())
3037 attr
.SetBulletName(previousParagraph
->GetAttributes().GetBulletName());
3038 attr
.SetBulletStyle(previousParagraph
->GetAttributes().GetBulletStyle());
3039 attr
.SetListStyleName(previousParagraph
->GetAttributes().GetListStyleName());
3041 int nextNumber
= previousParagraph
->GetAttributes().GetBulletNumber() + 1;
3042 attr
.SetBulletNumber(nextNumber
);
3046 wxString text
= previousParagraph
->GetAttributes().GetBulletText();
3047 if (!text
.IsEmpty())
3049 int pos
= text
.Find(wxT('.'), true);
3050 if (pos
!= wxNOT_FOUND
)
3052 text
= text
.Mid(0, text
.Length() - pos
- 1);
3055 text
= wxEmptyString
;
3056 if (!text
.IsEmpty())
3058 text
+= wxString::Format(wxT("%d"), nextNumber
);
3059 attr
.SetBulletText(text
);
3073 * wxRichTextParagraph
3074 * This object represents a single paragraph (or in a straight text editor, a line).
3077 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraph
, wxRichTextBox
)
3079 wxArrayInt
wxRichTextParagraph::sm_defaultTabs
;
3081 wxRichTextParagraph::wxRichTextParagraph(wxRichTextObject
* parent
, wxTextAttr
* style
):
3082 wxRichTextBox(parent
)
3085 SetAttributes(*style
);
3088 wxRichTextParagraph::wxRichTextParagraph(const wxString
& text
, wxRichTextObject
* parent
, wxTextAttr
* paraStyle
, wxTextAttr
* charStyle
):
3089 wxRichTextBox(parent
)
3092 SetAttributes(*paraStyle
);
3094 AppendChild(new wxRichTextPlainText(text
, this, charStyle
));
3097 wxRichTextParagraph::~wxRichTextParagraph()
3103 bool wxRichTextParagraph::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& WXUNUSED(rect
), int WXUNUSED(descent
), int style
)
3105 wxTextAttr attr
= GetCombinedAttributes();
3107 // Draw the bullet, if any
3108 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3110 if (attr
.GetLeftSubIndent() != 0)
3112 int spaceBeforePara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingBefore());
3113 int leftIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftIndent());
3115 wxTextAttr
bulletAttr(GetCombinedAttributes());
3117 // Combine with the font of the first piece of content, if one is specified
3118 if (GetChildren().GetCount() > 0)
3120 wxRichTextObject
* firstObj
= (wxRichTextObject
*) GetChildren().GetFirst()->GetData();
3121 if (firstObj
->GetAttributes().HasFont())
3123 wxRichTextApplyStyle(bulletAttr
, firstObj
->GetAttributes());
3127 // Get line height from first line, if any
3128 wxRichTextLine
* line
= m_cachedLines
.GetFirst() ? (wxRichTextLine
* ) m_cachedLines
.GetFirst()->GetData() : (wxRichTextLine
*) NULL
;
3131 int lineHeight
wxDUMMY_INITIALIZE(0);
3134 lineHeight
= line
->GetSize().y
;
3135 linePos
= line
->GetPosition() + GetPosition();
3140 if (bulletAttr
.HasFont() && GetBuffer())
3141 font
= GetBuffer()->GetFontTable().FindFont(bulletAttr
);
3143 font
= (*wxNORMAL_FONT
);
3145 wxCheckSetFont(dc
, font
);
3147 lineHeight
= dc
.GetCharHeight();
3148 linePos
= GetPosition();
3149 linePos
.y
+= spaceBeforePara
;
3152 wxRect
bulletRect(GetPosition().x
+ leftIndent
, linePos
.y
, linePos
.x
- (GetPosition().x
+ leftIndent
), lineHeight
);
3154 if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP
)
3156 if (wxRichTextBuffer::GetRenderer())
3157 wxRichTextBuffer::GetRenderer()->DrawBitmapBullet(this, dc
, bulletAttr
, bulletRect
);
3159 else if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_STANDARD
)
3161 if (wxRichTextBuffer::GetRenderer())
3162 wxRichTextBuffer::GetRenderer()->DrawStandardBullet(this, dc
, bulletAttr
, bulletRect
);
3166 wxString bulletText
= GetBulletText();
3168 if (!bulletText
.empty() && wxRichTextBuffer::GetRenderer())
3169 wxRichTextBuffer::GetRenderer()->DrawTextBullet(this, dc
, bulletAttr
, bulletRect
, bulletText
);
3174 // Draw the range for each line, one object at a time.
3176 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3179 wxRichTextLine
* line
= node
->GetData();
3180 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3182 int maxDescent
= line
->GetDescent();
3184 // Lines are specified relative to the paragraph
3186 wxPoint linePosition
= line
->GetPosition() + GetPosition();
3187 wxPoint objectPosition
= linePosition
;
3189 // Loop through objects until we get to the one within range
3190 wxRichTextObjectList::compatibility_iterator node2
= m_children
.GetFirst();
3193 wxRichTextObject
* child
= node2
->GetData();
3195 if (!child
->GetRange().IsOutside(lineRange
) && !lineRange
.IsOutside(range
))
3197 // Draw this part of the line at the correct position
3198 wxRichTextRange
objectRange(child
->GetRange());
3199 objectRange
.LimitTo(lineRange
);
3203 child
->GetRangeSize(objectRange
, objectSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, objectPosition
);
3205 // Use the child object's width, but the whole line's height
3206 wxRect
childRect(objectPosition
, wxSize(objectSize
.x
, line
->GetSize().y
));
3207 child
->Draw(dc
, objectRange
, selectionRange
, childRect
, maxDescent
, style
);
3209 objectPosition
.x
+= objectSize
.x
;
3211 else if (child
->GetRange().GetStart() > lineRange
.GetEnd())
3212 // Can break out of inner loop now since we've passed this line's range
3215 node2
= node2
->GetNext();
3218 node
= node
->GetNext();
3224 /// Lay the item out
3225 bool wxRichTextParagraph::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
3227 wxTextAttr attr
= GetCombinedAttributes();
3231 // Increase the size of the paragraph due to spacing
3232 int spaceBeforePara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingBefore());
3233 int spaceAfterPara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingAfter());
3234 int leftIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftIndent());
3235 int leftSubIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftSubIndent());
3236 int rightIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetRightIndent());
3238 int lineSpacing
= 0;
3240 // Let's assume line spacing of 10 is normal, 15 is 1.5, 20 is 2, etc.
3241 if (attr
.GetLineSpacing() != 10 && GetBuffer())
3243 wxFont
font(GetBuffer()->GetFontTable().FindFont(attr
));
3244 wxCheckSetFont(dc
, font
);
3245 lineSpacing
= (ConvertTenthsMMToPixels(dc
, dc
.GetCharHeight()) * attr
.GetLineSpacing())/10;
3248 // Available space for text on each line differs.
3249 int availableTextSpaceFirstLine
= rect
.GetWidth() - leftIndent
- rightIndent
;
3251 // Bullets start the text at the same position as subsequent lines
3252 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3253 availableTextSpaceFirstLine
-= leftSubIndent
;
3255 int availableTextSpaceSubsequentLines
= rect
.GetWidth() - leftIndent
- rightIndent
- leftSubIndent
;
3257 // Start position for each line relative to the paragraph
3258 int startPositionFirstLine
= leftIndent
;
3259 int startPositionSubsequentLines
= leftIndent
+ leftSubIndent
;
3261 // If we have a bullet in this paragraph, the start position for the first line's text
3262 // is actually leftIndent + leftSubIndent.
3263 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3264 startPositionFirstLine
= startPositionSubsequentLines
;
3266 long lastEndPos
= GetRange().GetStart()-1;
3267 long lastCompletedEndPos
= lastEndPos
;
3269 int currentWidth
= 0;
3270 SetPosition(rect
.GetPosition());
3272 wxPoint
currentPosition(0, spaceBeforePara
); // We will calculate lines relative to paragraph
3279 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3282 wxRichTextObject
* child
= node
->GetData();
3284 child
->SetCachedSize(wxDefaultSize
);
3285 child
->Layout(dc
, rect
, style
);
3287 node
= node
->GetNext();
3290 #if wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
3291 wxArrayInt partialExtents
;
3296 // This calculates the partial text extents
3297 GetRangeSize(GetRange(), paraSize
, paraDescent
, dc
, wxRICHTEXT_UNFORMATTED
, wxPoint(0,0), & partialExtents
);
3302 // We may need to go back to a previous child, in which case create the new line,
3303 // find the child corresponding to the start position of the string, and
3306 node
= m_children
.GetFirst();
3309 wxRichTextObject
* child
= node
->GetData();
3311 // If this is e.g. a composite text box, it will need to be laid out itself.
3312 // But if just a text fragment or image, for example, this will
3313 // do nothing. NB: won't we need to set the position after layout?
3314 // since for example if position is dependent on vertical line size, we
3315 // can't tell the position until the size is determined. So possibly introduce
3316 // another layout phase.
3318 // Available width depends on whether we're on the first or subsequent lines
3319 int availableSpaceForText
= (lineCount
== 0 ? availableTextSpaceFirstLine
: availableTextSpaceSubsequentLines
);
3321 currentPosition
.x
= (lineCount
== 0 ? startPositionFirstLine
: startPositionSubsequentLines
);
3323 // We may only be looking at part of a child, if we searched back for wrapping
3324 // and found a suitable point some way into the child. So get the size for the fragment
3327 long nextBreakPos
= GetFirstLineBreakPosition(lastEndPos
+1);
3328 long lastPosToUse
= child
->GetRange().GetEnd();
3329 bool lineBreakInThisObject
= (nextBreakPos
> -1 && nextBreakPos
<= child
->GetRange().GetEnd());
3331 if (lineBreakInThisObject
)
3332 lastPosToUse
= nextBreakPos
;
3335 int childDescent
= 0;
3337 if ((nextBreakPos
== -1) && (lastEndPos
== child
->GetRange().GetStart() - 1)) // i.e. we want to get the whole thing
3339 childSize
= child
->GetCachedSize();
3340 childDescent
= child
->GetDescent();
3343 GetRangeSize(wxRichTextRange(lastEndPos
+1, lastPosToUse
), childSize
, childDescent
, dc
, wxRICHTEXT_UNFORMATTED
, rect
.GetPosition());
3346 // 1) There was a line break BEFORE the natural break
3347 // 2) There was a line break AFTER the natural break
3348 // 3) The child still fits (carry on)
3350 if ((lineBreakInThisObject
&& (childSize
.x
+ currentWidth
<= availableSpaceForText
)) ||
3351 (childSize
.x
+ currentWidth
> availableSpaceForText
))
3353 long wrapPosition
= 0;
3355 // Find a place to wrap. This may walk back to previous children,
3356 // for example if a word spans several objects.
3357 if (!FindWrapPosition(wxRichTextRange(lastCompletedEndPos
+1, child
->GetRange().GetEnd()), dc
, availableSpaceForText
, wrapPosition
, & partialExtents
))
3359 // If the function failed, just cut it off at the end of this child.
3360 wrapPosition
= child
->GetRange().GetEnd();
3363 // FindWrapPosition can still return a value that will put us in an endless wrapping loop
3364 if (wrapPosition
<= lastCompletedEndPos
)
3365 wrapPosition
= wxMax(lastCompletedEndPos
+1,child
->GetRange().GetEnd());
3367 // wxLogDebug(wxT("Split at %ld"), wrapPosition);
3369 // Let's find the actual size of the current line now
3371 wxRichTextRange
actualRange(lastCompletedEndPos
+1, wrapPosition
);
3372 GetRangeSize(actualRange
, actualSize
, childDescent
, dc
, wxRICHTEXT_UNFORMATTED
);
3373 currentWidth
= actualSize
.x
;
3374 lineHeight
= wxMax(lineHeight
, actualSize
.y
);
3375 maxDescent
= wxMax(childDescent
, maxDescent
);
3378 wxRichTextLine
* line
= AllocateLine(lineCount
);
3380 // Set relative range so we won't have to change line ranges when paragraphs are moved
3381 line
->SetRange(wxRichTextRange(actualRange
.GetStart() - GetRange().GetStart(), actualRange
.GetEnd() - GetRange().GetStart()));
3382 line
->SetPosition(currentPosition
);
3383 line
->SetSize(wxSize(currentWidth
, lineHeight
));
3384 line
->SetDescent(maxDescent
);
3386 // Now move down a line. TODO: add margins, spacing
3387 currentPosition
.y
+= lineHeight
;
3388 currentPosition
.y
+= lineSpacing
;
3391 maxWidth
= wxMax(maxWidth
, currentWidth
);
3395 // TODO: account for zero-length objects, such as fields
3396 wxASSERT(wrapPosition
> lastCompletedEndPos
);
3398 lastEndPos
= wrapPosition
;
3399 lastCompletedEndPos
= lastEndPos
;
3403 // May need to set the node back to a previous one, due to searching back in wrapping
3404 wxRichTextObject
* childAfterWrapPosition
= FindObjectAtPosition(wrapPosition
+1);
3405 if (childAfterWrapPosition
)
3406 node
= m_children
.Find(childAfterWrapPosition
);
3408 node
= node
->GetNext();
3412 // We still fit, so don't add a line, and keep going
3413 currentWidth
+= childSize
.x
;
3414 lineHeight
= wxMax(lineHeight
, childSize
.y
);
3415 maxDescent
= wxMax(childDescent
, maxDescent
);
3417 maxWidth
= wxMax(maxWidth
, currentWidth
);
3418 lastEndPos
= child
->GetRange().GetEnd();
3420 node
= node
->GetNext();
3424 // Add the last line - it's the current pos -> last para pos
3425 // Substract -1 because the last position is always the end-paragraph position.
3426 if (lastCompletedEndPos
<= GetRange().GetEnd()-1)
3428 currentPosition
.x
= (lineCount
== 0 ? startPositionFirstLine
: startPositionSubsequentLines
);
3430 wxRichTextLine
* line
= AllocateLine(lineCount
);
3432 wxRichTextRange
actualRange(lastCompletedEndPos
+1, GetRange().GetEnd()-1);
3434 // Set relative range so we won't have to change line ranges when paragraphs are moved
3435 line
->SetRange(wxRichTextRange(actualRange
.GetStart() - GetRange().GetStart(), actualRange
.GetEnd() - GetRange().GetStart()));
3437 line
->SetPosition(currentPosition
);
3439 if (lineHeight
== 0 && GetBuffer())
3441 wxFont
font(GetBuffer()->GetFontTable().FindFont(attr
));
3442 wxCheckSetFont(dc
, font
);
3443 lineHeight
= dc
.GetCharHeight();
3445 if (maxDescent
== 0)
3448 dc
.GetTextExtent(wxT("X"), & w
, &h
, & maxDescent
);
3451 line
->SetSize(wxSize(currentWidth
, lineHeight
));
3452 line
->SetDescent(maxDescent
);
3453 currentPosition
.y
+= lineHeight
;
3454 currentPosition
.y
+= lineSpacing
;
3458 // Remove remaining unused line objects, if any
3459 ClearUnusedLines(lineCount
);
3461 // Apply styles to wrapped lines
3462 ApplyParagraphStyle(attr
, rect
);
3464 SetCachedSize(wxSize(maxWidth
, currentPosition
.y
+ spaceBeforePara
+ spaceAfterPara
));
3471 /// Apply paragraph styles, such as centering, to wrapped lines
3472 void wxRichTextParagraph::ApplyParagraphStyle(const wxTextAttr
& attr
, const wxRect
& rect
)
3474 if (!attr
.HasAlignment())
3477 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3480 wxRichTextLine
* line
= node
->GetData();
3482 wxPoint pos
= line
->GetPosition();
3483 wxSize size
= line
->GetSize();
3485 // centering, right-justification
3486 if (attr
.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_CENTRE
)
3488 pos
.x
= (rect
.GetWidth() - size
.x
)/2 + pos
.x
;
3489 line
->SetPosition(pos
);
3491 else if (attr
.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_RIGHT
)
3493 pos
.x
= pos
.x
+ rect
.GetWidth() - size
.x
;
3494 line
->SetPosition(pos
);
3497 node
= node
->GetNext();
3501 /// Insert text at the given position
3502 bool wxRichTextParagraph::InsertText(long pos
, const wxString
& text
)
3504 wxRichTextObject
* childToUse
= NULL
;
3505 wxRichTextObjectList::compatibility_iterator nodeToUse
= wxRichTextObjectList::compatibility_iterator();
3507 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3510 wxRichTextObject
* child
= node
->GetData();
3511 if (child
->GetRange().Contains(pos
) && child
->GetRange().GetLength() > 0)
3518 node
= node
->GetNext();
3523 wxRichTextPlainText
* textObject
= wxDynamicCast(childToUse
, wxRichTextPlainText
);
3526 int posInString
= pos
- textObject
->GetRange().GetStart();
3528 wxString newText
= textObject
->GetText().Mid(0, posInString
) +
3529 text
+ textObject
->GetText().Mid(posInString
);
3530 textObject
->SetText(newText
);
3532 int textLength
= text
.length();
3534 textObject
->SetRange(wxRichTextRange(textObject
->GetRange().GetStart(),
3535 textObject
->GetRange().GetEnd() + textLength
));
3537 // Increment the end range of subsequent fragments in this paragraph.
3538 // We'll set the paragraph range itself at a higher level.
3540 wxRichTextObjectList::compatibility_iterator node
= nodeToUse
->GetNext();
3543 wxRichTextObject
* child
= node
->GetData();
3544 child
->SetRange(wxRichTextRange(textObject
->GetRange().GetStart() + textLength
,
3545 textObject
->GetRange().GetEnd() + textLength
));
3547 node
= node
->GetNext();
3554 // TODO: if not a text object, insert at closest position, e.g. in front of it
3560 // Don't pass parent initially to suppress auto-setting of parent range.
3561 // We'll do that at a higher level.
3562 wxRichTextPlainText
* textObject
= new wxRichTextPlainText(text
, this);
3564 AppendChild(textObject
);
3571 void wxRichTextParagraph::Copy(const wxRichTextParagraph
& obj
)
3573 wxRichTextBox::Copy(obj
);
3576 /// Clear the cached lines
3577 void wxRichTextParagraph::ClearLines()
3579 WX_CLEAR_LIST(wxRichTextLineList
, m_cachedLines
);
3582 /// Get/set the object size for the given range. Returns false if the range
3583 /// is invalid for this object.
3584 bool wxRichTextParagraph::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
, wxArrayInt
* partialExtents
) const
3586 if (!range
.IsWithin(GetRange()))
3589 if (flags
& wxRICHTEXT_UNFORMATTED
)
3591 // Just use unformatted data, assume no line breaks
3592 // TODO: take into account line breaks
3596 wxArrayInt childExtents
;
3603 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3607 wxRichTextObject
* child
= node
->GetData();
3608 if (!child
->GetRange().IsOutside(range
))
3612 wxRichTextRange rangeToUse
= range
;
3613 rangeToUse
.LimitTo(child
->GetRange());
3614 int childDescent
= 0;
3616 if (child
->GetRangeSize(rangeToUse
, childSize
, childDescent
, dc
, flags
, wxPoint(position
.x
+ sz
.x
, position
.y
), p
))
3618 sz
.y
= wxMax(sz
.y
, childSize
.y
);
3619 sz
.x
+= childSize
.x
;
3620 descent
= wxMax(descent
, childDescent
);
3625 if (partialExtents
->GetCount() > 0)
3626 lastSize
= (*partialExtents
)[partialExtents
->GetCount()-1];
3631 for (i
= 0; i
< childExtents
.GetCount(); i
++)
3633 partialExtents
->Add(childExtents
[i
] + lastSize
);
3642 node
= node
->GetNext();
3648 // Use formatted data, with line breaks
3651 // We're going to loop through each line, and then for each line,
3652 // call GetRangeSize for the fragment that comprises that line.
3653 // Only we have to do that multiple times within the line, because
3654 // the line may be broken into pieces. For now ignore line break commands
3655 // (so we can assume that getting the unformatted size for a fragment
3656 // within a line is the actual size)
3658 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3661 wxRichTextLine
* line
= node
->GetData();
3662 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3663 if (!lineRange
.IsOutside(range
))
3667 wxRichTextObjectList::compatibility_iterator node2
= m_children
.GetFirst();
3670 wxRichTextObject
* child
= node2
->GetData();
3672 if (!child
->GetRange().IsOutside(lineRange
))
3674 wxRichTextRange rangeToUse
= lineRange
;
3675 rangeToUse
.LimitTo(child
->GetRange());
3678 int childDescent
= 0;
3679 if (child
->GetRangeSize(rangeToUse
, childSize
, childDescent
, dc
, flags
, wxPoint(position
.x
+ sz
.x
, position
.y
)))
3681 lineSize
.y
= wxMax(lineSize
.y
, childSize
.y
);
3682 lineSize
.x
+= childSize
.x
;
3684 descent
= wxMax(descent
, childDescent
);
3687 node2
= node2
->GetNext();
3690 // Increase size by a line (TODO: paragraph spacing)
3692 sz
.x
= wxMax(sz
.x
, lineSize
.x
);
3694 node
= node
->GetNext();
3701 /// Finds the absolute position and row height for the given character position
3702 bool wxRichTextParagraph::FindPosition(wxDC
& dc
, long index
, wxPoint
& pt
, int* height
, bool forceLineStart
)
3706 wxRichTextLine
* line
= ((wxRichTextParagraphLayoutBox
*)GetParent())->GetLineAtPosition(0);
3708 *height
= line
->GetSize().y
;
3710 *height
= dc
.GetCharHeight();
3712 // -1 means 'the start of the buffer'.
3715 pt
= pt
+ line
->GetPosition();
3720 // The final position in a paragraph is taken to mean the position
3721 // at the start of the next paragraph.
3722 if (index
== GetRange().GetEnd())
3724 wxRichTextParagraphLayoutBox
* parent
= wxDynamicCast(GetParent(), wxRichTextParagraphLayoutBox
);
3725 wxASSERT( parent
!= NULL
);
3727 // Find the height at the next paragraph, if any
3728 wxRichTextLine
* line
= parent
->GetLineAtPosition(index
+ 1);
3731 *height
= line
->GetSize().y
;
3732 pt
= line
->GetAbsolutePosition();
3736 *height
= dc
.GetCharHeight();
3737 int indent
= ConvertTenthsMMToPixels(dc
, m_attributes
.GetLeftIndent());
3738 pt
= wxPoint(indent
, GetCachedSize().y
);
3744 if (index
< GetRange().GetStart() || index
> GetRange().GetEnd())
3747 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3750 wxRichTextLine
* line
= node
->GetData();
3751 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3752 if (index
>= lineRange
.GetStart() && index
<= lineRange
.GetEnd())
3754 // If this is the last point in the line, and we're forcing the
3755 // returned value to be the start of the next line, do the required
3757 if (index
== lineRange
.GetEnd() && forceLineStart
)
3759 if (node
->GetNext())
3761 wxRichTextLine
* nextLine
= node
->GetNext()->GetData();
3762 *height
= nextLine
->GetSize().y
;
3763 pt
= nextLine
->GetAbsolutePosition();
3768 pt
.y
= line
->GetPosition().y
+ GetPosition().y
;
3770 wxRichTextRange
r(lineRange
.GetStart(), index
);
3774 // We find the size of the line up to this point,
3775 // then we can add this size to the line start position and
3776 // paragraph start position to find the actual position.
3778 if (GetRangeSize(r
, rangeSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, line
->GetPosition()+ GetPosition()))
3780 pt
.x
= line
->GetPosition().x
+ GetPosition().x
+ rangeSize
.x
;
3781 *height
= line
->GetSize().y
;
3788 node
= node
->GetNext();
3794 /// Hit-testing: returns a flag indicating hit test details, plus
3795 /// information about position
3796 int wxRichTextParagraph::HitTest(wxDC
& dc
, const wxPoint
& pt
, long& textPosition
)
3798 wxPoint paraPos
= GetPosition();
3800 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3803 wxRichTextLine
* line
= node
->GetData();
3804 wxPoint linePos
= paraPos
+ line
->GetPosition();
3805 wxSize lineSize
= line
->GetSize();
3806 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3808 if (pt
.y
<= linePos
.y
+ lineSize
.y
)
3810 if (pt
.x
< linePos
.x
)
3812 textPosition
= lineRange
.GetStart();
3813 return wxRICHTEXT_HITTEST_BEFORE
|wxRICHTEXT_HITTEST_OUTSIDE
;
3815 else if (pt
.x
>= (linePos
.x
+ lineSize
.x
))
3817 textPosition
= lineRange
.GetEnd();
3818 return wxRICHTEXT_HITTEST_AFTER
|wxRICHTEXT_HITTEST_OUTSIDE
;
3823 int lastX
= linePos
.x
;
3824 for (i
= lineRange
.GetStart(); i
<= lineRange
.GetEnd(); i
++)
3829 wxRichTextRange
rangeToUse(lineRange
.GetStart(), i
);
3831 GetRangeSize(rangeToUse
, childSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, linePos
);
3833 int nextX
= childSize
.x
+ linePos
.x
;
3835 if (pt
.x
>= lastX
&& pt
.x
<= nextX
)
3839 // So now we know it's between i-1 and i.
3840 // Let's see if we can be more precise about
3841 // which side of the position it's on.
3843 int midPoint
= (nextX
- lastX
)/2 + lastX
;
3844 if (pt
.x
>= midPoint
)
3845 return wxRICHTEXT_HITTEST_AFTER
;
3847 return wxRICHTEXT_HITTEST_BEFORE
;
3857 node
= node
->GetNext();
3860 return wxRICHTEXT_HITTEST_NONE
;
3863 /// Split an object at this position if necessary, and return
3864 /// the previous object, or NULL if inserting at beginning.
3865 wxRichTextObject
* wxRichTextParagraph::SplitAt(long pos
, wxRichTextObject
** previousObject
)
3867 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3870 wxRichTextObject
* child
= node
->GetData();
3872 if (pos
== child
->GetRange().GetStart())
3876 if (node
->GetPrevious())
3877 *previousObject
= node
->GetPrevious()->GetData();
3879 *previousObject
= NULL
;
3885 if (child
->GetRange().Contains(pos
))
3887 // This should create a new object, transferring part of
3888 // the content to the old object and the rest to the new object.
3889 wxRichTextObject
* newObject
= child
->DoSplit(pos
);
3891 // If we couldn't split this object, just insert in front of it.
3894 // Maybe this is an empty string, try the next one
3899 // Insert the new object after 'child'
3900 if (node
->GetNext())
3901 m_children
.Insert(node
->GetNext(), newObject
);
3903 m_children
.Append(newObject
);
3904 newObject
->SetParent(this);
3907 *previousObject
= child
;
3913 node
= node
->GetNext();
3916 *previousObject
= NULL
;
3920 /// Move content to a list from obj on
3921 void wxRichTextParagraph::MoveToList(wxRichTextObject
* obj
, wxList
& list
)
3923 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(obj
);
3926 wxRichTextObject
* child
= node
->GetData();
3929 wxRichTextObjectList::compatibility_iterator oldNode
= node
;
3931 node
= node
->GetNext();
3933 m_children
.DeleteNode(oldNode
);
3937 /// Add content back from list
3938 void wxRichTextParagraph::MoveFromList(wxList
& list
)
3940 for (wxList::compatibility_iterator node
= list
.GetFirst(); node
; node
= node
->GetNext())
3942 AppendChild((wxRichTextObject
*) node
->GetData());
3947 void wxRichTextParagraph::CalculateRange(long start
, long& end
)
3949 wxRichTextCompositeObject::CalculateRange(start
, end
);
3951 // Add one for end of paragraph
3954 m_range
.SetRange(start
, end
);
3957 /// Find the object at the given position
3958 wxRichTextObject
* wxRichTextParagraph::FindObjectAtPosition(long position
)
3960 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3963 wxRichTextObject
* obj
= node
->GetData();
3964 if (obj
->GetRange().Contains(position
))
3967 node
= node
->GetNext();
3972 /// Get the plain text searching from the start or end of the range.
3973 /// The resulting string may be shorter than the range given.
3974 bool wxRichTextParagraph::GetContiguousPlainText(wxString
& text
, const wxRichTextRange
& range
, bool fromStart
)
3976 text
= wxEmptyString
;
3980 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3983 wxRichTextObject
* obj
= node
->GetData();
3984 if (!obj
->GetRange().IsOutside(range
))
3986 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
3989 text
+= textObj
->GetTextForRange(range
);
3995 node
= node
->GetNext();
4000 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetLast();
4003 wxRichTextObject
* obj
= node
->GetData();
4004 if (!obj
->GetRange().IsOutside(range
))
4006 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
4009 text
= textObj
->GetTextForRange(range
) + text
;
4015 node
= node
->GetPrevious();
4022 /// Find a suitable wrap position.
4023 bool wxRichTextParagraph::FindWrapPosition(const wxRichTextRange
& range
, wxDC
& dc
, int availableSpace
, long& wrapPosition
, wxArrayInt
* partialExtents
)
4025 if (range
.GetLength() <= 0)
4028 // Find the first position where the line exceeds the available space.
4030 long breakPosition
= range
.GetEnd();
4032 #if wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
4033 if (partialExtents
&& partialExtents
->GetCount() >= (size_t) (GetRange().GetLength()-1)) // the final position in a paragraph is the newline
4037 if (range
.GetStart() > GetRange().GetStart())
4038 widthBefore
= (*partialExtents
)[range
.GetStart() - GetRange().GetStart() - 1];
4043 for (i
= (size_t) range
.GetStart(); i
< (size_t) range
.GetEnd(); i
++)
4045 int widthFromStartOfThisRange
= (*partialExtents
)[i
- GetRange().GetStart()] - widthBefore
;
4047 if (widthFromStartOfThisRange
> availableSpace
)
4049 breakPosition
= i
-1;
4057 // Binary chop for speed
4058 long minPos
= range
.GetStart();
4059 long maxPos
= range
.GetEnd();
4062 if (minPos
== maxPos
)
4065 GetRangeSize(wxRichTextRange(range
.GetStart(), minPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
4067 if (sz
.x
> availableSpace
)
4068 breakPosition
= minPos
- 1;
4071 else if ((maxPos
- minPos
) == 1)
4074 GetRangeSize(wxRichTextRange(range
.GetStart(), minPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
4076 if (sz
.x
> availableSpace
)
4077 breakPosition
= minPos
- 1;
4080 GetRangeSize(wxRichTextRange(range
.GetStart(), maxPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
4081 if (sz
.x
> availableSpace
)
4082 breakPosition
= maxPos
-1;
4088 long nextPos
= minPos
+ ((maxPos
- minPos
) / 2);
4091 GetRangeSize(wxRichTextRange(range
.GetStart(), nextPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
4093 if (sz
.x
> availableSpace
)
4105 // Now we know the last position on the line.
4106 // Let's try to find a word break.
4109 if (GetContiguousPlainText(plainText
, wxRichTextRange(range
.GetStart(), breakPosition
), false))
4111 int newLinePos
= plainText
.Find(wxRichTextLineBreakChar
);
4112 if (newLinePos
!= wxNOT_FOUND
)
4114 breakPosition
= wxMax(0, range
.GetStart() + newLinePos
);
4118 int spacePos
= plainText
.Find(wxT(' '), true);
4119 int tabPos
= plainText
.Find(wxT('\t'), true);
4120 int pos
= wxMax(spacePos
, tabPos
);
4121 if (pos
!= wxNOT_FOUND
)
4123 int positionsFromEndOfString
= plainText
.length() - pos
- 1;
4124 breakPosition
= breakPosition
- positionsFromEndOfString
;
4129 wrapPosition
= breakPosition
;
4134 /// Get the bullet text for this paragraph.
4135 wxString
wxRichTextParagraph::GetBulletText()
4137 if (GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE
||
4138 (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP
))
4139 return wxEmptyString
;
4141 int number
= GetAttributes().GetBulletNumber();
4144 if ((GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ARABIC
) || (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
))
4146 text
.Printf(wxT("%d"), number
);
4148 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER
)
4150 // TODO: Unicode, and also check if number > 26
4151 text
.Printf(wxT("%c"), (wxChar
) (number
+64));
4153 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER
)
4155 // TODO: Unicode, and also check if number > 26
4156 text
.Printf(wxT("%c"), (wxChar
) (number
+96));
4158 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER
)
4160 text
= wxRichTextDecimalToRoman(number
);
4162 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER
)
4164 text
= wxRichTextDecimalToRoman(number
);
4167 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL
)
4169 text
= GetAttributes().GetBulletText();
4172 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
)
4174 // The outline style relies on the text being computed statically,
4175 // since it depends on other levels points (e.g. 1.2.1.1). So normally the bullet text
4176 // should be stored in the attributes; if not, just use the number for this
4177 // level, as previously computed.
4178 if (!GetAttributes().GetBulletText().IsEmpty())
4179 text
= GetAttributes().GetBulletText();
4182 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PARENTHESES
)
4184 text
= wxT("(") + text
+ wxT(")");
4186 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS
)
4188 text
= text
+ wxT(")");
4191 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PERIOD
)
4199 /// Allocate or reuse a line object
4200 wxRichTextLine
* wxRichTextParagraph::AllocateLine(int pos
)
4202 if (pos
< (int) m_cachedLines
.GetCount())
4204 wxRichTextLine
* line
= m_cachedLines
.Item(pos
)->GetData();
4210 wxRichTextLine
* line
= new wxRichTextLine(this);
4211 m_cachedLines
.Append(line
);
4216 /// Clear remaining unused line objects, if any
4217 bool wxRichTextParagraph::ClearUnusedLines(int lineCount
)
4219 int cachedLineCount
= m_cachedLines
.GetCount();
4220 if ((int) cachedLineCount
> lineCount
)
4222 for (int i
= 0; i
< (int) (cachedLineCount
- lineCount
); i
++)
4224 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetLast();
4225 wxRichTextLine
* line
= node
->GetData();
4226 m_cachedLines
.Erase(node
);
4233 /// Get combined attributes of the base style, paragraph style and character style. We use this to dynamically
4234 /// retrieve the actual style.
4235 wxTextAttr
wxRichTextParagraph::GetCombinedAttributes(const wxTextAttr
& contentStyle
) const
4238 wxRichTextBuffer
* buf
= wxDynamicCast(GetParent(), wxRichTextBuffer
);
4241 attr
= buf
->GetBasicStyle();
4242 wxRichTextApplyStyle(attr
, GetAttributes());
4245 attr
= GetAttributes();
4247 wxRichTextApplyStyle(attr
, contentStyle
);
4251 /// Get combined attributes of the base style and paragraph style.
4252 wxTextAttr
wxRichTextParagraph::GetCombinedAttributes() const
4255 wxRichTextBuffer
* buf
= wxDynamicCast(GetParent(), wxRichTextBuffer
);
4258 attr
= buf
->GetBasicStyle();
4259 wxRichTextApplyStyle(attr
, GetAttributes());
4262 attr
= GetAttributes();
4267 /// Create default tabstop array
4268 void wxRichTextParagraph::InitDefaultTabs()
4270 // create a default tab list at 10 mm each.
4271 for (int i
= 0; i
< 20; ++i
)
4273 sm_defaultTabs
.Add(i
*100);
4277 /// Clear default tabstop array
4278 void wxRichTextParagraph::ClearDefaultTabs()
4280 sm_defaultTabs
.Clear();
4283 /// Get the first position from pos that has a line break character.
4284 long wxRichTextParagraph::GetFirstLineBreakPosition(long pos
)
4286 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
4289 wxRichTextObject
* obj
= node
->GetData();
4290 if (pos
>= obj
->GetRange().GetStart() && pos
<= obj
->GetRange().GetEnd())
4292 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
4295 long breakPos
= textObj
->GetFirstLineBreakPosition(pos
);
4300 node
= node
->GetNext();
4307 * This object represents a line in a paragraph, and stores
4308 * offsets from the start of the paragraph representing the
4309 * start and end positions of the line.
4312 wxRichTextLine::wxRichTextLine(wxRichTextParagraph
* parent
)
4318 void wxRichTextLine::Init(wxRichTextParagraph
* parent
)
4321 m_range
.SetRange(-1, -1);
4322 m_pos
= wxPoint(0, 0);
4323 m_size
= wxSize(0, 0);
4328 void wxRichTextLine::Copy(const wxRichTextLine
& obj
)
4330 m_range
= obj
.m_range
;
4333 /// Get the absolute object position
4334 wxPoint
wxRichTextLine::GetAbsolutePosition() const
4336 return m_parent
->GetPosition() + m_pos
;
4339 /// Get the absolute range
4340 wxRichTextRange
wxRichTextLine::GetAbsoluteRange() const
4342 wxRichTextRange
range(m_range
.GetStart() + m_parent
->GetRange().GetStart(), 0);
4343 range
.SetEnd(range
.GetStart() + m_range
.GetLength()-1);
4348 * wxRichTextPlainText
4349 * This object represents a single piece of text.
4352 IMPLEMENT_DYNAMIC_CLASS(wxRichTextPlainText
, wxRichTextObject
)
4354 wxRichTextPlainText::wxRichTextPlainText(const wxString
& text
, wxRichTextObject
* parent
, wxTextAttr
* style
):
4355 wxRichTextObject(parent
)
4358 SetAttributes(*style
);
4363 #define USE_KERNING_FIX 1
4365 // If insufficient tabs are defined, this is the tab width used
4366 #define WIDTH_FOR_DEFAULT_TABS 50
4369 bool wxRichTextPlainText::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int descent
, int WXUNUSED(style
))
4371 wxRichTextParagraph
* para
= wxDynamicCast(GetParent(), wxRichTextParagraph
);
4372 wxASSERT (para
!= NULL
);
4374 wxTextAttr
textAttr(para
? para
->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4376 int offset
= GetRange().GetStart();
4378 // Replace line break characters with spaces
4379 wxString str
= m_text
;
4380 wxString toRemove
= wxRichTextLineBreakChar
;
4381 str
.Replace(toRemove
, wxT(" "));
4382 if (textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
4385 long len
= range
.GetLength();
4386 wxString stringChunk
= str
.Mid(range
.GetStart() - offset
, (size_t) len
);
4388 // Test for the optimized situations where all is selected, or none
4391 wxFont
textFont(GetBuffer()->GetFontTable().FindFont(textAttr
));
4392 wxCheckSetFont(dc
, textFont
);
4393 int charHeight
= dc
.GetCharHeight();
4396 if ( textFont
.Ok() )
4398 if ( textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUPERSCRIPT
) )
4400 double size
= static_cast<double>(textFont
.GetPointSize()) / wxSCRIPT_MUL_FACTOR
;
4401 textFont
.SetPointSize( static_cast<int>(size
) );
4404 wxCheckSetFont(dc
, textFont
);
4406 else if ( textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUBSCRIPT
) )
4408 double size
= static_cast<double>(textFont
.GetPointSize()) / wxSCRIPT_MUL_FACTOR
;
4409 textFont
.SetPointSize( static_cast<int>(size
) );
4411 int sub_height
= static_cast<int>( static_cast<double>(charHeight
) / wxSCRIPT_MUL_FACTOR
);
4412 y
= rect
.y
+ (rect
.height
- sub_height
+ (descent
- m_descent
));
4413 wxCheckSetFont(dc
, textFont
);
4418 y
= rect
.y
+ (rect
.height
- charHeight
- (descent
- m_descent
));
4424 y
= rect
.y
+ (rect
.height
- charHeight
- (descent
- m_descent
));
4427 // (a) All selected.
4428 if (selectionRange
.GetStart() <= range
.GetStart() && selectionRange
.GetEnd() >= range
.GetEnd())
4430 DrawTabbedString(dc
, textAttr
, rect
, stringChunk
, x
, y
, true);
4432 // (b) None selected.
4433 else if (selectionRange
.GetEnd() < range
.GetStart() || selectionRange
.GetStart() > range
.GetEnd())
4435 // Draw all unselected
4436 DrawTabbedString(dc
, textAttr
, rect
, stringChunk
, x
, y
, false);
4440 // (c) Part selected, part not
4441 // Let's draw unselected chunk, selected chunk, then unselected chunk.
4443 dc
.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT
);
4445 // 1. Initial unselected chunk, if any, up until start of selection.
4446 if (selectionRange
.GetStart() > range
.GetStart() && selectionRange
.GetStart() <= range
.GetEnd())
4448 int r1
= range
.GetStart();
4449 int s1
= selectionRange
.GetStart()-1;
4450 int fragmentLen
= s1
- r1
+ 1;
4451 if (fragmentLen
< 0)
4452 wxLogDebug(wxT("Mid(%d, %d"), (int)(r1
- offset
), (int)fragmentLen
);
4453 wxString stringFragment
= str
.Mid(r1
- offset
, fragmentLen
);
4455 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, false);
4458 if (stringChunk
.Find(wxT("\t")) == wxNOT_FOUND
)
4460 // Compensate for kerning difference
4461 wxString
stringFragment2(str
.Mid(r1
- offset
, fragmentLen
+1));
4462 wxString
stringFragment3(str
.Mid(r1
- offset
+ fragmentLen
, 1));
4464 wxCoord w1
, h1
, w2
, h2
, w3
, h3
;
4465 dc
.GetTextExtent(stringFragment
, & w1
, & h1
);
4466 dc
.GetTextExtent(stringFragment2
, & w2
, & h2
);
4467 dc
.GetTextExtent(stringFragment3
, & w3
, & h3
);
4469 int kerningDiff
= (w1
+ w3
) - w2
;
4470 x
= x
- kerningDiff
;
4475 // 2. Selected chunk, if any.
4476 if (selectionRange
.GetEnd() >= range
.GetStart())
4478 int s1
= wxMax(selectionRange
.GetStart(), range
.GetStart());
4479 int s2
= wxMin(selectionRange
.GetEnd(), range
.GetEnd());
4481 int fragmentLen
= s2
- s1
+ 1;
4482 if (fragmentLen
< 0)
4483 wxLogDebug(wxT("Mid(%d, %d"), (int)(s1
- offset
), (int)fragmentLen
);
4484 wxString stringFragment
= str
.Mid(s1
- offset
, fragmentLen
);
4486 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, true);
4489 if (stringChunk
.Find(wxT("\t")) == wxNOT_FOUND
)
4491 // Compensate for kerning difference
4492 wxString
stringFragment2(str
.Mid(s1
- offset
, fragmentLen
+1));
4493 wxString
stringFragment3(str
.Mid(s1
- offset
+ fragmentLen
, 1));
4495 wxCoord w1
, h1
, w2
, h2
, w3
, h3
;
4496 dc
.GetTextExtent(stringFragment
, & w1
, & h1
);
4497 dc
.GetTextExtent(stringFragment2
, & w2
, & h2
);
4498 dc
.GetTextExtent(stringFragment3
, & w3
, & h3
);
4500 int kerningDiff
= (w1
+ w3
) - w2
;
4501 x
= x
- kerningDiff
;
4506 // 3. Remaining unselected chunk, if any
4507 if (selectionRange
.GetEnd() < range
.GetEnd())
4509 int s2
= wxMin(selectionRange
.GetEnd()+1, range
.GetEnd());
4510 int r2
= range
.GetEnd();
4512 int fragmentLen
= r2
- s2
+ 1;
4513 if (fragmentLen
< 0)
4514 wxLogDebug(wxT("Mid(%d, %d"), (int)(s2
- offset
), (int)fragmentLen
);
4515 wxString stringFragment
= str
.Mid(s2
- offset
, fragmentLen
);
4517 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, false);
4524 bool wxRichTextPlainText::DrawTabbedString(wxDC
& dc
, const wxTextAttr
& attr
, const wxRect
& rect
,wxString
& str
, wxCoord
& x
, wxCoord
& y
, bool selected
)
4526 bool hasTabs
= (str
.Find(wxT('\t')) != wxNOT_FOUND
);
4528 wxArrayInt tabArray
;
4532 if (attr
.GetTabs().IsEmpty())
4533 tabArray
= wxRichTextParagraph::GetDefaultTabs();
4535 tabArray
= attr
.GetTabs();
4536 tabCount
= tabArray
.GetCount();
4538 for (int i
= 0; i
< tabCount
; ++i
)
4540 int pos
= tabArray
[i
];
4541 pos
= ConvertTenthsMMToPixels(dc
, pos
);
4548 int nextTabPos
= -1;
4554 wxColour
highlightColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT
));
4555 wxColour
highlightTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT
));
4557 wxCheckSetBrush(dc
, wxBrush(highlightColour
));
4558 wxCheckSetPen(dc
, wxPen(highlightColour
));
4559 dc
.SetTextForeground(highlightTextColour
);
4560 dc
.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT
);
4564 dc
.SetTextForeground(attr
.GetTextColour());
4566 if (attr
.HasFlag(wxTEXT_ATTR_BACKGROUND_COLOUR
) && attr
.GetBackgroundColour().IsOk())
4568 dc
.SetBackgroundMode(wxBRUSHSTYLE_SOLID
);
4569 dc
.SetTextBackground(attr
.GetBackgroundColour());
4572 dc
.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT
);
4577 // the string has a tab
4578 // break up the string at the Tab
4579 wxString stringChunk
= str
.BeforeFirst(wxT('\t'));
4580 str
= str
.AfterFirst(wxT('\t'));
4581 dc
.GetTextExtent(stringChunk
, & w
, & h
);
4583 bool not_found
= true;
4584 for (int i
= 0; i
< tabCount
&& not_found
; ++i
)
4586 nextTabPos
= tabArray
.Item(i
);
4588 // Find the next tab position.
4589 // Even if we're at the end of the tab array, we must still draw the chunk.
4591 if (nextTabPos
> tabPos
|| (i
== (tabCount
- 1)))
4593 if (nextTabPos
<= tabPos
)
4595 int defaultTabWidth
= ConvertTenthsMMToPixels(dc
, WIDTH_FOR_DEFAULT_TABS
);
4596 nextTabPos
= tabPos
+ defaultTabWidth
;
4603 wxRect
selRect(x
, rect
.y
, w
, rect
.GetHeight());
4604 dc
.DrawRectangle(selRect
);
4606 dc
.DrawText(stringChunk
, x
, y
);
4608 if (attr
.HasTextEffects() && (attr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH
))
4610 wxPen oldPen
= dc
.GetPen();
4611 wxCheckSetPen(dc
, wxPen(attr
.GetTextColour(), 1));
4612 dc
.DrawLine(x
, (int) (y
+(h
/2)+0.5), x
+w
, (int) (y
+(h
/2)+0.5));
4613 wxCheckSetPen(dc
, oldPen
);
4619 hasTabs
= (str
.Find(wxT('\t')) != wxNOT_FOUND
);
4624 dc
.GetTextExtent(str
, & w
, & h
);
4627 wxRect
selRect(x
, rect
.y
, w
, rect
.GetHeight());
4628 dc
.DrawRectangle(selRect
);
4630 dc
.DrawText(str
, x
, y
);
4632 if (attr
.HasTextEffects() && (attr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH
))
4634 wxPen oldPen
= dc
.GetPen();
4635 wxCheckSetPen(dc
, wxPen(attr
.GetTextColour(), 1));
4636 dc
.DrawLine(x
, (int) (y
+(h
/2)+0.5), x
+w
, (int) (y
+(h
/2)+0.5));
4637 wxCheckSetPen(dc
, oldPen
);
4646 /// Lay the item out
4647 bool wxRichTextPlainText::Layout(wxDC
& dc
, const wxRect
& WXUNUSED(rect
), int WXUNUSED(style
))
4649 // Only lay out if we haven't already cached the size
4651 GetRangeSize(GetRange(), m_size
, m_descent
, dc
, 0, wxPoint(0, 0));
4657 void wxRichTextPlainText::Copy(const wxRichTextPlainText
& obj
)
4659 wxRichTextObject::Copy(obj
);
4661 m_text
= obj
.m_text
;
4664 /// Get/set the object size for the given range. Returns false if the range
4665 /// is invalid for this object.
4666 bool wxRichTextPlainText::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int WXUNUSED(flags
), wxPoint position
, wxArrayInt
* partialExtents
) const
4668 if (!range
.IsWithin(GetRange()))
4671 wxRichTextParagraph
* para
= wxDynamicCast(GetParent(), wxRichTextParagraph
);
4672 wxASSERT (para
!= NULL
);
4674 wxTextAttr
textAttr(para
? para
->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4676 // Always assume unformatted text, since at this level we have no knowledge
4677 // of line breaks - and we don't need it, since we'll calculate size within
4678 // formatted text by doing it in chunks according to the line ranges
4680 bool bScript(false);
4681 wxFont
font(GetBuffer()->GetFontTable().FindFont(textAttr
));
4684 if ( textAttr
.HasTextEffects() && ( (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUPERSCRIPT
)
4685 || (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUBSCRIPT
) ) )
4687 wxFont textFont
= font
;
4688 double size
= static_cast<double>(textFont
.GetPointSize()) / wxSCRIPT_MUL_FACTOR
;
4689 textFont
.SetPointSize( static_cast<int>(size
) );
4690 wxCheckSetFont(dc
, textFont
);
4695 wxCheckSetFont(dc
, font
);
4699 int startPos
= range
.GetStart() - GetRange().GetStart();
4700 long len
= range
.GetLength();
4702 wxString
str(m_text
);
4703 wxString toReplace
= wxRichTextLineBreakChar
;
4704 str
.Replace(toReplace
, wxT(" "));
4706 wxString stringChunk
= str
.Mid(startPos
, (size_t) len
);
4708 if (textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
4709 stringChunk
.MakeUpper();
4713 if (stringChunk
.Find(wxT('\t')) != wxNOT_FOUND
)
4715 // the string has a tab
4716 wxArrayInt tabArray
;
4717 if (textAttr
.GetTabs().IsEmpty())
4718 tabArray
= wxRichTextParagraph::GetDefaultTabs();
4720 tabArray
= textAttr
.GetTabs();
4722 int tabCount
= tabArray
.GetCount();
4724 for (int i
= 0; i
< tabCount
; ++i
)
4726 int pos
= tabArray
[i
];
4727 pos
= ((wxRichTextPlainText
*) this)->ConvertTenthsMMToPixels(dc
, pos
);
4731 int nextTabPos
= -1;
4733 while (stringChunk
.Find(wxT('\t')) >= 0)
4735 // the string has a tab
4736 // break up the string at the Tab
4737 wxString stringFragment
= stringChunk
.BeforeFirst(wxT('\t'));
4738 stringChunk
= stringChunk
.AfterFirst(wxT('\t'));
4739 int oldWidth
= width
;
4740 dc
.GetTextExtent(stringFragment
, & w
, & h
);
4742 int absoluteWidth
= width
+ position
.x
;
4746 // Add these partial extents
4748 dc
.GetPartialTextExtents(stringFragment
, p
);
4750 for (j
= 0; j
< p
.GetCount(); j
++)
4751 partialExtents
->Add(oldWidth
+ p
[j
]);
4754 bool notFound
= true;
4755 for (int i
= 0; i
< tabCount
&& notFound
; ++i
)
4757 nextTabPos
= tabArray
.Item(i
);
4759 // Find the next tab position.
4760 // Even if we're at the end of the tab array, we must still process the chunk.
4762 if (nextTabPos
> absoluteWidth
|| (i
== (tabCount
- 1)))
4764 if (nextTabPos
<= absoluteWidth
)
4766 int defaultTabWidth
= ((wxRichTextPlainText
*) this)->ConvertTenthsMMToPixels(dc
, WIDTH_FOR_DEFAULT_TABS
);
4767 nextTabPos
= absoluteWidth
+ defaultTabWidth
;
4771 width
= nextTabPos
- position
.x
;
4774 partialExtents
->Add(width
);
4780 if (!stringChunk
.IsEmpty())
4782 dc
.GetTextExtent(stringChunk
, & w
, & h
, & descent
);
4783 int oldWidth
= width
;
4788 // Add these partial extents
4790 dc
.GetPartialTextExtents(stringChunk
, p
);
4792 for (j
= 0; j
< p
.GetCount(); j
++)
4793 partialExtents
->Add(oldWidth
+ p
[j
]);
4800 size
= wxSize(width
, dc
.GetCharHeight());
4805 /// Do a split, returning an object containing the second part, and setting
4806 /// the first part in 'this'.
4807 wxRichTextObject
* wxRichTextPlainText::DoSplit(long pos
)
4809 long index
= pos
- GetRange().GetStart();
4811 if (index
< 0 || index
>= (int) m_text
.length())
4814 wxString firstPart
= m_text
.Mid(0, index
);
4815 wxString secondPart
= m_text
.Mid(index
);
4819 wxRichTextPlainText
* newObject
= new wxRichTextPlainText(secondPart
);
4820 newObject
->SetAttributes(GetAttributes());
4822 newObject
->SetRange(wxRichTextRange(pos
, GetRange().GetEnd()));
4823 GetRange().SetEnd(pos
-1);
4829 void wxRichTextPlainText::CalculateRange(long start
, long& end
)
4831 end
= start
+ m_text
.length() - 1;
4832 m_range
.SetRange(start
, end
);
4836 bool wxRichTextPlainText::DeleteRange(const wxRichTextRange
& range
)
4838 wxRichTextRange r
= range
;
4840 r
.LimitTo(GetRange());
4842 if (r
.GetStart() == GetRange().GetStart() && r
.GetEnd() == GetRange().GetEnd())
4848 long startIndex
= r
.GetStart() - GetRange().GetStart();
4849 long len
= r
.GetLength();
4851 m_text
= m_text
.Mid(0, startIndex
) + m_text
.Mid(startIndex
+len
);
4855 /// Get text for the given range.
4856 wxString
wxRichTextPlainText::GetTextForRange(const wxRichTextRange
& range
) const
4858 wxRichTextRange r
= range
;
4860 r
.LimitTo(GetRange());
4862 long startIndex
= r
.GetStart() - GetRange().GetStart();
4863 long len
= r
.GetLength();
4865 return m_text
.Mid(startIndex
, len
);
4868 /// Returns true if this object can merge itself with the given one.
4869 bool wxRichTextPlainText::CanMerge(wxRichTextObject
* object
) const
4871 return object
->GetClassInfo() == CLASSINFO(wxRichTextPlainText
) &&
4872 (m_text
.empty() || wxTextAttrEq(GetAttributes(), object
->GetAttributes()));
4875 /// Returns true if this object merged itself with the given one.
4876 /// The calling code will then delete the given object.
4877 bool wxRichTextPlainText::Merge(wxRichTextObject
* object
)
4879 wxRichTextPlainText
* textObject
= wxDynamicCast(object
, wxRichTextPlainText
);
4880 wxASSERT( textObject
!= NULL
);
4884 m_text
+= textObject
->GetText();
4885 wxRichTextApplyStyle(m_attributes
, textObject
->GetAttributes());
4892 /// Dump to output stream for debugging
4893 void wxRichTextPlainText::Dump(wxTextOutputStream
& stream
)
4895 wxRichTextObject::Dump(stream
);
4896 stream
<< m_text
<< wxT("\n");
4899 /// Get the first position from pos that has a line break character.
4900 long wxRichTextPlainText::GetFirstLineBreakPosition(long pos
)
4903 int len
= m_text
.length();
4904 int startPos
= pos
- m_range
.GetStart();
4905 for (i
= startPos
; i
< len
; i
++)
4907 wxChar ch
= m_text
[i
];
4908 if (ch
== wxRichTextLineBreakChar
)
4910 return i
+ m_range
.GetStart();
4918 * This is a kind of box, used to represent the whole buffer
4921 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBuffer
, wxRichTextParagraphLayoutBox
)
4923 wxList
wxRichTextBuffer::sm_handlers
;
4924 wxRichTextRenderer
* wxRichTextBuffer::sm_renderer
= NULL
;
4925 int wxRichTextBuffer::sm_bulletRightMargin
= 20;
4926 float wxRichTextBuffer::sm_bulletProportion
= (float) 0.3;
4929 void wxRichTextBuffer::Init()
4931 m_commandProcessor
= new wxCommandProcessor
;
4932 m_styleSheet
= NULL
;
4934 m_batchedCommandDepth
= 0;
4935 m_batchedCommand
= NULL
;
4942 wxRichTextBuffer::~wxRichTextBuffer()
4944 delete m_commandProcessor
;
4945 delete m_batchedCommand
;
4948 ClearEventHandlers();
4951 void wxRichTextBuffer::ResetAndClearCommands()
4955 GetCommandProcessor()->ClearCommands();
4958 Invalidate(wxRICHTEXT_ALL
);
4961 void wxRichTextBuffer::Copy(const wxRichTextBuffer
& obj
)
4963 wxRichTextParagraphLayoutBox::Copy(obj
);
4965 m_styleSheet
= obj
.m_styleSheet
;
4966 m_modified
= obj
.m_modified
;
4967 m_batchedCommandDepth
= obj
.m_batchedCommandDepth
;
4968 m_batchedCommand
= obj
.m_batchedCommand
;
4969 m_suppressUndo
= obj
.m_suppressUndo
;
4972 /// Push style sheet to top of stack
4973 bool wxRichTextBuffer::PushStyleSheet(wxRichTextStyleSheet
* styleSheet
)
4976 styleSheet
->InsertSheet(m_styleSheet
);
4978 SetStyleSheet(styleSheet
);
4983 /// Pop style sheet from top of stack
4984 wxRichTextStyleSheet
* wxRichTextBuffer::PopStyleSheet()
4988 wxRichTextStyleSheet
* oldSheet
= m_styleSheet
;
4989 m_styleSheet
= oldSheet
->GetNextSheet();
4998 /// Submit command to insert paragraphs
4999 bool wxRichTextBuffer::InsertParagraphsWithUndo(long pos
, const wxRichTextParagraphLayoutBox
& paragraphs
, wxRichTextCtrl
* ctrl
, int flags
)
5001 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
5003 wxTextAttr
attr(GetDefaultStyle());
5005 wxTextAttr
* p
= NULL
;
5006 wxTextAttr paraAttr
;
5007 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
5009 paraAttr
= GetStyleForNewParagraph(pos
);
5010 if (!paraAttr
.IsDefault())
5016 action
->GetNewParagraphs() = paragraphs
;
5018 action
->SetPosition(pos
);
5020 wxRichTextRange range
= wxRichTextRange(pos
, pos
+ paragraphs
.GetRange().GetEnd() - 1);
5021 if (!paragraphs
.GetPartialParagraph())
5022 range
.SetEnd(range
.GetEnd()+1);
5024 // Set the range we'll need to delete in Undo
5025 action
->SetRange(range
);
5027 SubmitAction(action
);
5032 /// Submit command to insert the given text
5033 bool wxRichTextBuffer::InsertTextWithUndo(long pos
, const wxString
& text
, wxRichTextCtrl
* ctrl
, int flags
)
5035 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
5037 wxTextAttr
* p
= NULL
;
5038 wxTextAttr paraAttr
;
5039 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
5041 // Get appropriate paragraph style
5042 paraAttr
= GetStyleForNewParagraph(pos
, false, false);
5043 if (!paraAttr
.IsDefault())
5047 action
->GetNewParagraphs().AddParagraphs(text
, p
);
5049 int length
= action
->GetNewParagraphs().GetRange().GetLength();
5051 if (text
.length() > 0 && text
.Last() != wxT('\n'))
5053 // Don't count the newline when undoing
5055 action
->GetNewParagraphs().SetPartialParagraph(true);
5057 else if (text
.length() > 0 && text
.Last() == wxT('\n'))
5060 action
->SetPosition(pos
);
5062 // Set the range we'll need to delete in Undo
5063 action
->SetRange(wxRichTextRange(pos
, pos
+ length
- 1));
5065 SubmitAction(action
);
5070 /// Submit command to insert the given text
5071 bool wxRichTextBuffer::InsertNewlineWithUndo(long pos
, wxRichTextCtrl
* ctrl
, int flags
)
5073 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
5075 wxTextAttr
* p
= NULL
;
5076 wxTextAttr paraAttr
;
5077 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
5079 paraAttr
= GetStyleForNewParagraph(pos
, false, true /* look for next paragraph style */);
5080 if (!paraAttr
.IsDefault())
5084 wxTextAttr
attr(GetDefaultStyle());
5086 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(wxEmptyString
, this, & attr
);
5087 action
->GetNewParagraphs().AppendChild(newPara
);
5088 action
->GetNewParagraphs().UpdateRanges();
5089 action
->GetNewParagraphs().SetPartialParagraph(false);
5090 wxRichTextParagraph
* para
= GetParagraphAtPosition(pos
, false);
5094 newPara
->SetAttributes(*p
);
5096 if (flags
& wxRICHTEXT_INSERT_INTERACTIVE
)
5098 if (para
&& para
->GetRange().GetEnd() == pos
)
5100 if (newPara
->GetAttributes().HasBulletNumber())
5101 newPara
->GetAttributes().SetBulletNumber(newPara
->GetAttributes().GetBulletNumber()+1);
5104 action
->SetPosition(pos
);
5106 // Use the default character style
5107 // Use the default character style
5108 if (!GetDefaultStyle().IsDefault() && newPara
->GetChildren().GetFirst())
5110 // Check whether the default style merely reflects the paragraph/basic style,
5111 // in which case don't apply it.
5112 wxTextAttrEx
defaultStyle(GetDefaultStyle());
5113 wxTextAttrEx toApply
;
5116 wxRichTextAttr combinedAttr
= para
->GetCombinedAttributes();
5117 wxTextAttrEx newAttr
;
5118 // This filters out attributes that are accounted for by the current
5119 // paragraph/basic style
5120 wxRichTextApplyStyle(toApply
, defaultStyle
, & combinedAttr
);
5123 toApply
= defaultStyle
;
5125 if (!toApply
.IsDefault())
5126 newPara
->GetChildren().GetFirst()->GetData()->SetAttributes(toApply
);
5129 // Set the range we'll need to delete in Undo
5130 action
->SetRange(wxRichTextRange(pos1
, pos1
));
5132 SubmitAction(action
);
5137 /// Submit command to insert the given image
5138 bool wxRichTextBuffer::InsertImageWithUndo(long pos
, const wxRichTextImageBlock
& imageBlock
, wxRichTextCtrl
* ctrl
, int flags
)
5140 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Image"), wxRICHTEXT_INSERT
, this, ctrl
, false);
5142 wxTextAttr
* p
= NULL
;
5143 wxTextAttr paraAttr
;
5144 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
5146 paraAttr
= GetStyleForNewParagraph(pos
);
5147 if (!paraAttr
.IsDefault())
5151 wxTextAttr
attr(GetDefaultStyle());
5153 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(this, & attr
);
5155 newPara
->SetAttributes(*p
);
5157 wxRichTextImage
* imageObject
= new wxRichTextImage(imageBlock
, newPara
);
5158 newPara
->AppendChild(imageObject
);
5159 action
->GetNewParagraphs().AppendChild(newPara
);
5160 action
->GetNewParagraphs().UpdateRanges();
5162 action
->GetNewParagraphs().SetPartialParagraph(true);
5164 action
->SetPosition(pos
);
5166 // Set the range we'll need to delete in Undo
5167 action
->SetRange(wxRichTextRange(pos
, pos
));
5169 SubmitAction(action
);
5174 /// Get the style that is appropriate for a new paragraph at this position.
5175 /// If the previous paragraph has a paragraph style name, look up the next-paragraph
5177 wxTextAttr
wxRichTextBuffer::GetStyleForNewParagraph(long pos
, bool caretPosition
, bool lookUpNewParaStyle
) const
5179 wxRichTextParagraph
* para
= GetParagraphAtPosition(pos
, caretPosition
);
5183 bool foundAttributes
= false;
5185 // Look for a matching paragraph style
5186 if (lookUpNewParaStyle
&& !para
->GetAttributes().GetParagraphStyleName().IsEmpty() && GetStyleSheet())
5188 wxRichTextParagraphStyleDefinition
* paraDef
= GetStyleSheet()->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
5191 // If we're not at the end of the paragraph, then we apply THIS style, and not the designated next style.
5192 if (para
->GetRange().GetEnd() == pos
&& !paraDef
->GetNextStyle().IsEmpty())
5194 wxRichTextParagraphStyleDefinition
* nextParaDef
= GetStyleSheet()->FindParagraphStyle(paraDef
->GetNextStyle());
5197 foundAttributes
= true;
5198 attr
= nextParaDef
->GetStyleMergedWithBase(GetStyleSheet());
5202 // If we didn't find the 'next style', use this style instead.
5203 if (!foundAttributes
)
5205 foundAttributes
= true;
5206 attr
= paraDef
->GetStyleMergedWithBase(GetStyleSheet());
5210 if (!foundAttributes
)
5212 attr
= para
->GetAttributes();
5213 int flags
= attr
.GetFlags();
5215 // Eliminate character styles
5216 flags
&= ( (~ wxTEXT_ATTR_FONT
) |
5217 (~ wxTEXT_ATTR_TEXT_COLOUR
) |
5218 (~ wxTEXT_ATTR_BACKGROUND_COLOUR
) );
5219 attr
.SetFlags(flags
);
5222 // Now see if we need to number the paragraph.
5223 if (attr
.HasBulletStyle())
5225 wxTextAttr numberingAttr
;
5226 if (FindNextParagraphNumber(para
, numberingAttr
))
5227 wxRichTextApplyStyle(attr
, (const wxTextAttr
&) numberingAttr
);
5233 return wxTextAttr();
5236 /// Submit command to delete this range
5237 bool wxRichTextBuffer::DeleteRangeWithUndo(const wxRichTextRange
& range
, wxRichTextCtrl
* ctrl
)
5239 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Delete"), wxRICHTEXT_DELETE
, this, ctrl
);
5241 action
->SetPosition(ctrl
->GetCaretPosition());
5243 // Set the range to delete
5244 action
->SetRange(range
);
5246 // Copy the fragment that we'll need to restore in Undo
5247 CopyFragment(range
, action
->GetOldParagraphs());
5249 // See if we're deleting a paragraph marker, in which case we need to
5250 // make a note not to copy the attributes from the 2nd paragraph to the 1st.
5251 if (range
.GetStart() == range
.GetEnd())
5253 wxRichTextParagraph
* para
= GetParagraphAtPosition(range
.GetStart());
5254 if (para
&& para
->GetRange().GetEnd() == range
.GetEnd())
5256 wxRichTextParagraph
* nextPara
= GetParagraphAtPosition(range
.GetStart()+1);
5257 if (nextPara
&& nextPara
!= para
)
5259 action
->GetOldParagraphs().GetChildren().GetFirst()->GetData()->SetAttributes(nextPara
->GetAttributes());
5260 action
->GetOldParagraphs().GetAttributes().SetFlags(action
->GetOldParagraphs().GetAttributes().GetFlags() | wxTEXT_ATTR_KEEP_FIRST_PARA_STYLE
);
5265 SubmitAction(action
);
5270 /// Collapse undo/redo commands
5271 bool wxRichTextBuffer::BeginBatchUndo(const wxString
& cmdName
)
5273 if (m_batchedCommandDepth
== 0)
5275 wxASSERT(m_batchedCommand
== NULL
);
5276 if (m_batchedCommand
)
5278 GetCommandProcessor()->Store(m_batchedCommand
);
5280 m_batchedCommand
= new wxRichTextCommand(cmdName
);
5283 m_batchedCommandDepth
++;
5288 /// Collapse undo/redo commands
5289 bool wxRichTextBuffer::EndBatchUndo()
5291 m_batchedCommandDepth
--;
5293 wxASSERT(m_batchedCommandDepth
>= 0);
5294 wxASSERT(m_batchedCommand
!= NULL
);
5296 if (m_batchedCommandDepth
== 0)
5298 GetCommandProcessor()->Store(m_batchedCommand
);
5299 m_batchedCommand
= NULL
;
5305 /// Submit immediately, or delay according to whether collapsing is on
5306 bool wxRichTextBuffer::SubmitAction(wxRichTextAction
* action
)
5308 if (BatchingUndo() && m_batchedCommand
&& !SuppressingUndo())
5310 wxRichTextCommand
* cmd
= new wxRichTextCommand(action
->GetName());
5311 cmd
->AddAction(action
);
5313 cmd
->GetActions().Clear();
5316 m_batchedCommand
->AddAction(action
);
5320 wxRichTextCommand
* cmd
= new wxRichTextCommand(action
->GetName());
5321 cmd
->AddAction(action
);
5323 // Only store it if we're not suppressing undo.
5324 return GetCommandProcessor()->Submit(cmd
, !SuppressingUndo());
5330 /// Begin suppressing undo/redo commands.
5331 bool wxRichTextBuffer::BeginSuppressUndo()
5338 /// End suppressing undo/redo commands.
5339 bool wxRichTextBuffer::EndSuppressUndo()
5346 /// Begin using a style
5347 bool wxRichTextBuffer::BeginStyle(const wxTextAttr
& style
)
5349 wxTextAttr
newStyle(GetDefaultStyle());
5351 // Save the old default style
5352 m_attributeStack
.Append((wxObject
*) new wxTextAttr(GetDefaultStyle()));
5354 wxRichTextApplyStyle(newStyle
, style
);
5355 newStyle
.SetFlags(style
.GetFlags()|newStyle
.GetFlags());
5357 SetDefaultStyle(newStyle
);
5359 // wxLogDebug("Default style size = %d", GetDefaultStyle().GetFont().GetPointSize());
5365 bool wxRichTextBuffer::EndStyle()
5367 if (!m_attributeStack
.GetFirst())
5369 wxLogDebug(_("Too many EndStyle calls!"));
5373 wxList::compatibility_iterator node
= m_attributeStack
.GetLast();
5374 wxTextAttr
* attr
= (wxTextAttr
*)node
->GetData();
5375 m_attributeStack
.Erase(node
);
5377 SetDefaultStyle(*attr
);
5384 bool wxRichTextBuffer::EndAllStyles()
5386 while (m_attributeStack
.GetCount() != 0)
5391 /// Clear the style stack
5392 void wxRichTextBuffer::ClearStyleStack()
5394 for (wxList::compatibility_iterator node
= m_attributeStack
.GetFirst(); node
; node
= node
->GetNext())
5395 delete (wxTextAttr
*) node
->GetData();
5396 m_attributeStack
.Clear();
5399 /// Begin using bold
5400 bool wxRichTextBuffer::BeginBold()
5403 attr
.SetFontWeight(wxBOLD
);
5405 return BeginStyle(attr
);
5408 /// Begin using italic
5409 bool wxRichTextBuffer::BeginItalic()
5412 attr
.SetFontStyle(wxITALIC
);
5414 return BeginStyle(attr
);
5417 /// Begin using underline
5418 bool wxRichTextBuffer::BeginUnderline()
5421 attr
.SetFontUnderlined(true);
5423 return BeginStyle(attr
);
5426 /// Begin using point size
5427 bool wxRichTextBuffer::BeginFontSize(int pointSize
)
5430 attr
.SetFontSize(pointSize
);
5432 return BeginStyle(attr
);
5435 /// Begin using this font
5436 bool wxRichTextBuffer::BeginFont(const wxFont
& font
)
5441 return BeginStyle(attr
);
5444 /// Begin using this colour
5445 bool wxRichTextBuffer::BeginTextColour(const wxColour
& colour
)
5448 attr
.SetFlags(wxTEXT_ATTR_TEXT_COLOUR
);
5449 attr
.SetTextColour(colour
);
5451 return BeginStyle(attr
);
5454 /// Begin using alignment
5455 bool wxRichTextBuffer::BeginAlignment(wxTextAttrAlignment alignment
)
5458 attr
.SetFlags(wxTEXT_ATTR_ALIGNMENT
);
5459 attr
.SetAlignment(alignment
);
5461 return BeginStyle(attr
);
5464 /// Begin left indent
5465 bool wxRichTextBuffer::BeginLeftIndent(int leftIndent
, int leftSubIndent
)
5468 attr
.SetFlags(wxTEXT_ATTR_LEFT_INDENT
);
5469 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5471 return BeginStyle(attr
);
5474 /// Begin right indent
5475 bool wxRichTextBuffer::BeginRightIndent(int rightIndent
)
5478 attr
.SetFlags(wxTEXT_ATTR_RIGHT_INDENT
);
5479 attr
.SetRightIndent(rightIndent
);
5481 return BeginStyle(attr
);
5484 /// Begin paragraph spacing
5485 bool wxRichTextBuffer::BeginParagraphSpacing(int before
, int after
)
5489 flags
|= wxTEXT_ATTR_PARA_SPACING_BEFORE
;
5491 flags
|= wxTEXT_ATTR_PARA_SPACING_AFTER
;
5494 attr
.SetFlags(flags
);
5495 attr
.SetParagraphSpacingBefore(before
);
5496 attr
.SetParagraphSpacingAfter(after
);
5498 return BeginStyle(attr
);
5501 /// Begin line spacing
5502 bool wxRichTextBuffer::BeginLineSpacing(int lineSpacing
)
5505 attr
.SetFlags(wxTEXT_ATTR_LINE_SPACING
);
5506 attr
.SetLineSpacing(lineSpacing
);
5508 return BeginStyle(attr
);
5511 /// Begin numbered bullet
5512 bool wxRichTextBuffer::BeginNumberedBullet(int bulletNumber
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5515 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5516 attr
.SetBulletStyle(bulletStyle
);
5517 attr
.SetBulletNumber(bulletNumber
);
5518 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5520 return BeginStyle(attr
);
5523 /// Begin symbol bullet
5524 bool wxRichTextBuffer::BeginSymbolBullet(const wxString
& symbol
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5527 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5528 attr
.SetBulletStyle(bulletStyle
);
5529 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5530 attr
.SetBulletText(symbol
);
5532 return BeginStyle(attr
);
5535 /// Begin standard bullet
5536 bool wxRichTextBuffer::BeginStandardBullet(const wxString
& bulletName
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5539 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5540 attr
.SetBulletStyle(bulletStyle
);
5541 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5542 attr
.SetBulletName(bulletName
);
5544 return BeginStyle(attr
);
5547 /// Begin named character style
5548 bool wxRichTextBuffer::BeginCharacterStyle(const wxString
& characterStyle
)
5550 if (GetStyleSheet())
5552 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterStyle
);
5555 wxTextAttr attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5556 return BeginStyle(attr
);
5562 /// Begin named paragraph style
5563 bool wxRichTextBuffer::BeginParagraphStyle(const wxString
& paragraphStyle
)
5565 if (GetStyleSheet())
5567 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(paragraphStyle
);
5570 wxTextAttr attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5571 return BeginStyle(attr
);
5577 /// Begin named list style
5578 bool wxRichTextBuffer::BeginListStyle(const wxString
& listStyle
, int level
, int number
)
5580 if (GetStyleSheet())
5582 wxRichTextListStyleDefinition
* def
= GetStyleSheet()->FindListStyle(listStyle
);
5585 wxTextAttr
attr(def
->GetCombinedStyleForLevel(level
));
5587 attr
.SetBulletNumber(number
);
5589 return BeginStyle(attr
);
5596 bool wxRichTextBuffer::BeginURL(const wxString
& url
, const wxString
& characterStyle
)
5600 if (!characterStyle
.IsEmpty() && GetStyleSheet())
5602 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterStyle
);
5605 attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5610 return BeginStyle(attr
);
5613 /// Adds a handler to the end
5614 void wxRichTextBuffer::AddHandler(wxRichTextFileHandler
*handler
)
5616 sm_handlers
.Append(handler
);
5619 /// Inserts a handler at the front
5620 void wxRichTextBuffer::InsertHandler(wxRichTextFileHandler
*handler
)
5622 sm_handlers
.Insert( handler
);
5625 /// Removes a handler
5626 bool wxRichTextBuffer::RemoveHandler(const wxString
& name
)
5628 wxRichTextFileHandler
*handler
= FindHandler(name
);
5631 sm_handlers
.DeleteObject(handler
);
5639 /// Finds a handler by filename or, if supplied, type
5640 wxRichTextFileHandler
*wxRichTextBuffer::FindHandlerFilenameOrType(const wxString
& filename
, int imageType
)
5642 if (imageType
!= wxRICHTEXT_TYPE_ANY
)
5643 return FindHandler(imageType
);
5644 else if (!filename
.IsEmpty())
5646 wxString path
, file
, ext
;
5647 wxSplitPath(filename
, & path
, & file
, & ext
);
5648 return FindHandler(ext
, imageType
);
5655 /// Finds a handler by name
5656 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(const wxString
& name
)
5658 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5661 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5662 if (handler
->GetName().Lower() == name
.Lower()) return handler
;
5664 node
= node
->GetNext();
5669 /// Finds a handler by extension and type
5670 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(const wxString
& extension
, int type
)
5672 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5675 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5676 if ( handler
->GetExtension().Lower() == extension
.Lower() &&
5677 (type
== wxRICHTEXT_TYPE_ANY
|| handler
->GetType() == type
) )
5679 node
= node
->GetNext();
5684 /// Finds a handler by type
5685 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(int type
)
5687 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5690 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5691 if (handler
->GetType() == type
) return handler
;
5692 node
= node
->GetNext();
5697 void wxRichTextBuffer::InitStandardHandlers()
5699 if (!FindHandler(wxRICHTEXT_TYPE_TEXT
))
5700 AddHandler(new wxRichTextPlainTextHandler
);
5703 void wxRichTextBuffer::CleanUpHandlers()
5705 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5708 wxRichTextFileHandler
* handler
= (wxRichTextFileHandler
*)node
->GetData();
5709 wxList::compatibility_iterator next
= node
->GetNext();
5714 sm_handlers
.Clear();
5717 wxString
wxRichTextBuffer::GetExtWildcard(bool combine
, bool save
, wxArrayInt
* types
)
5724 wxList::compatibility_iterator node
= GetHandlers().GetFirst();
5728 wxRichTextFileHandler
* handler
= (wxRichTextFileHandler
*) node
->GetData();
5729 if (handler
->IsVisible() && ((save
&& handler
->CanSave()) || !save
&& handler
->CanLoad()))
5734 wildcard
+= wxT(";");
5735 wildcard
+= wxT("*.") + handler
->GetExtension();
5740 wildcard
+= wxT("|");
5741 wildcard
+= handler
->GetName();
5742 wildcard
+= wxT(" ");
5743 wildcard
+= _("files");
5744 wildcard
+= wxT(" (*.");
5745 wildcard
+= handler
->GetExtension();
5746 wildcard
+= wxT(")|*.");
5747 wildcard
+= handler
->GetExtension();
5749 types
->Add(handler
->GetType());
5754 node
= node
->GetNext();
5758 wildcard
= wxT("(") + wildcard
+ wxT(")|") + wildcard
;
5763 bool wxRichTextBuffer::LoadFile(const wxString
& filename
, int type
)
5765 wxRichTextFileHandler
* handler
= FindHandlerFilenameOrType(filename
, type
);
5768 SetDefaultStyle(wxTextAttr());
5769 handler
->SetFlags(GetHandlerFlags());
5770 bool success
= handler
->LoadFile(this, filename
);
5771 Invalidate(wxRICHTEXT_ALL
);
5779 bool wxRichTextBuffer::SaveFile(const wxString
& filename
, int type
)
5781 wxRichTextFileHandler
* handler
= FindHandlerFilenameOrType(filename
, type
);
5784 handler
->SetFlags(GetHandlerFlags());
5785 return handler
->SaveFile(this, filename
);
5791 /// Load from a stream
5792 bool wxRichTextBuffer::LoadFile(wxInputStream
& stream
, int type
)
5794 wxRichTextFileHandler
* handler
= FindHandler(type
);
5797 SetDefaultStyle(wxTextAttr());
5798 handler
->SetFlags(GetHandlerFlags());
5799 bool success
= handler
->LoadFile(this, stream
);
5800 Invalidate(wxRICHTEXT_ALL
);
5807 /// Save to a stream
5808 bool wxRichTextBuffer::SaveFile(wxOutputStream
& stream
, int type
)
5810 wxRichTextFileHandler
* handler
= FindHandler(type
);
5813 handler
->SetFlags(GetHandlerFlags());
5814 return handler
->SaveFile(this, stream
);
5820 /// Copy the range to the clipboard
5821 bool wxRichTextBuffer::CopyToClipboard(const wxRichTextRange
& range
)
5823 bool success
= false;
5824 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5826 if (!wxTheClipboard
->IsOpened() && wxTheClipboard
->Open())
5828 wxTheClipboard
->Clear();
5830 // Add composite object
5832 wxDataObjectComposite
* compositeObject
= new wxDataObjectComposite();
5835 wxString text
= GetTextForRange(range
);
5838 text
= wxTextFile::Translate(text
, wxTextFileType_Dos
);
5841 compositeObject
->Add(new wxTextDataObject(text
), false /* not preferred */);
5844 // Add rich text buffer data object. This needs the XML handler to be present.
5846 if (FindHandler(wxRICHTEXT_TYPE_XML
))
5848 wxRichTextBuffer
* richTextBuf
= new wxRichTextBuffer
;
5849 CopyFragment(range
, *richTextBuf
);
5851 compositeObject
->Add(new wxRichTextBufferDataObject(richTextBuf
), true /* preferred */);
5854 if (wxTheClipboard
->SetData(compositeObject
))
5857 wxTheClipboard
->Close();
5866 /// Paste the clipboard content to the buffer
5867 bool wxRichTextBuffer::PasteFromClipboard(long position
)
5869 bool success
= false;
5870 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5871 if (CanPasteFromClipboard())
5873 if (wxTheClipboard
->Open())
5875 if (wxTheClipboard
->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())))
5877 wxRichTextBufferDataObject data
;
5878 wxTheClipboard
->GetData(data
);
5879 wxRichTextBuffer
* richTextBuffer
= data
.GetRichTextBuffer();
5882 InsertParagraphsWithUndo(position
+1, *richTextBuffer
, GetRichTextCtrl(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
);
5883 if (GetRichTextCtrl())
5884 GetRichTextCtrl()->ShowPosition(position
+ richTextBuffer
->GetRange().GetEnd());
5885 delete richTextBuffer
;
5888 else if (wxTheClipboard
->IsSupported(wxDF_TEXT
) || wxTheClipboard
->IsSupported(wxDF_UNICODETEXT
))
5890 wxTextDataObject data
;
5891 wxTheClipboard
->GetData(data
);
5892 wxString
text(data
.GetText());
5895 text2
.Alloc(text
.Length()+1);
5897 for (i
= 0; i
< text
.Length(); i
++)
5899 wxChar ch
= text
[i
];
5900 if (ch
!= wxT('\r'))
5904 wxString text2
= text
;
5906 InsertTextWithUndo(position
+1, text2
, GetRichTextCtrl());
5908 if (GetRichTextCtrl())
5909 GetRichTextCtrl()->ShowPosition(position
+ text2
.Length());
5913 else if (wxTheClipboard
->IsSupported(wxDF_BITMAP
))
5915 wxBitmapDataObject data
;
5916 wxTheClipboard
->GetData(data
);
5917 wxBitmap
bitmap(data
.GetBitmap());
5918 wxImage
image(bitmap
.ConvertToImage());
5920 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Image"), wxRICHTEXT_INSERT
, this, GetRichTextCtrl(), false);
5922 action
->GetNewParagraphs().AddImage(image
);
5924 if (action
->GetNewParagraphs().GetChildCount() == 1)
5925 action
->GetNewParagraphs().SetPartialParagraph(true);
5927 action
->SetPosition(position
);
5929 // Set the range we'll need to delete in Undo
5930 action
->SetRange(wxRichTextRange(position
, position
));
5932 SubmitAction(action
);
5936 wxTheClipboard
->Close();
5940 wxUnusedVar(position
);
5945 /// Can we paste from the clipboard?
5946 bool wxRichTextBuffer::CanPasteFromClipboard() const
5948 bool canPaste
= false;
5949 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5950 if (!wxTheClipboard
->IsOpened() && wxTheClipboard
->Open())
5952 if (wxTheClipboard
->IsSupported(wxDF_TEXT
) || wxTheClipboard
->IsSupported(wxDF_UNICODETEXT
) ||
5953 wxTheClipboard
->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())) ||
5954 wxTheClipboard
->IsSupported(wxDF_BITMAP
))
5958 wxTheClipboard
->Close();
5964 /// Dumps contents of buffer for debugging purposes
5965 void wxRichTextBuffer::Dump()
5969 wxStringOutputStream
stream(& text
);
5970 wxTextOutputStream
textStream(stream
);
5977 /// Add an event handler
5978 bool wxRichTextBuffer::AddEventHandler(wxEvtHandler
* handler
)
5980 m_eventHandlers
.Append(handler
);
5984 /// Remove an event handler
5985 bool wxRichTextBuffer::RemoveEventHandler(wxEvtHandler
* handler
, bool deleteHandler
)
5987 wxList::compatibility_iterator node
= m_eventHandlers
.Find(handler
);
5990 m_eventHandlers
.Erase(node
);
6000 /// Clear event handlers
6001 void wxRichTextBuffer::ClearEventHandlers()
6003 m_eventHandlers
.Clear();
6006 /// Send event to event handlers. If sendToAll is true, will send to all event handlers,
6007 /// otherwise will stop at the first successful one.
6008 bool wxRichTextBuffer::SendEvent(wxEvent
& event
, bool sendToAll
)
6010 bool success
= false;
6011 for (wxList::compatibility_iterator node
= m_eventHandlers
.GetFirst(); node
; node
= node
->GetNext())
6013 wxEvtHandler
* handler
= (wxEvtHandler
*) node
->GetData();
6014 if (handler
->ProcessEvent(event
))
6024 /// Set style sheet and notify of the change
6025 bool wxRichTextBuffer::SetStyleSheetAndNotify(wxRichTextStyleSheet
* sheet
)
6027 wxRichTextStyleSheet
* oldSheet
= GetStyleSheet();
6029 wxWindowID id
= wxID_ANY
;
6030 if (GetRichTextCtrl())
6031 id
= GetRichTextCtrl()->GetId();
6033 wxRichTextEvent
event(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING
, id
);
6034 event
.SetEventObject(GetRichTextCtrl());
6035 event
.SetOldStyleSheet(oldSheet
);
6036 event
.SetNewStyleSheet(sheet
);
6039 if (SendEvent(event
) && !event
.IsAllowed())
6041 if (sheet
!= oldSheet
)
6047 if (oldSheet
&& oldSheet
!= sheet
)
6050 SetStyleSheet(sheet
);
6052 event
.SetEventType(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED
);
6053 event
.SetOldStyleSheet(NULL
);
6056 return SendEvent(event
);
6059 /// Set renderer, deleting old one
6060 void wxRichTextBuffer::SetRenderer(wxRichTextRenderer
* renderer
)
6064 sm_renderer
= renderer
;
6067 bool wxRichTextStdRenderer::DrawStandardBullet(wxRichTextParagraph
* paragraph
, wxDC
& dc
, const wxTextAttr
& bulletAttr
, const wxRect
& rect
)
6069 if (bulletAttr
.GetTextColour().Ok())
6071 wxCheckSetPen(dc
, wxPen(bulletAttr
.GetTextColour()));
6072 wxCheckSetBrush(dc
, wxBrush(bulletAttr
.GetTextColour()));
6076 wxCheckSetPen(dc
, *wxBLACK_PEN
);
6077 wxCheckSetBrush(dc
, *wxBLACK_BRUSH
);
6081 if (bulletAttr
.HasFont())
6083 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(bulletAttr
);
6086 font
= (*wxNORMAL_FONT
);
6088 wxCheckSetFont(dc
, font
);
6090 int charHeight
= dc
.GetCharHeight();
6092 int bulletWidth
= (int) (((float) charHeight
) * wxRichTextBuffer::GetBulletProportion());
6093 int bulletHeight
= bulletWidth
;
6097 // Calculate the top position of the character (as opposed to the whole line height)
6098 int y
= rect
.y
+ (rect
.height
- charHeight
);
6100 // Calculate where the bullet should be positioned
6101 y
= y
+ (charHeight
+1)/2 - (bulletHeight
+1)/2;
6103 // The margin between a bullet and text.
6104 int margin
= paragraph
->ConvertTenthsMMToPixels(dc
, wxRichTextBuffer::GetBulletRightMargin());
6106 if (bulletAttr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT
)
6107 x
= rect
.x
+ rect
.width
- bulletWidth
- margin
;
6108 else if (bulletAttr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE
)
6109 x
= x
+ (rect
.width
)/2 - bulletWidth
/2;
6111 if (bulletAttr
.GetBulletName() == wxT("standard/square"))
6113 dc
.DrawRectangle(x
, y
, bulletWidth
, bulletHeight
);
6115 else if (bulletAttr
.GetBulletName() == wxT("standard/diamond"))
6118 pts
[0].x
= x
; pts
[0].y
= y
+ bulletHeight
/2;
6119 pts
[1].x
= x
+ bulletWidth
/2; pts
[1].y
= y
;
6120 pts
[2].x
= x
+ bulletWidth
; pts
[2].y
= y
+ bulletHeight
/2;
6121 pts
[3].x
= x
+ bulletWidth
/2; pts
[3].y
= y
+ bulletHeight
;
6123 dc
.DrawPolygon(4, pts
);
6125 else if (bulletAttr
.GetBulletName() == wxT("standard/triangle"))
6128 pts
[0].x
= x
; pts
[0].y
= y
;
6129 pts
[1].x
= x
+ bulletWidth
; pts
[1].y
= y
+ bulletHeight
/2;
6130 pts
[2].x
= x
; pts
[2].y
= y
+ bulletHeight
;
6132 dc
.DrawPolygon(3, pts
);
6134 else // "standard/circle", and catch-all
6136 dc
.DrawEllipse(x
, y
, bulletWidth
, bulletHeight
);
6142 bool wxRichTextStdRenderer::DrawTextBullet(wxRichTextParagraph
* paragraph
, wxDC
& dc
, const wxTextAttr
& attr
, const wxRect
& rect
, const wxString
& text
)
6147 if ((attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL
) && !attr
.GetBulletFont().IsEmpty() && attr
.HasFont())
6149 wxTextAttr fontAttr
;
6150 fontAttr
.SetFontSize(attr
.GetFontSize());
6151 fontAttr
.SetFontStyle(attr
.GetFontStyle());
6152 fontAttr
.SetFontWeight(attr
.GetFontWeight());
6153 fontAttr
.SetFontUnderlined(attr
.GetFontUnderlined());
6154 fontAttr
.SetFontFaceName(attr
.GetBulletFont());
6155 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(fontAttr
);
6157 else if (attr
.HasFont())
6158 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(attr
);
6160 font
= (*wxNORMAL_FONT
);
6162 wxCheckSetFont(dc
, font
);
6164 if (attr
.GetTextColour().Ok())
6165 dc
.SetTextForeground(attr
.GetTextColour());
6167 dc
.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT
);
6169 int charHeight
= dc
.GetCharHeight();
6171 dc
.GetTextExtent(text
, & tw
, & th
);
6175 // Calculate the top position of the character (as opposed to the whole line height)
6176 int y
= rect
.y
+ (rect
.height
- charHeight
);
6178 // The margin between a bullet and text.
6179 int margin
= paragraph
->ConvertTenthsMMToPixels(dc
, wxRichTextBuffer::GetBulletRightMargin());
6181 if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT
)
6182 x
= (rect
.x
+ rect
.width
) - tw
- margin
;
6183 else if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE
)
6184 x
= x
+ (rect
.width
)/2 - tw
/2;
6186 dc
.DrawText(text
, x
, y
);
6194 bool wxRichTextStdRenderer::DrawBitmapBullet(wxRichTextParagraph
* WXUNUSED(paragraph
), wxDC
& WXUNUSED(dc
), const wxTextAttr
& WXUNUSED(attr
), const wxRect
& WXUNUSED(rect
))
6196 // Currently unimplemented. The intention is to store bitmaps by name in a media store associated
6197 // with the buffer. The store will allow retrieval from memory, disk or other means.
6201 /// Enumerate the standard bullet names currently supported
6202 bool wxRichTextStdRenderer::EnumerateStandardBulletNames(wxArrayString
& bulletNames
)
6204 bulletNames
.Add(wxT("standard/circle"));
6205 bulletNames
.Add(wxT("standard/square"));
6206 bulletNames
.Add(wxT("standard/diamond"));
6207 bulletNames
.Add(wxT("standard/triangle"));
6213 * Module to initialise and clean up handlers
6216 class wxRichTextModule
: public wxModule
6218 DECLARE_DYNAMIC_CLASS(wxRichTextModule
)
6220 wxRichTextModule() {}
6223 wxRichTextBuffer::SetRenderer(new wxRichTextStdRenderer
);
6224 wxRichTextBuffer::InitStandardHandlers();
6225 wxRichTextParagraph::InitDefaultTabs();
6230 wxRichTextBuffer::CleanUpHandlers();
6231 wxRichTextDecimalToRoman(-1);
6232 wxRichTextParagraph::ClearDefaultTabs();
6233 wxRichTextCtrl::ClearAvailableFontNames();
6234 wxRichTextBuffer::SetRenderer(NULL
);
6238 IMPLEMENT_DYNAMIC_CLASS(wxRichTextModule
, wxModule
)
6241 // If the richtext lib is dynamically loaded after the app has already started
6242 // (such as from wxPython) then the built-in module system will not init this
6243 // module. Provide this function to do it manually.
6244 void wxRichTextModuleInit()
6246 wxModule
* module = new wxRichTextModule
;
6248 wxModule::RegisterModule(module);
6253 * Commands for undo/redo
6257 wxRichTextCommand::wxRichTextCommand(const wxString
& name
, wxRichTextCommandId id
, wxRichTextBuffer
* buffer
,
6258 wxRichTextCtrl
* ctrl
, bool ignoreFirstTime
): wxCommand(true, name
)
6260 /* wxRichTextAction* action = */ new wxRichTextAction(this, name
, id
, buffer
, ctrl
, ignoreFirstTime
);
6263 wxRichTextCommand::wxRichTextCommand(const wxString
& name
): wxCommand(true, name
)
6267 wxRichTextCommand::~wxRichTextCommand()
6272 void wxRichTextCommand::AddAction(wxRichTextAction
* action
)
6274 if (!m_actions
.Member(action
))
6275 m_actions
.Append(action
);
6278 bool wxRichTextCommand::Do()
6280 for (wxList::compatibility_iterator node
= m_actions
.GetFirst(); node
; node
= node
->GetNext())
6282 wxRichTextAction
* action
= (wxRichTextAction
*) node
->GetData();
6289 bool wxRichTextCommand::Undo()
6291 for (wxList::compatibility_iterator node
= m_actions
.GetLast(); node
; node
= node
->GetPrevious())
6293 wxRichTextAction
* action
= (wxRichTextAction
*) node
->GetData();
6300 void wxRichTextCommand::ClearActions()
6302 WX_CLEAR_LIST(wxList
, m_actions
);
6310 wxRichTextAction::wxRichTextAction(wxRichTextCommand
* cmd
, const wxString
& name
, wxRichTextCommandId id
, wxRichTextBuffer
* buffer
,
6311 wxRichTextCtrl
* ctrl
, bool ignoreFirstTime
)
6314 m_ignoreThis
= ignoreFirstTime
;
6319 m_newParagraphs
.SetDefaultStyle(buffer
->GetDefaultStyle());
6320 m_newParagraphs
.SetBasicStyle(buffer
->GetBasicStyle());
6322 cmd
->AddAction(this);
6325 wxRichTextAction::~wxRichTextAction()
6329 bool wxRichTextAction::Do()
6331 m_buffer
->Modify(true);
6335 case wxRICHTEXT_INSERT
:
6337 // Store a list of line start character and y positions so we can figure out which area
6338 // we need to refresh
6339 wxArrayInt optimizationLineCharPositions
;
6340 wxArrayInt optimizationLineYPositions
;
6342 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6343 // NOTE: we're assuming that the buffer is laid out correctly at this point.
6344 // If we had several actions, which only invalidate and leave layout until the
6345 // paint handler is called, then this might not be true. So we may need to switch
6346 // optimisation on only when we're simply adding text and not simultaneously
6347 // deleting a selection, for example. Or, we make sure the buffer is laid out correctly
6348 // first, but of course this means we'll be doing it twice.
6349 if (!m_buffer
->GetDirty() && m_ctrl
) // can only do optimisation if the buffer is already laid out correctly
6351 wxSize clientSize
= m_ctrl
->GetClientSize();
6352 wxPoint firstVisiblePt
= m_ctrl
->GetFirstVisiblePoint();
6353 int lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6355 wxRichTextParagraph
* para
= m_buffer
->GetParagraphAtPosition(GetRange().GetStart());
6356 wxRichTextObjectList::compatibility_iterator node
= m_buffer
->GetChildren().Find(para
);
6359 wxRichTextParagraph
* child
= (wxRichTextParagraph
*) node
->GetData();
6360 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
6363 wxRichTextLine
* line
= node2
->GetData();
6364 wxPoint pt
= line
->GetAbsolutePosition();
6365 wxRichTextRange range
= line
->GetAbsoluteRange();
6369 node2
= wxRichTextLineList::compatibility_iterator();
6370 node
= wxRichTextObjectList::compatibility_iterator();
6372 else if (range
.GetStart() > GetPosition() && pt
.y
>= firstVisiblePt
.y
)
6374 optimizationLineCharPositions
.Add(range
.GetStart());
6375 optimizationLineYPositions
.Add(pt
.y
);
6379 node2
= node2
->GetNext();
6383 node
= node
->GetNext();
6388 m_buffer
->InsertFragment(GetRange().GetStart(), m_newParagraphs
);
6389 m_buffer
->UpdateRanges();
6390 m_buffer
->Invalidate(wxRichTextRange(wxMax(0, GetRange().GetStart()-1), GetRange().GetEnd()));
6392 long newCaretPosition
= GetPosition() + m_newParagraphs
.GetRange().GetLength();
6394 // Character position to caret position
6395 newCaretPosition
--;
6397 // Don't take into account the last newline
6398 if (m_newParagraphs
.GetPartialParagraph())
6399 newCaretPosition
--;
6401 if (m_newParagraphs
.GetChildren().GetCount() > 1)
6403 wxRichTextObject
* p
= (wxRichTextObject
*) m_newParagraphs
.GetChildren().GetLast()->GetData();
6404 if (p
->GetRange().GetLength() == 1)
6405 newCaretPosition
--;
6408 newCaretPosition
= wxMin(newCaretPosition
, (m_buffer
->GetRange().GetEnd()-1));
6410 if (optimizationLineCharPositions
.GetCount() > 0)
6411 UpdateAppearance(newCaretPosition
, true /* send update event */, & optimizationLineCharPositions
, & optimizationLineYPositions
);
6413 UpdateAppearance(newCaretPosition
, true /* send update event */);
6415 wxRichTextEvent
cmdEvent(
6416 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED
,
6417 m_ctrl
? m_ctrl
->GetId() : -1);
6418 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6419 cmdEvent
.SetRange(GetRange());
6420 cmdEvent
.SetPosition(GetRange().GetStart());
6422 m_buffer
->SendEvent(cmdEvent
);
6426 case wxRICHTEXT_DELETE
:
6428 m_buffer
->DeleteRange(GetRange());
6429 m_buffer
->UpdateRanges();
6430 m_buffer
->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6432 long caretPos
= GetRange().GetStart()-1;
6433 if (caretPos
>= m_buffer
->GetRange().GetEnd())
6436 UpdateAppearance(caretPos
, true /* send update event */);
6438 wxRichTextEvent
cmdEvent(
6439 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED
,
6440 m_ctrl
? m_ctrl
->GetId() : -1);
6441 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6442 cmdEvent
.SetRange(GetRange());
6443 cmdEvent
.SetPosition(GetRange().GetStart());
6445 m_buffer
->SendEvent(cmdEvent
);
6449 case wxRICHTEXT_CHANGE_STYLE
:
6451 ApplyParagraphs(GetNewParagraphs());
6452 m_buffer
->Invalidate(GetRange());
6454 UpdateAppearance(GetPosition());
6456 wxRichTextEvent
cmdEvent(
6457 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED
,
6458 m_ctrl
? m_ctrl
->GetId() : -1);
6459 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6460 cmdEvent
.SetRange(GetRange());
6461 cmdEvent
.SetPosition(GetRange().GetStart());
6463 m_buffer
->SendEvent(cmdEvent
);
6474 bool wxRichTextAction::Undo()
6476 m_buffer
->Modify(true);
6480 case wxRICHTEXT_INSERT
:
6482 m_buffer
->DeleteRange(GetRange());
6483 m_buffer
->UpdateRanges();
6484 m_buffer
->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6486 long newCaretPosition
= GetPosition() - 1;
6488 UpdateAppearance(newCaretPosition
, true /* send update event */);
6490 wxRichTextEvent
cmdEvent(
6491 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED
,
6492 m_ctrl
? m_ctrl
->GetId() : -1);
6493 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6494 cmdEvent
.SetRange(GetRange());
6495 cmdEvent
.SetPosition(GetRange().GetStart());
6497 m_buffer
->SendEvent(cmdEvent
);
6501 case wxRICHTEXT_DELETE
:
6503 m_buffer
->InsertFragment(GetRange().GetStart(), m_oldParagraphs
);
6504 m_buffer
->UpdateRanges();
6505 m_buffer
->Invalidate(GetRange());
6507 UpdateAppearance(GetPosition(), true /* send update event */);
6509 wxRichTextEvent
cmdEvent(
6510 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED
,
6511 m_ctrl
? m_ctrl
->GetId() : -1);
6512 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6513 cmdEvent
.SetRange(GetRange());
6514 cmdEvent
.SetPosition(GetRange().GetStart());
6516 m_buffer
->SendEvent(cmdEvent
);
6520 case wxRICHTEXT_CHANGE_STYLE
:
6522 ApplyParagraphs(GetOldParagraphs());
6523 m_buffer
->Invalidate(GetRange());
6525 UpdateAppearance(GetPosition());
6527 wxRichTextEvent
cmdEvent(
6528 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED
,
6529 m_ctrl
? m_ctrl
->GetId() : -1);
6530 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6531 cmdEvent
.SetRange(GetRange());
6532 cmdEvent
.SetPosition(GetRange().GetStart());
6534 m_buffer
->SendEvent(cmdEvent
);
6545 /// Update the control appearance
6546 void wxRichTextAction::UpdateAppearance(long caretPosition
, bool sendUpdateEvent
, wxArrayInt
* optimizationLineCharPositions
, wxArrayInt
* optimizationLineYPositions
)
6550 m_ctrl
->SetCaretPosition(caretPosition
);
6551 if (!m_ctrl
->IsFrozen())
6553 m_ctrl
->LayoutContent();
6554 m_ctrl
->PositionCaret();
6556 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6557 // Find refresh rectangle if we are in a position to optimise refresh
6558 if (m_cmdId
== wxRICHTEXT_INSERT
&& optimizationLineCharPositions
&& optimizationLineCharPositions
->GetCount() > 0)
6562 wxSize clientSize
= m_ctrl
->GetClientSize();
6563 wxPoint firstVisiblePt
= m_ctrl
->GetFirstVisiblePoint();
6565 // Start/end positions
6567 int lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6569 bool foundStart
= false;
6570 bool foundEnd
= false;
6572 // position offset - how many characters were inserted
6573 int positionOffset
= GetRange().GetLength();
6575 // find the first line which is being drawn at the same position as it was
6576 // before. Since we're talking about a simple insertion, we can assume
6577 // that the rest of the window does not need to be redrawn.
6579 wxRichTextParagraph
* para
= m_buffer
->GetParagraphAtPosition(GetPosition());
6580 wxRichTextObjectList::compatibility_iterator node
= m_buffer
->GetChildren().Find(para
);
6583 wxRichTextParagraph
* child
= (wxRichTextParagraph
*) node
->GetData();
6584 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
6587 wxRichTextLine
* line
= node2
->GetData();
6588 wxPoint pt
= line
->GetAbsolutePosition();
6589 wxRichTextRange range
= line
->GetAbsoluteRange();
6591 // we want to find the first line that is in the same position
6592 // as before. This will mean we're at the end of the changed text.
6594 if (pt
.y
> lastY
) // going past the end of the window, no more info
6596 node2
= wxRichTextLineList::compatibility_iterator();
6597 node
= wxRichTextObjectList::compatibility_iterator();
6603 firstY
= pt
.y
- firstVisiblePt
.y
;
6607 // search for this line being at the same position as before
6608 for (i
= 0; i
< optimizationLineCharPositions
->GetCount(); i
++)
6610 if (((*optimizationLineCharPositions
)[i
] + positionOffset
== range
.GetStart()) &&
6611 ((*optimizationLineYPositions
)[i
] == pt
.y
))
6613 // Stop, we're now the same as we were
6615 lastY
= pt
.y
- firstVisiblePt
.y
;
6617 node2
= wxRichTextLineList::compatibility_iterator();
6618 node
= wxRichTextObjectList::compatibility_iterator();
6626 node2
= node2
->GetNext();
6630 node
= node
->GetNext();
6634 firstY
= firstVisiblePt
.y
;
6636 lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6638 wxRect
rect(firstVisiblePt
.x
, firstY
, firstVisiblePt
.x
+ clientSize
.x
, lastY
- firstY
);
6639 m_ctrl
->RefreshRect(rect
);
6641 // TODO: we need to make sure that lines are only drawn if in the update region. The rect
6642 // passed to Draw is currently used in different ways (to pass the position the content should
6643 // be drawn at as well as the relevant region).
6647 m_ctrl
->Refresh(false);
6649 if (sendUpdateEvent
)
6650 wxTextCtrl::SendTextUpdatedEvent(m_ctrl
);
6655 /// Replace the buffer paragraphs with the new ones.
6656 void wxRichTextAction::ApplyParagraphs(const wxRichTextParagraphLayoutBox
& fragment
)
6658 wxRichTextObjectList::compatibility_iterator node
= fragment
.GetChildren().GetFirst();
6661 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
6662 wxASSERT (para
!= NULL
);
6664 // We'll replace the existing paragraph by finding the paragraph at this position,
6665 // delete its node data, and setting a copy as the new node data.
6666 // TODO: make more efficient by simply swapping old and new paragraph objects.
6668 wxRichTextParagraph
* existingPara
= m_buffer
->GetParagraphAtPosition(para
->GetRange().GetStart());
6671 wxRichTextObjectList::compatibility_iterator bufferParaNode
= m_buffer
->GetChildren().Find(existingPara
);
6674 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(*para
);
6675 newPara
->SetParent(m_buffer
);
6677 bufferParaNode
->SetData(newPara
);
6679 delete existingPara
;
6683 node
= node
->GetNext();
6690 * This stores beginning and end positions for a range of data.
6693 /// Limit this range to be within 'range'
6694 bool wxRichTextRange::LimitTo(const wxRichTextRange
& range
)
6696 if (m_start
< range
.m_start
)
6697 m_start
= range
.m_start
;
6699 if (m_end
> range
.m_end
)
6700 m_end
= range
.m_end
;
6706 * wxRichTextImage implementation
6707 * This object represents an image.
6710 IMPLEMENT_DYNAMIC_CLASS(wxRichTextImage
, wxRichTextObject
)
6712 wxRichTextImage::wxRichTextImage(const wxImage
& image
, wxRichTextObject
* parent
, wxTextAttr
* charStyle
):
6713 wxRichTextObject(parent
)
6717 SetAttributes(*charStyle
);
6720 wxRichTextImage::wxRichTextImage(const wxRichTextImageBlock
& imageBlock
, wxRichTextObject
* parent
, wxTextAttr
* charStyle
):
6721 wxRichTextObject(parent
)
6723 m_imageBlock
= imageBlock
;
6724 m_imageBlock
.Load(m_image
);
6726 SetAttributes(*charStyle
);
6729 /// Load wxImage from the block
6730 bool wxRichTextImage::LoadFromBlock()
6732 m_imageBlock
.Load(m_image
);
6733 return m_imageBlock
.Ok();
6736 /// Make block from the wxImage
6737 bool wxRichTextImage::MakeBlock()
6739 if (m_imageBlock
.GetImageType() == wxBITMAP_TYPE_ANY
|| m_imageBlock
.GetImageType() == -1)
6740 m_imageBlock
.SetImageType(wxBITMAP_TYPE_PNG
);
6742 m_imageBlock
.MakeImageBlock(m_image
, m_imageBlock
.GetImageType());
6743 return m_imageBlock
.Ok();
6748 bool wxRichTextImage::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int WXUNUSED(descent
), int WXUNUSED(style
))
6750 if (!m_image
.Ok() && m_imageBlock
.Ok())
6756 if (m_image
.Ok() && !m_bitmap
.Ok())
6757 m_bitmap
= wxBitmap(m_image
);
6759 int y
= rect
.y
+ (rect
.height
- m_image
.GetHeight());
6762 dc
.DrawBitmap(m_bitmap
, rect
.x
, y
, true);
6764 if (selectionRange
.Contains(range
.GetStart()))
6766 wxCheckSetBrush(dc
, *wxBLACK_BRUSH
);
6767 wxCheckSetPen(dc
, *wxBLACK_PEN
);
6768 dc
.SetLogicalFunction(wxINVERT
);
6769 dc
.DrawRectangle(rect
);
6770 dc
.SetLogicalFunction(wxCOPY
);
6776 /// Lay the item out
6777 bool wxRichTextImage::Layout(wxDC
& WXUNUSED(dc
), const wxRect
& rect
, int WXUNUSED(style
))
6784 SetCachedSize(wxSize(m_image
.GetWidth(), m_image
.GetHeight()));
6785 SetPosition(rect
.GetPosition());
6791 /// Get/set the object size for the given range. Returns false if the range
6792 /// is invalid for this object.
6793 bool wxRichTextImage::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& WXUNUSED(descent
), wxDC
& WXUNUSED(dc
), int WXUNUSED(flags
), wxPoint
WXUNUSED(position
), wxArrayInt
* partialExtents
) const
6795 if (!range
.IsWithin(GetRange()))
6801 partialExtents
->Add(m_image
.GetWidth());
6803 partialExtents
->Add(0);
6809 size
.x
= m_image
.GetWidth();
6810 size
.y
= m_image
.GetHeight();
6816 void wxRichTextImage::Copy(const wxRichTextImage
& obj
)
6818 wxRichTextObject::Copy(obj
);
6820 m_image
= obj
.m_image
;
6821 m_imageBlock
= obj
.m_imageBlock
;
6829 /// Compare two attribute objects
6830 bool wxTextAttrEq(const wxTextAttr
& attr1
, const wxTextAttr
& attr2
)
6832 return (attr1
== attr2
);
6835 // Partial equality test taking flags into account
6836 bool wxTextAttrEqPartial(const wxTextAttr
& attr1
, const wxTextAttr
& attr2
, int flags
)
6838 return attr1
.EqPartial(attr2
, flags
);
6842 bool wxRichTextTabsEq(const wxArrayInt
& tabs1
, const wxArrayInt
& tabs2
)
6844 if (tabs1
.GetCount() != tabs2
.GetCount())
6848 for (i
= 0; i
< tabs1
.GetCount(); i
++)
6850 if (tabs1
[i
] != tabs2
[i
])
6856 bool wxRichTextApplyStyle(wxTextAttr
& destStyle
, const wxTextAttr
& style
, wxTextAttr
* compareWith
)
6858 return destStyle
.Apply(style
, compareWith
);
6861 // Remove attributes
6862 bool wxRichTextRemoveStyle(wxTextAttr
& destStyle
, const wxTextAttr
& style
)
6864 return wxTextAttr::RemoveStyle(destStyle
, style
);
6867 /// Combine two bitlists, specifying the bits of interest with separate flags.
6868 bool wxRichTextCombineBitlists(int& valueA
, int valueB
, int& flagsA
, int flagsB
)
6870 return wxTextAttr::CombineBitlists(valueA
, valueB
, flagsA
, flagsB
);
6873 /// Compare two bitlists
6874 bool wxRichTextBitlistsEqPartial(int valueA
, int valueB
, int flags
)
6876 return wxTextAttr::BitlistsEqPartial(valueA
, valueB
, flags
);
6879 /// Split into paragraph and character styles
6880 bool wxRichTextSplitParaCharStyles(const wxTextAttr
& style
, wxTextAttr
& parStyle
, wxTextAttr
& charStyle
)
6882 return wxTextAttr::SplitParaCharStyles(style
, parStyle
, charStyle
);
6885 /// Convert a decimal to Roman numerals
6886 wxString
wxRichTextDecimalToRoman(long n
)
6888 static wxArrayInt decimalNumbers
;
6889 static wxArrayString romanNumbers
;
6894 decimalNumbers
.Clear();
6895 romanNumbers
.Clear();
6896 return wxEmptyString
;
6899 if (decimalNumbers
.GetCount() == 0)
6901 #define wxRichTextAddDecRom(n, r) decimalNumbers.Add(n); romanNumbers.Add(r);
6903 wxRichTextAddDecRom(1000, wxT("M"));
6904 wxRichTextAddDecRom(900, wxT("CM"));
6905 wxRichTextAddDecRom(500, wxT("D"));
6906 wxRichTextAddDecRom(400, wxT("CD"));
6907 wxRichTextAddDecRom(100, wxT("C"));
6908 wxRichTextAddDecRom(90, wxT("XC"));
6909 wxRichTextAddDecRom(50, wxT("L"));
6910 wxRichTextAddDecRom(40, wxT("XL"));
6911 wxRichTextAddDecRom(10, wxT("X"));
6912 wxRichTextAddDecRom(9, wxT("IX"));
6913 wxRichTextAddDecRom(5, wxT("V"));
6914 wxRichTextAddDecRom(4, wxT("IV"));
6915 wxRichTextAddDecRom(1, wxT("I"));
6921 while (n
> 0 && i
< 13)
6923 if (n
>= decimalNumbers
[i
])
6925 n
-= decimalNumbers
[i
];
6926 roman
+= romanNumbers
[i
];
6933 if (roman
.IsEmpty())
6939 * wxRichTextFileHandler
6940 * Base class for file handlers
6943 IMPLEMENT_CLASS(wxRichTextFileHandler
, wxObject
)
6945 #if wxUSE_FFILE && wxUSE_STREAMS
6946 bool wxRichTextFileHandler::LoadFile(wxRichTextBuffer
*buffer
, const wxString
& filename
)
6948 wxFFileInputStream
stream(filename
);
6950 return LoadFile(buffer
, stream
);
6955 bool wxRichTextFileHandler::SaveFile(wxRichTextBuffer
*buffer
, const wxString
& filename
)
6957 wxFFileOutputStream
stream(filename
);
6959 return SaveFile(buffer
, stream
);
6963 #endif // wxUSE_FFILE && wxUSE_STREAMS
6965 /// Can we handle this filename (if using files)? By default, checks the extension.
6966 bool wxRichTextFileHandler::CanHandle(const wxString
& filename
) const
6968 wxString path
, file
, ext
;
6969 wxSplitPath(filename
, & path
, & file
, & ext
);
6971 return (ext
.Lower() == GetExtension());
6975 * wxRichTextTextHandler
6976 * Plain text handler
6979 IMPLEMENT_CLASS(wxRichTextPlainTextHandler
, wxRichTextFileHandler
)
6982 bool wxRichTextPlainTextHandler::DoLoadFile(wxRichTextBuffer
*buffer
, wxInputStream
& stream
)
6990 while (!stream
.Eof())
6992 int ch
= stream
.GetC();
6996 if (ch
== 10 && lastCh
!= 13)
6999 if (ch
> 0 && ch
!= 10)
7006 buffer
->ResetAndClearCommands();
7008 buffer
->AddParagraphs(str
);
7009 buffer
->UpdateRanges();
7014 bool wxRichTextPlainTextHandler::DoSaveFile(wxRichTextBuffer
*buffer
, wxOutputStream
& stream
)
7019 wxString text
= buffer
->GetText();
7021 wxString newLine
= wxRichTextLineBreakChar
;
7022 text
.Replace(newLine
, wxT("\n"));
7024 wxCharBuffer buf
= text
.ToAscii();
7026 stream
.Write((const char*) buf
, text
.length());
7029 #endif // wxUSE_STREAMS
7032 * Stores information about an image, in binary in-memory form
7035 wxRichTextImageBlock::wxRichTextImageBlock()
7040 wxRichTextImageBlock::wxRichTextImageBlock(const wxRichTextImageBlock
& block
):wxObject()
7046 wxRichTextImageBlock::~wxRichTextImageBlock()
7055 void wxRichTextImageBlock::Init()
7062 void wxRichTextImageBlock::Clear()
7071 // Load the original image into a memory block.
7072 // If the image is not a JPEG, we must convert it into a JPEG
7073 // to conserve space.
7074 // If it's not a JPEG we can make use of 'image', already scaled, so we don't have to
7075 // load the image a 2nd time.
7077 bool wxRichTextImageBlock::MakeImageBlock(const wxString
& filename
, int imageType
, wxImage
& image
, bool convertToJPEG
)
7079 m_imageType
= imageType
;
7081 wxString
filenameToRead(filename
);
7082 bool removeFile
= false;
7084 if (imageType
== -1)
7085 return false; // Could not determine image type
7087 if ((imageType
!= wxBITMAP_TYPE_JPEG
) && convertToJPEG
)
7090 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
7094 wxUnusedVar(success
);
7096 image
.SaveFile(tempFile
, wxBITMAP_TYPE_JPEG
);
7097 filenameToRead
= tempFile
;
7100 m_imageType
= wxBITMAP_TYPE_JPEG
;
7103 if (!file
.Open(filenameToRead
))
7106 m_dataSize
= (size_t) file
.Length();
7111 m_data
= ReadBlock(filenameToRead
, m_dataSize
);
7114 wxRemoveFile(filenameToRead
);
7116 return (m_data
!= NULL
);
7119 // Make an image block from the wxImage in the given
7121 bool wxRichTextImageBlock::MakeImageBlock(wxImage
& image
, int imageType
, int quality
)
7123 m_imageType
= imageType
;
7124 image
.SetOption(wxT("quality"), quality
);
7126 if (imageType
== -1)
7127 return false; // Could not determine image type
7130 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
7133 wxUnusedVar(success
);
7135 if (!image
.SaveFile(tempFile
, m_imageType
))
7137 if (wxFileExists(tempFile
))
7138 wxRemoveFile(tempFile
);
7143 if (!file
.Open(tempFile
))
7146 m_dataSize
= (size_t) file
.Length();
7151 m_data
= ReadBlock(tempFile
, m_dataSize
);
7153 wxRemoveFile(tempFile
);
7155 return (m_data
!= NULL
);
7160 bool wxRichTextImageBlock::Write(const wxString
& filename
)
7162 return WriteBlock(filename
, m_data
, m_dataSize
);
7165 void wxRichTextImageBlock::Copy(const wxRichTextImageBlock
& block
)
7167 m_imageType
= block
.m_imageType
;
7173 m_dataSize
= block
.m_dataSize
;
7174 if (m_dataSize
== 0)
7177 m_data
= new unsigned char[m_dataSize
];
7179 for (i
= 0; i
< m_dataSize
; i
++)
7180 m_data
[i
] = block
.m_data
[i
];
7184 void wxRichTextImageBlock::operator=(const wxRichTextImageBlock
& block
)
7189 // Load a wxImage from the block
7190 bool wxRichTextImageBlock::Load(wxImage
& image
)
7195 // Read in the image.
7197 wxMemoryInputStream
mstream(m_data
, m_dataSize
);
7198 bool success
= image
.LoadFile(mstream
, GetImageType());
7201 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
7204 if (!WriteBlock(tempFile
, m_data
, m_dataSize
))
7208 success
= image
.LoadFile(tempFile
, GetImageType());
7209 wxRemoveFile(tempFile
);
7215 // Write data in hex to a stream
7216 bool wxRichTextImageBlock::WriteHex(wxOutputStream
& stream
)
7218 const int bufSize
= 512;
7219 char buf
[bufSize
+1];
7221 int left
= m_dataSize
;
7226 if (left
*2 > bufSize
)
7228 n
= bufSize
; left
-= (bufSize
/2);
7232 n
= left
*2; left
= 0;
7236 for (i
= 0; i
< (n
/2); i
++)
7238 wxDecToHex(m_data
[j
], b
, b
+1);
7243 stream
.Write((const char*) buf
, n
);
7248 // Read data in hex from a stream
7249 bool wxRichTextImageBlock::ReadHex(wxInputStream
& stream
, int length
, int imageType
)
7251 int dataSize
= length
/2;
7257 m_data
= new unsigned char[dataSize
];
7259 for (i
= 0; i
< dataSize
; i
++)
7261 str
[0] = (char)stream
.GetC();
7262 str
[1] = (char)stream
.GetC();
7264 m_data
[i
] = (unsigned char)wxHexToDec(str
);
7267 m_dataSize
= dataSize
;
7268 m_imageType
= imageType
;
7273 // Allocate and read from stream as a block of memory
7274 unsigned char* wxRichTextImageBlock::ReadBlock(wxInputStream
& stream
, size_t size
)
7276 unsigned char* block
= new unsigned char[size
];
7280 stream
.Read(block
, size
);
7285 unsigned char* wxRichTextImageBlock::ReadBlock(const wxString
& filename
, size_t size
)
7287 wxFileInputStream
stream(filename
);
7291 return ReadBlock(stream
, size
);
7294 // Write memory block to stream
7295 bool wxRichTextImageBlock::WriteBlock(wxOutputStream
& stream
, unsigned char* block
, size_t size
)
7297 stream
.Write((void*) block
, size
);
7298 return stream
.IsOk();
7302 // Write memory block to file
7303 bool wxRichTextImageBlock::WriteBlock(const wxString
& filename
, unsigned char* block
, size_t size
)
7305 wxFileOutputStream
outStream(filename
);
7306 if (!outStream
.Ok())
7309 return WriteBlock(outStream
, block
, size
);
7312 // Gets the extension for the block's type
7313 wxString
wxRichTextImageBlock::GetExtension() const
7315 wxImageHandler
* handler
= wxImage::FindHandler(GetImageType());
7317 return handler
->GetExtension();
7319 return wxEmptyString
;
7325 * The data object for a wxRichTextBuffer
7328 const wxChar
*wxRichTextBufferDataObject::ms_richTextBufferFormatId
= wxT("wxShape");
7330 wxRichTextBufferDataObject::wxRichTextBufferDataObject(wxRichTextBuffer
* richTextBuffer
)
7332 m_richTextBuffer
= richTextBuffer
;
7334 // this string should uniquely identify our format, but is otherwise
7336 m_formatRichTextBuffer
.SetId(GetRichTextBufferFormatId());
7338 SetFormat(m_formatRichTextBuffer
);
7341 wxRichTextBufferDataObject::~wxRichTextBufferDataObject()
7343 delete m_richTextBuffer
;
7346 // after a call to this function, the richTextBuffer is owned by the caller and it
7347 // is responsible for deleting it!
7348 wxRichTextBuffer
* wxRichTextBufferDataObject::GetRichTextBuffer()
7350 wxRichTextBuffer
* richTextBuffer
= m_richTextBuffer
;
7351 m_richTextBuffer
= NULL
;
7353 return richTextBuffer
;
7356 wxDataFormat
wxRichTextBufferDataObject::GetPreferredFormat(Direction
WXUNUSED(dir
)) const
7358 return m_formatRichTextBuffer
;
7361 size_t wxRichTextBufferDataObject::GetDataSize() const
7363 if (!m_richTextBuffer
)
7369 wxStringOutputStream
stream(& bufXML
);
7370 if (!m_richTextBuffer
->SaveFile(stream
, wxRICHTEXT_TYPE_XML
))
7372 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
7378 wxCharBuffer buffer
= bufXML
.mb_str(wxConvUTF8
);
7379 return strlen(buffer
) + 1;
7381 return bufXML
.Length()+1;
7385 bool wxRichTextBufferDataObject::GetDataHere(void *pBuf
) const
7387 if (!pBuf
|| !m_richTextBuffer
)
7393 wxStringOutputStream
stream(& bufXML
);
7394 if (!m_richTextBuffer
->SaveFile(stream
, wxRICHTEXT_TYPE_XML
))
7396 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
7402 wxCharBuffer buffer
= bufXML
.mb_str(wxConvUTF8
);
7403 size_t len
= strlen(buffer
);
7404 memcpy((char*) pBuf
, (const char*) buffer
, len
);
7405 ((char*) pBuf
)[len
] = 0;
7407 size_t len
= bufXML
.Length();
7408 memcpy((char*) pBuf
, (const char*) bufXML
.c_str(), len
);
7409 ((char*) pBuf
)[len
] = 0;
7415 bool wxRichTextBufferDataObject::SetData(size_t WXUNUSED(len
), const void *buf
)
7417 delete m_richTextBuffer
;
7418 m_richTextBuffer
= NULL
;
7420 wxString
bufXML((const char*) buf
, wxConvUTF8
);
7422 m_richTextBuffer
= new wxRichTextBuffer
;
7424 wxStringInputStream
stream(bufXML
);
7425 if (!m_richTextBuffer
->LoadFile(stream
, wxRICHTEXT_TYPE_XML
))
7427 wxLogError(wxT("Could not read the buffer from an XML stream.\nYou may have forgotten to add the XML file handler."));
7429 delete m_richTextBuffer
;
7430 m_richTextBuffer
= NULL
;
7442 * wxRichTextFontTable
7443 * Manages quick access to a pool of fonts for rendering rich text
7446 WX_DECLARE_STRING_HASH_MAP_WITH_DECL(wxFont
, wxRichTextFontTableHashMap
, class WXDLLIMPEXP_RICHTEXT
);
7448 class wxRichTextFontTableData
: public wxObjectRefData
7451 wxRichTextFontTableData() {}
7453 wxFont
FindFont(const wxTextAttr
& fontSpec
);
7455 wxRichTextFontTableHashMap m_hashMap
;
7458 wxFont
wxRichTextFontTableData::FindFont(const wxTextAttr
& fontSpec
)
7460 wxString
facename(fontSpec
.GetFontFaceName());
7461 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()));
7462 wxRichTextFontTableHashMap::iterator entry
= m_hashMap
.find(spec
);
7464 if ( entry
== m_hashMap
.end() )
7466 wxFont
font(fontSpec
.GetFontSize(), wxDEFAULT
, fontSpec
.GetFontStyle(), fontSpec
.GetFontWeight(), fontSpec
.GetFontUnderlined(), facename
.c_str());
7467 m_hashMap
[spec
] = font
;
7472 return entry
->second
;
7476 IMPLEMENT_DYNAMIC_CLASS(wxRichTextFontTable
, wxObject
)
7478 wxRichTextFontTable::wxRichTextFontTable()
7480 m_refData
= new wxRichTextFontTableData
;
7483 wxRichTextFontTable::wxRichTextFontTable(const wxRichTextFontTable
& table
)
7488 wxRichTextFontTable::~wxRichTextFontTable()
7493 bool wxRichTextFontTable::operator == (const wxRichTextFontTable
& table
) const
7495 return (m_refData
== table
.m_refData
);
7498 void wxRichTextFontTable::operator= (const wxRichTextFontTable
& table
)
7503 wxFont
wxRichTextFontTable::FindFont(const wxTextAttr
& fontSpec
)
7505 wxRichTextFontTableData
* data
= (wxRichTextFontTableData
*) m_refData
;
7507 return data
->FindFont(fontSpec
);
7512 void wxRichTextFontTable::Clear()
7514 wxRichTextFontTableData
* data
= (wxRichTextFontTableData
*) m_refData
;
7516 data
->m_hashMap
.clear();