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 const wxChar wxRichTextLineBreakChar
= (wxChar
) 29;
53 // Helpers for efficiency
55 inline void wxCheckSetFont(wxDC
& dc
, const wxFont
& font
)
57 const wxFont
& font1
= dc
.GetFont();
58 if (font1
.IsOk() && font
.IsOk())
60 if (font1
.GetPointSize() == font
.GetPointSize() &&
61 font1
.GetFamily() == font
.GetFamily() &&
62 font1
.GetStyle() == font
.GetStyle() &&
63 font1
.GetWeight() == font
.GetWeight() &&
64 font1
.GetUnderlined() == font
.GetUnderlined() &&
65 font1
.GetFaceName() == font
.GetFaceName())
71 inline void wxCheckSetPen(wxDC
& dc
, const wxPen
& pen
)
73 const wxPen
& pen1
= dc
.GetPen();
74 if (pen1
.IsOk() && pen
.IsOk())
76 if (pen1
.GetWidth() == pen
.GetWidth() &&
77 pen1
.GetStyle() == pen
.GetStyle() &&
78 pen1
.GetColour() == pen
.GetColour())
84 inline void wxCheckSetBrush(wxDC
& dc
, const wxBrush
& brush
)
86 const wxBrush
& brush1
= dc
.GetBrush();
87 if (brush1
.IsOk() && brush
.IsOk())
89 if (brush1
.GetStyle() == brush
.GetStyle() &&
90 brush1
.GetColour() == brush
.GetColour())
98 * This is the base for drawable objects.
101 IMPLEMENT_CLASS(wxRichTextObject
, wxObject
)
103 wxRichTextObject::wxRichTextObject(wxRichTextObject
* parent
)
115 wxRichTextObject::~wxRichTextObject()
119 void wxRichTextObject::Dereference()
127 void wxRichTextObject::Copy(const wxRichTextObject
& obj
)
131 m_dirty
= obj
.m_dirty
;
132 m_range
= obj
.m_range
;
133 m_attributes
= obj
.m_attributes
;
134 m_descent
= obj
.m_descent
;
137 void wxRichTextObject::SetMargins(int margin
)
139 m_leftMargin
= m_rightMargin
= m_topMargin
= m_bottomMargin
= margin
;
142 void wxRichTextObject::SetMargins(int leftMargin
, int rightMargin
, int topMargin
, int bottomMargin
)
144 m_leftMargin
= leftMargin
;
145 m_rightMargin
= rightMargin
;
146 m_topMargin
= topMargin
;
147 m_bottomMargin
= bottomMargin
;
150 // Convert units in tenths of a millimetre to device units
151 int wxRichTextObject::ConvertTenthsMMToPixels(wxDC
& dc
, int units
)
153 int p
= ConvertTenthsMMToPixels(dc
.GetPPI().x
, units
);
156 wxRichTextBuffer
* buffer
= GetBuffer();
158 p
= (int) ((double)p
/ buffer
->GetScale());
162 // Convert units in tenths of a millimetre to device units
163 int wxRichTextObject::ConvertTenthsMMToPixels(int ppi
, int units
)
165 // There are ppi pixels in 254.1 "1/10 mm"
167 double pixels
= ((double) units
* (double)ppi
) / 254.1;
172 /// Dump to output stream for debugging
173 void wxRichTextObject::Dump(wxTextOutputStream
& stream
)
175 stream
<< GetClassInfo()->GetClassName() << wxT("\n");
176 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");
177 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");
180 /// Gets the containing buffer
181 wxRichTextBuffer
* wxRichTextObject::GetBuffer() const
183 const wxRichTextObject
* obj
= this;
184 while (obj
&& !obj
->IsKindOf(CLASSINFO(wxRichTextBuffer
)))
185 obj
= obj
->GetParent();
186 return wxDynamicCast(obj
, wxRichTextBuffer
);
190 * wxRichTextCompositeObject
191 * This is the base for drawable objects.
194 IMPLEMENT_CLASS(wxRichTextCompositeObject
, wxRichTextObject
)
196 wxRichTextCompositeObject::wxRichTextCompositeObject(wxRichTextObject
* parent
):
197 wxRichTextObject(parent
)
201 wxRichTextCompositeObject::~wxRichTextCompositeObject()
206 /// Get the nth child
207 wxRichTextObject
* wxRichTextCompositeObject::GetChild(size_t n
) const
209 wxASSERT ( n
< m_children
.GetCount() );
211 return m_children
.Item(n
)->GetData();
214 /// Append a child, returning the position
215 size_t wxRichTextCompositeObject::AppendChild(wxRichTextObject
* child
)
217 m_children
.Append(child
);
218 child
->SetParent(this);
219 return m_children
.GetCount() - 1;
222 /// Insert the child in front of the given object, or at the beginning
223 bool wxRichTextCompositeObject::InsertChild(wxRichTextObject
* child
, wxRichTextObject
* inFrontOf
)
227 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(inFrontOf
);
228 m_children
.Insert(node
, child
);
231 m_children
.Insert(child
);
232 child
->SetParent(this);
238 bool wxRichTextCompositeObject::RemoveChild(wxRichTextObject
* child
, bool deleteChild
)
240 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(child
);
243 wxRichTextObject
* obj
= node
->GetData();
244 m_children
.Erase(node
);
253 /// Delete all children
254 bool wxRichTextCompositeObject::DeleteChildren()
256 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
259 wxRichTextObjectList::compatibility_iterator oldNode
= node
;
261 wxRichTextObject
* child
= node
->GetData();
262 child
->Dereference(); // Only delete if reference count is zero
264 node
= node
->GetNext();
265 m_children
.Erase(oldNode
);
271 /// Get the child count
272 size_t wxRichTextCompositeObject::GetChildCount() const
274 return m_children
.GetCount();
278 void wxRichTextCompositeObject::Copy(const wxRichTextCompositeObject
& obj
)
280 wxRichTextObject::Copy(obj
);
284 wxRichTextObjectList::compatibility_iterator node
= obj
.m_children
.GetFirst();
287 wxRichTextObject
* child
= node
->GetData();
288 wxRichTextObject
* newChild
= child
->Clone();
289 newChild
->SetParent(this);
290 m_children
.Append(newChild
);
292 node
= node
->GetNext();
296 /// Hit-testing: returns a flag indicating hit test details, plus
297 /// information about position
298 int wxRichTextCompositeObject::HitTest(wxDC
& dc
, const wxPoint
& pt
, long& textPosition
)
300 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
303 wxRichTextObject
* child
= node
->GetData();
305 int ret
= child
->HitTest(dc
, pt
, textPosition
);
306 if (ret
!= wxRICHTEXT_HITTEST_NONE
)
309 node
= node
->GetNext();
312 return wxRICHTEXT_HITTEST_NONE
;
315 /// Finds the absolute position and row height for the given character position
316 bool wxRichTextCompositeObject::FindPosition(wxDC
& dc
, long index
, wxPoint
& pt
, int* height
, bool forceLineStart
)
318 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
321 wxRichTextObject
* child
= node
->GetData();
323 if (child
->FindPosition(dc
, index
, pt
, height
, forceLineStart
))
326 node
= node
->GetNext();
333 void wxRichTextCompositeObject::CalculateRange(long start
, long& end
)
335 long current
= start
;
336 long lastEnd
= current
;
338 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
341 wxRichTextObject
* child
= node
->GetData();
344 child
->CalculateRange(current
, childEnd
);
347 current
= childEnd
+ 1;
349 node
= node
->GetNext();
354 // An object with no children has zero length
355 if (m_children
.GetCount() == 0)
358 m_range
.SetRange(start
, end
);
361 /// Delete range from layout.
362 bool wxRichTextCompositeObject::DeleteRange(const wxRichTextRange
& range
)
364 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
368 wxRichTextObject
* obj
= (wxRichTextObject
*) node
->GetData();
369 wxRichTextObjectList::compatibility_iterator next
= node
->GetNext();
371 // Delete the range in each paragraph
373 // When a chunk has been deleted, internally the content does not
374 // now match the ranges.
375 // However, so long as deletion is not done on the same object twice this is OK.
376 // If you may delete content from the same object twice, recalculate
377 // the ranges inbetween DeleteRange calls by calling CalculateRanges, and
378 // adjust the range you're deleting accordingly.
380 if (!obj
->GetRange().IsOutside(range
))
382 obj
->DeleteRange(range
);
384 // Delete an empty object, or paragraph within this range.
385 if (obj
->IsEmpty() ||
386 (range
.GetStart() <= obj
->GetRange().GetStart() && range
.GetEnd() >= obj
->GetRange().GetEnd()))
388 // An empty paragraph has length 1, so won't be deleted unless the
389 // whole range is deleted.
390 RemoveChild(obj
, true);
400 /// Get any text in this object for the given range
401 wxString
wxRichTextCompositeObject::GetTextForRange(const wxRichTextRange
& range
) const
404 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
407 wxRichTextObject
* child
= node
->GetData();
408 wxRichTextRange childRange
= range
;
409 if (!child
->GetRange().IsOutside(range
))
411 childRange
.LimitTo(child
->GetRange());
413 wxString childText
= child
->GetTextForRange(childRange
);
417 node
= node
->GetNext();
423 /// Recursively merge all pieces that can be merged.
424 bool wxRichTextCompositeObject::Defragment()
426 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
429 wxRichTextObject
* child
= node
->GetData();
430 wxRichTextCompositeObject
* composite
= wxDynamicCast(child
, wxRichTextCompositeObject
);
432 composite
->Defragment();
436 wxRichTextObject
* nextChild
= node
->GetNext()->GetData();
437 if (child
->CanMerge(nextChild
) && child
->Merge(nextChild
))
439 nextChild
->Dereference();
440 m_children
.Erase(node
->GetNext());
442 // Don't set node -- we'll see if we can merge again with the next
446 node
= node
->GetNext();
449 node
= node
->GetNext();
455 /// Dump to output stream for debugging
456 void wxRichTextCompositeObject::Dump(wxTextOutputStream
& stream
)
458 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
461 wxRichTextObject
* child
= node
->GetData();
463 node
= node
->GetNext();
470 * This defines a 2D space to lay out objects
473 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBox
, wxRichTextCompositeObject
)
475 wxRichTextBox::wxRichTextBox(wxRichTextObject
* parent
):
476 wxRichTextCompositeObject(parent
)
481 bool wxRichTextBox::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& WXUNUSED(rect
), int descent
, int style
)
483 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
486 wxRichTextObject
* child
= node
->GetData();
488 wxRect childRect
= wxRect(child
->GetPosition(), child
->GetCachedSize());
489 child
->Draw(dc
, range
, selectionRange
, childRect
, descent
, style
);
491 node
= node
->GetNext();
497 bool wxRichTextBox::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
499 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
502 wxRichTextObject
* child
= node
->GetData();
503 child
->Layout(dc
, rect
, style
);
505 node
= node
->GetNext();
511 /// Get/set the size for the given range. Assume only has one child.
512 bool wxRichTextBox::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
) const
514 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
517 wxRichTextObject
* child
= node
->GetData();
518 return child
->GetRangeSize(range
, size
, descent
, dc
, flags
, position
);
525 void wxRichTextBox::Copy(const wxRichTextBox
& obj
)
527 wxRichTextCompositeObject::Copy(obj
);
532 * wxRichTextParagraphLayoutBox
533 * This box knows how to lay out paragraphs.
536 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraphLayoutBox
, wxRichTextBox
)
538 wxRichTextParagraphLayoutBox::wxRichTextParagraphLayoutBox(wxRichTextObject
* parent
):
539 wxRichTextBox(parent
)
544 /// Initialize the object.
545 void wxRichTextParagraphLayoutBox::Init()
549 // For now, assume is the only box and has no initial size.
550 m_range
= wxRichTextRange(0, -1);
552 m_invalidRange
.SetRange(-1, -1);
557 m_partialParagraph
= false;
561 bool wxRichTextParagraphLayoutBox::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int descent
, int style
)
563 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
566 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
567 wxASSERT (child
!= NULL
);
569 if (child
&& !child
->GetRange().IsOutside(range
))
571 wxRect
childRect(child
->GetPosition(), child
->GetCachedSize());
573 if (((style
& wxRICHTEXT_DRAW_IGNORE_CACHE
) == 0) && childRect
.GetTop() > rect
.GetBottom())
578 else if (((style
& wxRICHTEXT_DRAW_IGNORE_CACHE
) == 0) && childRect
.GetBottom() < rect
.GetTop())
583 child
->Draw(dc
, range
, selectionRange
, childRect
, descent
, style
);
586 node
= node
->GetNext();
592 bool wxRichTextParagraphLayoutBox::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
594 wxRect availableSpace
;
595 bool formatRect
= (style
& wxRICHTEXT_LAYOUT_SPECIFIED_RECT
) == wxRICHTEXT_LAYOUT_SPECIFIED_RECT
;
597 // If only laying out a specific area, the passed rect has a different meaning:
598 // the visible part of the buffer. This is used in wxRichTextCtrl::OnSize,
599 // so that during a size, only the visible part will be relaid out, or
600 // it would take too long causing flicker. As an approximation, we assume that
601 // everything up to the start of the visible area is laid out correctly.
604 availableSpace
= wxRect(0 + m_leftMargin
,
606 rect
.width
- m_leftMargin
- m_rightMargin
,
609 // Invalidate the part of the buffer from the first visible line
610 // to the end. If other parts of the buffer are currently invalid,
611 // then they too will be taken into account if they are above
612 // the visible point.
614 wxRichTextLine
* line
= GetLineAtYPosition(rect
.y
);
616 startPos
= line
->GetAbsoluteRange().GetStart();
618 Invalidate(wxRichTextRange(startPos
, GetRange().GetEnd()));
621 availableSpace
= wxRect(rect
.x
+ m_leftMargin
,
622 rect
.y
+ m_topMargin
,
623 rect
.width
- m_leftMargin
- m_rightMargin
,
624 rect
.height
- m_topMargin
- m_bottomMargin
);
628 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
630 bool layoutAll
= true;
632 // Get invalid range, rounding to paragraph start/end.
633 wxRichTextRange invalidRange
= GetInvalidRange(true);
635 if (invalidRange
== wxRICHTEXT_NONE
&& !formatRect
)
638 if (invalidRange
== wxRICHTEXT_ALL
)
640 else // If we know what range is affected, start laying out from that point on.
641 if (invalidRange
.GetStart() >= GetRange().GetStart())
643 wxRichTextParagraph
* firstParagraph
= GetParagraphAtPosition(invalidRange
.GetStart());
646 wxRichTextObjectList::compatibility_iterator firstNode
= m_children
.Find(firstParagraph
);
647 wxRichTextObjectList::compatibility_iterator previousNode
;
649 previousNode
= firstNode
->GetPrevious();
654 wxRichTextParagraph
* previousParagraph
= wxDynamicCast(previousNode
->GetData(), wxRichTextParagraph
);
655 availableSpace
.y
= previousParagraph
->GetPosition().y
+ previousParagraph
->GetCachedSize().y
;
658 // Now we're going to start iterating from the first affected paragraph.
666 // A way to force speedy rest-of-buffer layout (the 'else' below)
667 bool forceQuickLayout
= false;
671 // Assume this box only contains paragraphs
673 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
674 wxCHECK_MSG( child
, false, _T("Unknown object in layout") );
676 // TODO: what if the child hasn't been laid out (e.g. involved in Undo) but still has 'old' lines
677 if ( !forceQuickLayout
&&
679 child
->GetLines().IsEmpty() ||
680 !child
->GetRange().IsOutside(invalidRange
)) )
682 child
->Layout(dc
, availableSpace
, style
);
684 // Layout must set the cached size
685 availableSpace
.y
+= child
->GetCachedSize().y
;
686 maxWidth
= wxMax(maxWidth
, child
->GetCachedSize().x
);
688 // If we're just formatting the visible part of the buffer,
689 // and we're now past the bottom of the window, start quick
691 if (formatRect
&& child
->GetPosition().y
> rect
.GetBottom())
692 forceQuickLayout
= true;
696 // We're outside the immediately affected range, so now let's just
697 // move everything up or down. This assumes that all the children have previously
698 // been laid out and have wrapped line lists associated with them.
699 // TODO: check all paragraphs before the affected range.
701 int inc
= availableSpace
.y
- child
->GetPosition().y
;
705 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
708 if (child
->GetLines().GetCount() == 0)
709 child
->Layout(dc
, availableSpace
, style
);
711 child
->SetPosition(wxPoint(child
->GetPosition().x
, child
->GetPosition().y
+ inc
));
713 availableSpace
.y
+= child
->GetCachedSize().y
;
714 maxWidth
= wxMax(maxWidth
, child
->GetCachedSize().x
);
717 node
= node
->GetNext();
722 node
= node
->GetNext();
725 SetCachedSize(wxSize(maxWidth
, availableSpace
.y
));
728 m_invalidRange
= wxRICHTEXT_NONE
;
734 void wxRichTextParagraphLayoutBox::Copy(const wxRichTextParagraphLayoutBox
& obj
)
736 wxRichTextBox::Copy(obj
);
738 m_partialParagraph
= obj
.m_partialParagraph
;
739 m_defaultAttributes
= obj
.m_defaultAttributes
;
742 /// Get/set the size for the given range.
743 bool wxRichTextParagraphLayoutBox::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
) const
747 wxRichTextObjectList::compatibility_iterator startPara
= wxRichTextObjectList::compatibility_iterator();
748 wxRichTextObjectList::compatibility_iterator endPara
= wxRichTextObjectList::compatibility_iterator();
750 // First find the first paragraph whose starting position is within the range.
751 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
754 // child is a paragraph
755 wxRichTextObject
* child
= node
->GetData();
756 const wxRichTextRange
& r
= child
->GetRange();
758 if (r
.GetStart() <= range
.GetStart() && r
.GetEnd() >= range
.GetStart())
764 node
= node
->GetNext();
767 // Next find the last paragraph containing part of the range
768 node
= m_children
.GetFirst();
771 // child is a paragraph
772 wxRichTextObject
* child
= node
->GetData();
773 const wxRichTextRange
& r
= child
->GetRange();
775 if (r
.GetStart() <= range
.GetEnd() && r
.GetEnd() >= range
.GetEnd())
781 node
= node
->GetNext();
784 if (!startPara
|| !endPara
)
787 // Now we can add up the sizes
788 for (node
= startPara
; node
; node
= node
->GetNext())
790 // child is a paragraph
791 wxRichTextObject
* child
= node
->GetData();
792 const wxRichTextRange
& childRange
= child
->GetRange();
793 wxRichTextRange rangeToFind
= range
;
794 rangeToFind
.LimitTo(childRange
);
798 int childDescent
= 0;
799 child
->GetRangeSize(rangeToFind
, childSize
, childDescent
, dc
, flags
, position
);
801 descent
= wxMax(childDescent
, descent
);
803 sz
.x
= wxMax(sz
.x
, childSize
.x
);
815 /// Get the paragraph at the given position
816 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphAtPosition(long pos
, bool caretPosition
) const
821 // First find the first paragraph whose starting position is within the range.
822 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
825 // child is a paragraph
826 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
827 wxASSERT (child
!= NULL
);
829 // Return first child in buffer if position is -1
833 if (child
->GetRange().Contains(pos
))
836 node
= node
->GetNext();
841 /// Get the line at the given position
842 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineAtPosition(long pos
, bool caretPosition
) const
847 // First find the first paragraph whose starting position is within the range.
848 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
851 // child is a paragraph
852 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
853 wxASSERT (child
!= NULL
);
855 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
858 wxRichTextLine
* line
= node2
->GetData();
860 wxRichTextRange range
= line
->GetAbsoluteRange();
862 if (range
.Contains(pos
) ||
864 // If the position is end-of-paragraph, then return the last line of
866 (range
.GetEnd() == child
->GetRange().GetEnd()-1) && (pos
== child
->GetRange().GetEnd()))
869 node2
= node2
->GetNext();
872 node
= node
->GetNext();
875 int lineCount
= GetLineCount();
877 return GetLineForVisibleLineNumber(lineCount
-1);
882 /// Get the line at the given y pixel position, or the last line.
883 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineAtYPosition(int y
) const
885 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
888 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
889 wxASSERT (child
!= NULL
);
891 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
894 wxRichTextLine
* line
= node2
->GetData();
896 wxRect
rect(line
->GetRect());
898 if (y
<= rect
.GetBottom())
901 node2
= node2
->GetNext();
904 node
= node
->GetNext();
908 int lineCount
= GetLineCount();
910 return GetLineForVisibleLineNumber(lineCount
-1);
915 /// Get the number of visible lines
916 int wxRichTextParagraphLayoutBox::GetLineCount() const
920 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
923 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
924 wxASSERT (child
!= NULL
);
926 count
+= child
->GetLines().GetCount();
927 node
= node
->GetNext();
933 /// Get the paragraph for a given line
934 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphForLine(wxRichTextLine
* line
) const
936 return GetParagraphAtPosition(line
->GetAbsoluteRange().GetStart());
939 /// Get the line size at the given position
940 wxSize
wxRichTextParagraphLayoutBox::GetLineSizeAtPosition(long pos
, bool caretPosition
) const
942 wxRichTextLine
* line
= GetLineAtPosition(pos
, caretPosition
);
945 return line
->GetSize();
952 /// Convenience function to add a paragraph of text
953 wxRichTextRange
wxRichTextParagraphLayoutBox::AddParagraph(const wxString
& text
, wxTextAttr
* paraStyle
)
955 // Don't use the base style, just the default style, and the base style will
956 // be combined at display time.
957 // Divide into paragraph and character styles.
959 wxTextAttr defaultCharStyle
;
960 wxTextAttr defaultParaStyle
;
962 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
963 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
964 wxTextAttr
* cStyle
= & defaultCharStyle
;
966 wxRichTextParagraph
* para
= new wxRichTextParagraph(text
, this, pStyle
, cStyle
);
973 return para
->GetRange();
976 /// Adds multiple paragraphs, based on newlines.
977 wxRichTextRange
wxRichTextParagraphLayoutBox::AddParagraphs(const wxString
& text
, wxTextAttr
* paraStyle
)
979 // Don't use the base style, just the default style, and the base style will
980 // be combined at display time.
981 // Divide into paragraph and character styles.
983 wxTextAttr defaultCharStyle
;
984 wxTextAttr defaultParaStyle
;
985 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
987 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
988 wxTextAttr
* cStyle
= & defaultCharStyle
;
990 wxRichTextParagraph
* firstPara
= NULL
;
991 wxRichTextParagraph
* lastPara
= NULL
;
993 wxRichTextRange
range(-1, -1);
996 size_t len
= text
.length();
998 wxRichTextParagraph
* para
= new wxRichTextParagraph(wxEmptyString
, this, pStyle
, cStyle
);
1007 wxChar ch
= text
[i
];
1008 if (ch
== wxT('\n') || ch
== wxT('\r'))
1010 wxRichTextPlainText
* plainText
= (wxRichTextPlainText
*) para
->GetChildren().GetFirst()->GetData();
1011 plainText
->SetText(line
);
1013 para
= new wxRichTextParagraph(wxEmptyString
, this, pStyle
, cStyle
);
1018 line
= wxEmptyString
;
1028 wxRichTextPlainText
* plainText
= (wxRichTextPlainText
*) para
->GetChildren().GetFirst()->GetData();
1029 plainText
->SetText(line
);
1036 return wxRichTextRange(firstPara
->GetRange().GetStart(), lastPara
->GetRange().GetEnd());
1039 /// Convenience function to add an image
1040 wxRichTextRange
wxRichTextParagraphLayoutBox::AddImage(const wxImage
& image
, wxTextAttr
* paraStyle
)
1042 // Don't use the base style, just the default style, and the base style will
1043 // be combined at display time.
1044 // Divide into paragraph and character styles.
1046 wxTextAttr defaultCharStyle
;
1047 wxTextAttr defaultParaStyle
;
1048 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
1050 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
1051 wxTextAttr
* cStyle
= & defaultCharStyle
;
1053 wxRichTextParagraph
* para
= new wxRichTextParagraph(this, pStyle
);
1055 para
->AppendChild(new wxRichTextImage(image
, this, cStyle
));
1060 return para
->GetRange();
1064 /// Insert fragment into this box at the given position. If partialParagraph is true,
1065 /// it is assumed that the last (or only) paragraph is just a piece of data with no paragraph
1068 bool wxRichTextParagraphLayoutBox::InsertFragment(long position
, wxRichTextParagraphLayoutBox
& fragment
)
1072 // First, find the first paragraph whose starting position is within the range.
1073 wxRichTextParagraph
* para
= GetParagraphAtPosition(position
);
1076 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(para
);
1078 // Now split at this position, returning the object to insert the new
1079 // ones in front of.
1080 wxRichTextObject
* nextObject
= para
->SplitAt(position
);
1082 // Special case: partial paragraph, just one paragraph. Might be a small amount of
1083 // text, for example, so let's optimize.
1085 if (fragment
.GetPartialParagraph() && fragment
.GetChildren().GetCount() == 1)
1087 // Add the first para to this para...
1088 wxRichTextObjectList::compatibility_iterator firstParaNode
= fragment
.GetChildren().GetFirst();
1092 // Iterate through the fragment paragraph inserting the content into this paragraph.
1093 wxRichTextParagraph
* firstPara
= wxDynamicCast(firstParaNode
->GetData(), wxRichTextParagraph
);
1094 wxASSERT (firstPara
!= NULL
);
1096 // Apply the new paragraph attributes to the existing paragraph
1097 wxTextAttr
attr(para
->GetAttributes());
1098 wxRichTextApplyStyle(attr
, firstPara
->GetAttributes());
1099 para
->SetAttributes(attr
);
1101 wxRichTextObjectList::compatibility_iterator objectNode
= firstPara
->GetChildren().GetFirst();
1104 wxRichTextObject
* newObj
= objectNode
->GetData()->Clone();
1109 para
->AppendChild(newObj
);
1113 // Insert before nextObject
1114 para
->InsertChild(newObj
, nextObject
);
1117 objectNode
= objectNode
->GetNext();
1124 // Procedure for inserting a fragment consisting of a number of
1127 // 1. Remove and save the content that's after the insertion point, for adding
1128 // back once we've added the fragment.
1129 // 2. Add the content from the first fragment paragraph to the current
1131 // 3. Add remaining fragment paragraphs after the current paragraph.
1132 // 4. Add back the saved content from the first paragraph. If partialParagraph
1133 // is true, add it to the last paragraph added and not a new one.
1135 // 1. Remove and save objects after split point.
1136 wxList savedObjects
;
1138 para
->MoveToList(nextObject
, savedObjects
);
1140 // 2. Add the content from the 1st fragment paragraph.
1141 wxRichTextObjectList::compatibility_iterator firstParaNode
= fragment
.GetChildren().GetFirst();
1145 wxRichTextParagraph
* firstPara
= wxDynamicCast(firstParaNode
->GetData(), wxRichTextParagraph
);
1146 wxASSERT(firstPara
!= NULL
);
1148 wxRichTextObjectList::compatibility_iterator objectNode
= firstPara
->GetChildren().GetFirst();
1151 wxRichTextObject
* newObj
= objectNode
->GetData()->Clone();
1154 para
->AppendChild(newObj
);
1156 objectNode
= objectNode
->GetNext();
1159 // 3. Add remaining fragment paragraphs after the current paragraph.
1160 wxRichTextObjectList::compatibility_iterator nextParagraphNode
= node
->GetNext();
1161 wxRichTextObject
* nextParagraph
= NULL
;
1162 if (nextParagraphNode
)
1163 nextParagraph
= nextParagraphNode
->GetData();
1165 wxRichTextObjectList::compatibility_iterator i
= fragment
.GetChildren().GetFirst()->GetNext();
1166 wxRichTextParagraph
* finalPara
= para
;
1168 // If there was only one paragraph, we need to insert a new one.
1171 finalPara
= new wxRichTextParagraph
;
1173 // TODO: These attributes should come from the subsequent paragraph
1174 // when originally deleted, since the subsequent para takes on
1175 // the previous para's attributes.
1176 finalPara
->SetAttributes(firstPara
->GetAttributes());
1179 InsertChild(finalPara
, nextParagraph
);
1181 AppendChild(finalPara
);
1185 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1186 wxASSERT( para
!= NULL
);
1188 finalPara
= (wxRichTextParagraph
*) para
->Clone();
1191 InsertChild(finalPara
, nextParagraph
);
1193 AppendChild(finalPara
);
1198 // 4. Add back the remaining content.
1201 finalPara
->MoveFromList(savedObjects
);
1203 // Ensure there's at least one object
1204 if (finalPara
->GetChildCount() == 0)
1206 wxRichTextPlainText
* text
= new wxRichTextPlainText(wxEmptyString
);
1208 finalPara
->AppendChild(text
);
1218 wxRichTextObjectList::compatibility_iterator i
= fragment
.GetChildren().GetFirst();
1221 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1222 wxASSERT( para
!= NULL
);
1224 AppendChild(para
->Clone());
1233 /// Make a copy of the fragment corresponding to the given range, putting it in 'fragment'.
1234 /// If there was an incomplete paragraph at the end, partialParagraph is set to true.
1235 bool wxRichTextParagraphLayoutBox::CopyFragment(const wxRichTextRange
& range
, wxRichTextParagraphLayoutBox
& fragment
)
1237 wxRichTextObjectList::compatibility_iterator i
= GetChildren().GetFirst();
1240 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1241 wxASSERT( para
!= NULL
);
1243 if (!para
->GetRange().IsOutside(range
))
1245 fragment
.AppendChild(para
->Clone());
1250 // Now top and tail the first and last paragraphs in our new fragment (which might be the same).
1251 if (!fragment
.IsEmpty())
1253 wxRichTextRange
topTailRange(range
);
1255 wxRichTextParagraph
* firstPara
= wxDynamicCast(fragment
.GetChildren().GetFirst()->GetData(), wxRichTextParagraph
);
1256 wxASSERT( firstPara
!= NULL
);
1258 // Chop off the start of the paragraph
1259 if (topTailRange
.GetStart() > firstPara
->GetRange().GetStart())
1261 wxRichTextRange
r(firstPara
->GetRange().GetStart(), topTailRange
.GetStart()-1);
1262 firstPara
->DeleteRange(r
);
1264 // Make sure the numbering is correct
1266 fragment
.CalculateRange(firstPara
->GetRange().GetStart(), end
);
1268 // Now, we've deleted some positions, so adjust the range
1270 topTailRange
.SetEnd(topTailRange
.GetEnd() - r
.GetLength());
1273 wxRichTextParagraph
* lastPara
= wxDynamicCast(fragment
.GetChildren().GetLast()->GetData(), wxRichTextParagraph
);
1274 wxASSERT( lastPara
!= NULL
);
1276 if (topTailRange
.GetEnd() < (lastPara
->GetRange().GetEnd()-1))
1278 wxRichTextRange
r(topTailRange
.GetEnd()+1, lastPara
->GetRange().GetEnd()-1); /* -1 since actual text ends 1 position before end of para marker */
1279 lastPara
->DeleteRange(r
);
1281 // Make sure the numbering is correct
1283 fragment
.CalculateRange(firstPara
->GetRange().GetStart(), end
);
1285 // We only have part of a paragraph at the end
1286 fragment
.SetPartialParagraph(true);
1290 if (topTailRange
.GetEnd() == (lastPara
->GetRange().GetEnd() - 1))
1291 // We have a partial paragraph (don't save last new paragraph marker)
1292 fragment
.SetPartialParagraph(true);
1294 // We have a complete paragraph
1295 fragment
.SetPartialParagraph(false);
1302 /// Given a position, get the number of the visible line (potentially many to a paragraph),
1303 /// starting from zero at the start of the buffer.
1304 long wxRichTextParagraphLayoutBox::GetVisibleLineNumber(long pos
, bool caretPosition
, bool startOfLine
) const
1311 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1314 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1315 wxASSERT( child
!= NULL
);
1317 if (child
->GetRange().Contains(pos
))
1319 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
1322 wxRichTextLine
* line
= node2
->GetData();
1323 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
1325 if (lineRange
.Contains(pos
))
1327 // If the caret is displayed at the end of the previous wrapped line,
1328 // we want to return the line it's _displayed_ at (not the actual line
1329 // containing the position).
1330 if (lineRange
.GetStart() == pos
&& !startOfLine
&& child
->GetRange().GetStart() != pos
)
1331 return lineCount
- 1;
1338 node2
= node2
->GetNext();
1340 // If we didn't find it in the lines, it must be
1341 // the last position of the paragraph. So return the last line.
1345 lineCount
+= child
->GetLines().GetCount();
1347 node
= node
->GetNext();
1354 /// Given a line number, get the corresponding wxRichTextLine object.
1355 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineForVisibleLineNumber(long lineNumber
) const
1359 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1362 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1363 wxASSERT(child
!= NULL
);
1365 if (lineNumber
< (int) (child
->GetLines().GetCount() + lineCount
))
1367 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
1370 wxRichTextLine
* line
= node2
->GetData();
1372 if (lineCount
== lineNumber
)
1377 node2
= node2
->GetNext();
1381 lineCount
+= child
->GetLines().GetCount();
1383 node
= node
->GetNext();
1390 /// Delete range from layout.
1391 bool wxRichTextParagraphLayoutBox::DeleteRange(const wxRichTextRange
& range
)
1393 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1397 wxRichTextParagraph
* obj
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1398 wxASSERT (obj
!= NULL
);
1400 wxRichTextObjectList::compatibility_iterator next
= node
->GetNext();
1402 // Delete the range in each paragraph
1404 if (!obj
->GetRange().IsOutside(range
))
1406 // Deletes the content of this object within the given range
1407 obj
->DeleteRange(range
);
1409 // If the whole paragraph is within the range to delete,
1410 // delete the whole thing.
1411 if (range
.GetStart() <= obj
->GetRange().GetStart() && range
.GetEnd() >= obj
->GetRange().GetEnd())
1413 // Delete the whole object
1414 RemoveChild(obj
, true);
1416 // If the range includes the paragraph end, we need to join this
1417 // and the next paragraph.
1418 else if (range
.Contains(obj
->GetRange().GetEnd()))
1420 // We need to move the objects from the next paragraph
1421 // to this paragraph
1425 wxRichTextParagraph
* nextParagraph
= wxDynamicCast(next
->GetData(), wxRichTextParagraph
);
1426 next
= next
->GetNext();
1429 // Delete the stuff we need to delete
1430 nextParagraph
->DeleteRange(range
);
1432 // Move the objects to the previous para
1433 wxRichTextObjectList::compatibility_iterator node1
= nextParagraph
->GetChildren().GetFirst();
1437 wxRichTextObject
* obj1
= node1
->GetData();
1439 // If the object is empty, optimise it out
1440 if (obj1
->IsEmpty())
1446 obj
->AppendChild(obj1
);
1449 wxRichTextObjectList::compatibility_iterator next1
= node1
->GetNext();
1450 nextParagraph
->GetChildren().Erase(node1
);
1455 // Delete the paragraph
1456 RemoveChild(nextParagraph
, true);
1470 /// Get any text in this object for the given range
1471 wxString
wxRichTextParagraphLayoutBox::GetTextForRange(const wxRichTextRange
& range
) const
1475 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1478 wxRichTextObject
* child
= node
->GetData();
1479 if (!child
->GetRange().IsOutside(range
))
1481 wxRichTextRange childRange
= range
;
1482 childRange
.LimitTo(child
->GetRange());
1484 wxString childText
= child
->GetTextForRange(childRange
);
1488 if ((childRange
.GetEnd() == child
->GetRange().GetEnd()) && node
->GetNext())
1493 node
= node
->GetNext();
1499 /// Get all the text
1500 wxString
wxRichTextParagraphLayoutBox::GetText() const
1502 return GetTextForRange(GetRange());
1505 /// Get the paragraph by number
1506 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphAtLine(long paragraphNumber
) const
1508 if ((size_t) paragraphNumber
>= GetChildCount())
1511 return (wxRichTextParagraph
*) GetChild((size_t) paragraphNumber
);
1514 /// Get the length of the paragraph
1515 int wxRichTextParagraphLayoutBox::GetParagraphLength(long paragraphNumber
) const
1517 wxRichTextParagraph
* para
= GetParagraphAtLine(paragraphNumber
);
1519 return para
->GetRange().GetLength() - 1; // don't include newline
1524 /// Get the text of the paragraph
1525 wxString
wxRichTextParagraphLayoutBox::GetParagraphText(long paragraphNumber
) const
1527 wxRichTextParagraph
* para
= GetParagraphAtLine(paragraphNumber
);
1529 return para
->GetTextForRange(para
->GetRange());
1531 return wxEmptyString
;
1534 /// Convert zero-based line column and paragraph number to a position.
1535 long wxRichTextParagraphLayoutBox::XYToPosition(long x
, long y
) const
1537 wxRichTextParagraph
* para
= GetParagraphAtLine(y
);
1540 return para
->GetRange().GetStart() + x
;
1546 /// Convert zero-based position to line column and paragraph number
1547 bool wxRichTextParagraphLayoutBox::PositionToXY(long pos
, long* x
, long* y
) const
1549 wxRichTextParagraph
* para
= GetParagraphAtPosition(pos
);
1553 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1556 wxRichTextObject
* child
= node
->GetData();
1560 node
= node
->GetNext();
1564 *x
= pos
- para
->GetRange().GetStart();
1572 /// Get the leaf object in a paragraph at this position.
1573 /// Given a line number, get the corresponding wxRichTextLine object.
1574 wxRichTextObject
* wxRichTextParagraphLayoutBox::GetLeafObjectAtPosition(long position
) const
1576 wxRichTextParagraph
* para
= GetParagraphAtPosition(position
);
1579 wxRichTextObjectList::compatibility_iterator node
= para
->GetChildren().GetFirst();
1583 wxRichTextObject
* child
= node
->GetData();
1584 if (child
->GetRange().Contains(position
))
1587 node
= node
->GetNext();
1589 if (position
== para
->GetRange().GetEnd() && para
->GetChildCount() > 0)
1590 return para
->GetChildren().GetLast()->GetData();
1595 /// Set character or paragraph text attributes: apply character styles only to immediate text nodes
1596 bool wxRichTextParagraphLayoutBox::SetStyle(const wxRichTextRange
& range
, const wxTextAttr
& style
, int flags
)
1598 bool characterStyle
= false;
1599 bool paragraphStyle
= false;
1601 if (style
.IsCharacterStyle())
1602 characterStyle
= true;
1603 if (style
.IsParagraphStyle())
1604 paragraphStyle
= true;
1606 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
1607 bool applyMinimal
= ((flags
& wxRICHTEXT_SETSTYLE_OPTIMIZE
) != 0);
1608 bool parasOnly
= ((flags
& wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY
) != 0);
1609 bool charactersOnly
= ((flags
& wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY
) != 0);
1610 bool resetExistingStyle
= ((flags
& wxRICHTEXT_SETSTYLE_RESET
) != 0);
1611 bool removeStyle
= ((flags
& wxRICHTEXT_SETSTYLE_REMOVE
) != 0);
1613 // Apply paragraph style first, if any
1614 wxTextAttr
wholeStyle(style
);
1616 if (!removeStyle
&& wholeStyle
.HasParagraphStyleName() && GetStyleSheet())
1618 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(wholeStyle
.GetParagraphStyleName());
1620 wxRichTextApplyStyle(wholeStyle
, def
->GetStyleMergedWithBase(GetStyleSheet()));
1623 // Limit the attributes to be set to the content to only character attributes.
1624 wxTextAttr
characterAttributes(wholeStyle
);
1625 characterAttributes
.SetFlags(characterAttributes
.GetFlags() & (wxTEXT_ATTR_CHARACTER
));
1627 if (!removeStyle
&& characterAttributes
.HasCharacterStyleName() && GetStyleSheet())
1629 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterAttributes
.GetCharacterStyleName());
1631 wxRichTextApplyStyle(characterAttributes
, def
->GetStyleMergedWithBase(GetStyleSheet()));
1634 // If we are associated with a control, make undoable; otherwise, apply immediately
1637 bool haveControl
= (GetRichTextCtrl() != NULL
);
1639 wxRichTextAction
* action
= NULL
;
1641 if (haveControl
&& withUndo
)
1643 action
= new wxRichTextAction(NULL
, _("Change Style"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
1644 action
->SetRange(range
);
1645 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
1648 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1651 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1652 wxASSERT (para
!= NULL
);
1654 if (para
&& para
->GetChildCount() > 0)
1656 // Stop searching if we're beyond the range of interest
1657 if (para
->GetRange().GetStart() > range
.GetEnd())
1660 if (!para
->GetRange().IsOutside(range
))
1662 // We'll be using a copy of the paragraph to make style changes,
1663 // not updating the buffer directly.
1664 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
1666 if (haveControl
&& withUndo
)
1668 newPara
= new wxRichTextParagraph(*para
);
1669 action
->GetNewParagraphs().AppendChild(newPara
);
1671 // Also store the old ones for Undo
1672 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
1677 // If we're specifying paragraphs only, then we really mean character formatting
1678 // to be included in the paragraph style
1679 if ((paragraphStyle
|| parasOnly
) && !charactersOnly
)
1683 // Removes the given style from the paragraph
1684 wxRichTextRemoveStyle(newPara
->GetAttributes(), style
);
1686 else if (resetExistingStyle
)
1687 newPara
->GetAttributes() = wholeStyle
;
1692 // Only apply attributes that will make a difference to the combined
1693 // style as seen on the display
1694 wxTextAttr
combinedAttr(para
->GetCombinedAttributes());
1695 wxRichTextApplyStyle(newPara
->GetAttributes(), wholeStyle
, & combinedAttr
);
1698 wxRichTextApplyStyle(newPara
->GetAttributes(), wholeStyle
);
1702 // When applying paragraph styles dynamically, don't change the text objects' attributes
1703 // since they will computed as needed. Only apply the character styling if it's _only_
1704 // character styling. This policy is subject to change and might be put under user control.
1706 // Hm. we might well be applying a mix of paragraph and character styles, in which
1707 // case we _do_ want to apply character styles regardless of what para styles are set.
1708 // But if we're applying a paragraph style, which has some character attributes, but
1709 // we only want the paragraphs to hold this character style, then we _don't_ want to
1710 // apply the character style. So we need to be able to choose.
1712 // if (!paragraphStyle && characterStyle && range.GetStart() != newPara->GetRange().GetEnd())
1713 if (!parasOnly
&& characterStyle
&& range
.GetStart() != newPara
->GetRange().GetEnd())
1715 wxRichTextRange
childRange(range
);
1716 childRange
.LimitTo(newPara
->GetRange());
1718 // Find the starting position and if necessary split it so
1719 // we can start applying a different style.
1720 // TODO: check that the style actually changes or is different
1721 // from style outside of range
1722 wxRichTextObject
* firstObject
wxDUMMY_INITIALIZE(NULL
);
1723 wxRichTextObject
* lastObject
wxDUMMY_INITIALIZE(NULL
);
1725 if (childRange
.GetStart() == newPara
->GetRange().GetStart())
1726 firstObject
= newPara
->GetChildren().GetFirst()->GetData();
1728 firstObject
= newPara
->SplitAt(range
.GetStart());
1730 // Increment by 1 because we're apply the style one _after_ the split point
1731 long splitPoint
= childRange
.GetEnd();
1732 if (splitPoint
!= newPara
->GetRange().GetEnd())
1736 if (splitPoint
== newPara
->GetRange().GetEnd() || splitPoint
== (newPara
->GetRange().GetEnd() - 1))
1737 lastObject
= newPara
->GetChildren().GetLast()->GetData();
1739 // lastObject is set as a side-effect of splitting. It's
1740 // returned as the object before the new object.
1741 (void) newPara
->SplitAt(splitPoint
, & lastObject
);
1743 wxASSERT(firstObject
!= NULL
);
1744 wxASSERT(lastObject
!= NULL
);
1746 if (!firstObject
|| !lastObject
)
1749 wxRichTextObjectList::compatibility_iterator firstNode
= newPara
->GetChildren().Find(firstObject
);
1750 wxRichTextObjectList::compatibility_iterator lastNode
= newPara
->GetChildren().Find(lastObject
);
1752 wxASSERT(firstNode
);
1755 wxRichTextObjectList::compatibility_iterator node2
= firstNode
;
1759 wxRichTextObject
* child
= node2
->GetData();
1763 // Removes the given style from the paragraph
1764 wxRichTextRemoveStyle(child
->GetAttributes(), style
);
1766 else if (resetExistingStyle
)
1767 child
->GetAttributes() = characterAttributes
;
1772 // Only apply attributes that will make a difference to the combined
1773 // style as seen on the display
1774 wxTextAttr
combinedAttr(newPara
->GetCombinedAttributes(child
->GetAttributes()));
1775 wxRichTextApplyStyle(child
->GetAttributes(), characterAttributes
, & combinedAttr
);
1778 wxRichTextApplyStyle(child
->GetAttributes(), characterAttributes
);
1781 if (node2
== lastNode
)
1784 node2
= node2
->GetNext();
1790 node
= node
->GetNext();
1793 // Do action, or delay it until end of batch.
1794 if (haveControl
&& withUndo
)
1795 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
1800 /// Get the text attributes for this position.
1801 bool wxRichTextParagraphLayoutBox::GetStyle(long position
, wxTextAttr
& style
)
1803 return DoGetStyle(position
, style
, true);
1806 bool wxRichTextParagraphLayoutBox::GetUncombinedStyle(long position
, wxTextAttr
& style
)
1808 return DoGetStyle(position
, style
, false);
1811 /// Implementation helper for GetStyle. If combineStyles is true, combine base, paragraph and
1812 /// context attributes.
1813 bool wxRichTextParagraphLayoutBox::DoGetStyle(long position
, wxTextAttr
& style
, bool combineStyles
)
1815 wxRichTextObject
* obj
wxDUMMY_INITIALIZE(NULL
);
1817 if (style
.IsParagraphStyle())
1819 obj
= GetParagraphAtPosition(position
);
1824 // Start with the base style
1825 style
= GetAttributes();
1827 // Apply the paragraph style
1828 wxRichTextApplyStyle(style
, obj
->GetAttributes());
1831 style
= obj
->GetAttributes();
1838 obj
= GetLeafObjectAtPosition(position
);
1843 wxRichTextParagraph
* para
= wxDynamicCast(obj
->GetParent(), wxRichTextParagraph
);
1844 style
= para
? para
->GetCombinedAttributes(obj
->GetAttributes()) : obj
->GetAttributes();
1847 style
= obj
->GetAttributes();
1855 static bool wxHasStyle(long flags
, long style
)
1857 return (flags
& style
) != 0;
1860 /// Combines 'style' with 'currentStyle' for the purpose of summarising the attributes of a range of
1862 bool wxRichTextParagraphLayoutBox::CollectStyle(wxTextAttr
& currentStyle
, const wxTextAttr
& style
, long& multipleStyleAttributes
, int& multipleTextEffectAttributes
)
1864 if (style
.HasFont())
1866 if (style
.HasFontSize() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_SIZE
))
1868 if (currentStyle
.HasFontSize())
1870 if (currentStyle
.GetFontSize() != style
.GetFontSize())
1872 // Clash of style - mark as such
1873 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_SIZE
;
1874 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_SIZE
);
1879 currentStyle
.SetFontSize(style
.GetFontSize());
1883 if (style
.HasFontItalic() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_ITALIC
))
1885 if (currentStyle
.HasFontItalic())
1887 if (currentStyle
.GetFontStyle() != style
.GetFontStyle())
1889 // Clash of style - mark as such
1890 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_ITALIC
;
1891 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_ITALIC
);
1896 currentStyle
.SetFontStyle(style
.GetFontStyle());
1900 if (style
.HasFontWeight() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_WEIGHT
))
1902 if (currentStyle
.HasFontWeight())
1904 if (currentStyle
.GetFontWeight() != style
.GetFontWeight())
1906 // Clash of style - mark as such
1907 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_WEIGHT
;
1908 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_WEIGHT
);
1913 currentStyle
.SetFontWeight(style
.GetFontWeight());
1917 if (style
.HasFontFaceName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_FACE
))
1919 if (currentStyle
.HasFontFaceName())
1921 wxString
faceName1(currentStyle
.GetFontFaceName());
1922 wxString
faceName2(style
.GetFontFaceName());
1924 if (faceName1
!= faceName2
)
1926 // Clash of style - mark as such
1927 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_FACE
;
1928 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_FACE
);
1933 currentStyle
.SetFontFaceName(style
.GetFontFaceName());
1937 if (style
.HasFontUnderlined() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_UNDERLINE
))
1939 if (currentStyle
.HasFontUnderlined())
1941 if (currentStyle
.GetFontUnderlined() != style
.GetFontUnderlined())
1943 // Clash of style - mark as such
1944 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_UNDERLINE
;
1945 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_UNDERLINE
);
1950 currentStyle
.SetFontUnderlined(style
.GetFontUnderlined());
1955 if (style
.HasTextColour() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_TEXT_COLOUR
))
1957 if (currentStyle
.HasTextColour())
1959 if (currentStyle
.GetTextColour() != style
.GetTextColour())
1961 // Clash of style - mark as such
1962 multipleStyleAttributes
|= wxTEXT_ATTR_TEXT_COLOUR
;
1963 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_TEXT_COLOUR
);
1967 currentStyle
.SetTextColour(style
.GetTextColour());
1970 if (style
.HasBackgroundColour() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BACKGROUND_COLOUR
))
1972 if (currentStyle
.HasBackgroundColour())
1974 if (currentStyle
.GetBackgroundColour() != style
.GetBackgroundColour())
1976 // Clash of style - mark as such
1977 multipleStyleAttributes
|= wxTEXT_ATTR_BACKGROUND_COLOUR
;
1978 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BACKGROUND_COLOUR
);
1982 currentStyle
.SetBackgroundColour(style
.GetBackgroundColour());
1985 if (style
.HasAlignment() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_ALIGNMENT
))
1987 if (currentStyle
.HasAlignment())
1989 if (currentStyle
.GetAlignment() != style
.GetAlignment())
1991 // Clash of style - mark as such
1992 multipleStyleAttributes
|= wxTEXT_ATTR_ALIGNMENT
;
1993 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_ALIGNMENT
);
1997 currentStyle
.SetAlignment(style
.GetAlignment());
2000 if (style
.HasTabs() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_TABS
))
2002 if (currentStyle
.HasTabs())
2004 if (!wxRichTextTabsEq(currentStyle
.GetTabs(), style
.GetTabs()))
2006 // Clash of style - mark as such
2007 multipleStyleAttributes
|= wxTEXT_ATTR_TABS
;
2008 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_TABS
);
2012 currentStyle
.SetTabs(style
.GetTabs());
2015 if (style
.HasLeftIndent() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_LEFT_INDENT
))
2017 if (currentStyle
.HasLeftIndent())
2019 if (currentStyle
.GetLeftIndent() != style
.GetLeftIndent() || currentStyle
.GetLeftSubIndent() != style
.GetLeftSubIndent())
2021 // Clash of style - mark as such
2022 multipleStyleAttributes
|= wxTEXT_ATTR_LEFT_INDENT
;
2023 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LEFT_INDENT
);
2027 currentStyle
.SetLeftIndent(style
.GetLeftIndent(), style
.GetLeftSubIndent());
2030 if (style
.HasRightIndent() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_RIGHT_INDENT
))
2032 if (currentStyle
.HasRightIndent())
2034 if (currentStyle
.GetRightIndent() != style
.GetRightIndent())
2036 // Clash of style - mark as such
2037 multipleStyleAttributes
|= wxTEXT_ATTR_RIGHT_INDENT
;
2038 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_RIGHT_INDENT
);
2042 currentStyle
.SetRightIndent(style
.GetRightIndent());
2045 if (style
.HasParagraphSpacingAfter() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_PARA_SPACING_AFTER
))
2047 if (currentStyle
.HasParagraphSpacingAfter())
2049 if (currentStyle
.GetParagraphSpacingAfter() != style
.GetParagraphSpacingAfter())
2051 // Clash of style - mark as such
2052 multipleStyleAttributes
|= wxTEXT_ATTR_PARA_SPACING_AFTER
;
2053 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARA_SPACING_AFTER
);
2057 currentStyle
.SetParagraphSpacingAfter(style
.GetParagraphSpacingAfter());
2060 if (style
.HasParagraphSpacingBefore() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_PARA_SPACING_BEFORE
))
2062 if (currentStyle
.HasParagraphSpacingBefore())
2064 if (currentStyle
.GetParagraphSpacingBefore() != style
.GetParagraphSpacingBefore())
2066 // Clash of style - mark as such
2067 multipleStyleAttributes
|= wxTEXT_ATTR_PARA_SPACING_BEFORE
;
2068 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARA_SPACING_BEFORE
);
2072 currentStyle
.SetParagraphSpacingBefore(style
.GetParagraphSpacingBefore());
2075 if (style
.HasLineSpacing() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_LINE_SPACING
))
2077 if (currentStyle
.HasLineSpacing())
2079 if (currentStyle
.GetLineSpacing() != style
.GetLineSpacing())
2081 // Clash of style - mark as such
2082 multipleStyleAttributes
|= wxTEXT_ATTR_LINE_SPACING
;
2083 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LINE_SPACING
);
2087 currentStyle
.SetLineSpacing(style
.GetLineSpacing());
2090 if (style
.HasCharacterStyleName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_CHARACTER_STYLE_NAME
))
2092 if (currentStyle
.HasCharacterStyleName())
2094 if (currentStyle
.GetCharacterStyleName() != style
.GetCharacterStyleName())
2096 // Clash of style - mark as such
2097 multipleStyleAttributes
|= wxTEXT_ATTR_CHARACTER_STYLE_NAME
;
2098 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_CHARACTER_STYLE_NAME
);
2102 currentStyle
.SetCharacterStyleName(style
.GetCharacterStyleName());
2105 if (style
.HasParagraphStyleName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
))
2107 if (currentStyle
.HasParagraphStyleName())
2109 if (currentStyle
.GetParagraphStyleName() != style
.GetParagraphStyleName())
2111 // Clash of style - mark as such
2112 multipleStyleAttributes
|= wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
;
2113 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
);
2117 currentStyle
.SetParagraphStyleName(style
.GetParagraphStyleName());
2120 if (style
.HasListStyleName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_LIST_STYLE_NAME
))
2122 if (currentStyle
.HasListStyleName())
2124 if (currentStyle
.GetListStyleName() != style
.GetListStyleName())
2126 // Clash of style - mark as such
2127 multipleStyleAttributes
|= wxTEXT_ATTR_LIST_STYLE_NAME
;
2128 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LIST_STYLE_NAME
);
2132 currentStyle
.SetListStyleName(style
.GetListStyleName());
2135 if (style
.HasBulletStyle() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_STYLE
))
2137 if (currentStyle
.HasBulletStyle())
2139 if (currentStyle
.GetBulletStyle() != style
.GetBulletStyle())
2141 // Clash of style - mark as such
2142 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_STYLE
;
2143 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_STYLE
);
2147 currentStyle
.SetBulletStyle(style
.GetBulletStyle());
2150 if (style
.HasBulletNumber() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_NUMBER
))
2152 if (currentStyle
.HasBulletNumber())
2154 if (currentStyle
.GetBulletNumber() != style
.GetBulletNumber())
2156 // Clash of style - mark as such
2157 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_NUMBER
;
2158 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_NUMBER
);
2162 currentStyle
.SetBulletNumber(style
.GetBulletNumber());
2165 if (style
.HasBulletText() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_TEXT
))
2167 if (currentStyle
.HasBulletText())
2169 if (currentStyle
.GetBulletText() != style
.GetBulletText())
2171 // Clash of style - mark as such
2172 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_TEXT
;
2173 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_TEXT
);
2178 currentStyle
.SetBulletText(style
.GetBulletText());
2179 currentStyle
.SetBulletFont(style
.GetBulletFont());
2183 if (style
.HasBulletName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_NAME
))
2185 if (currentStyle
.HasBulletName())
2187 if (currentStyle
.GetBulletName() != style
.GetBulletName())
2189 // Clash of style - mark as such
2190 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_NAME
;
2191 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_NAME
);
2196 currentStyle
.SetBulletName(style
.GetBulletName());
2200 if (style
.HasURL() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_URL
))
2202 if (currentStyle
.HasURL())
2204 if (currentStyle
.GetURL() != style
.GetURL())
2206 // Clash of style - mark as such
2207 multipleStyleAttributes
|= wxTEXT_ATTR_URL
;
2208 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_URL
);
2213 currentStyle
.SetURL(style
.GetURL());
2217 if (style
.HasTextEffects() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_EFFECTS
))
2219 if (currentStyle
.HasTextEffects())
2221 // We need to find the bits in the new style that are different:
2222 // just look at those bits that are specified by the new style.
2224 int currentRelevantTextEffects
= currentStyle
.GetTextEffects() & style
.GetTextEffectFlags();
2225 int newRelevantTextEffects
= style
.GetTextEffects() & style
.GetTextEffectFlags();
2227 if (currentRelevantTextEffects
!= newRelevantTextEffects
)
2229 // Find the text effects that were different, using XOR
2230 int differentEffects
= currentRelevantTextEffects
^ newRelevantTextEffects
;
2232 // Clash of style - mark as such
2233 multipleTextEffectAttributes
|= differentEffects
;
2234 currentStyle
.SetTextEffectFlags(currentStyle
.GetTextEffectFlags() & ~differentEffects
);
2239 currentStyle
.SetTextEffects(style
.GetTextEffects());
2240 currentStyle
.SetTextEffectFlags(style
.GetTextEffectFlags());
2244 if (style
.HasOutlineLevel() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_OUTLINE_LEVEL
))
2246 if (currentStyle
.HasOutlineLevel())
2248 if (currentStyle
.GetOutlineLevel() != style
.GetOutlineLevel())
2250 // Clash of style - mark as such
2251 multipleStyleAttributes
|= wxTEXT_ATTR_OUTLINE_LEVEL
;
2252 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_OUTLINE_LEVEL
);
2256 currentStyle
.SetOutlineLevel(style
.GetOutlineLevel());
2262 /// Get the combined style for a range - if any attribute is different within the range,
2263 /// that attribute is not present within the flags.
2264 /// *** Note that this is not recursive, and so assumes that content inside a paragraph is not itself
2266 bool wxRichTextParagraphLayoutBox::GetStyleForRange(const wxRichTextRange
& range
, wxTextAttr
& style
)
2268 style
= wxTextAttr();
2270 // The attributes that aren't valid because of multiple styles within the range
2271 long multipleStyleAttributes
= 0;
2272 int multipleTextEffectAttributes
= 0;
2274 wxRichTextObjectList::compatibility_iterator node
= GetChildren().GetFirst();
2277 wxRichTextParagraph
* para
= (wxRichTextParagraph
*) node
->GetData();
2278 if (!(para
->GetRange().GetStart() > range
.GetEnd() || para
->GetRange().GetEnd() < range
.GetStart()))
2280 if (para
->GetChildren().GetCount() == 0)
2282 wxTextAttr paraStyle
= para
->GetCombinedAttributes();
2284 CollectStyle(style
, paraStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
);
2288 wxRichTextRange
paraRange(para
->GetRange());
2289 paraRange
.LimitTo(range
);
2291 // First collect paragraph attributes only
2292 wxTextAttr paraStyle
= para
->GetCombinedAttributes();
2293 paraStyle
.SetFlags(paraStyle
.GetFlags() & wxTEXT_ATTR_PARAGRAPH
);
2294 CollectStyle(style
, paraStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
);
2296 wxRichTextObjectList::compatibility_iterator childNode
= para
->GetChildren().GetFirst();
2300 wxRichTextObject
* child
= childNode
->GetData();
2301 if (!(child
->GetRange().GetStart() > range
.GetEnd() || child
->GetRange().GetEnd() < range
.GetStart()))
2303 wxTextAttr childStyle
= para
->GetCombinedAttributes(child
->GetAttributes());
2305 // Now collect character attributes only
2306 childStyle
.SetFlags(childStyle
.GetFlags() & wxTEXT_ATTR_CHARACTER
);
2308 CollectStyle(style
, childStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
);
2311 childNode
= childNode
->GetNext();
2315 node
= node
->GetNext();
2320 /// Set default style
2321 bool wxRichTextParagraphLayoutBox::SetDefaultStyle(const wxTextAttr
& style
)
2323 m_defaultAttributes
= style
;
2327 /// Test if this whole range has character attributes of the specified kind. If any
2328 /// of the attributes are different within the range, the test fails. You
2329 /// can use this to implement, for example, bold button updating. style must have
2330 /// flags indicating which attributes are of interest.
2331 bool wxRichTextParagraphLayoutBox::HasCharacterAttributes(const wxRichTextRange
& range
, const wxTextAttr
& style
) const
2334 int matchingCount
= 0;
2336 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2339 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2340 wxASSERT (para
!= NULL
);
2344 // Stop searching if we're beyond the range of interest
2345 if (para
->GetRange().GetStart() > range
.GetEnd())
2346 return foundCount
== matchingCount
;
2348 if (!para
->GetRange().IsOutside(range
))
2350 wxRichTextObjectList::compatibility_iterator node2
= para
->GetChildren().GetFirst();
2354 wxRichTextObject
* child
= node2
->GetData();
2355 if (!child
->GetRange().IsOutside(range
) && child
->IsKindOf(CLASSINFO(wxRichTextPlainText
)))
2358 wxTextAttr textAttr
= para
->GetCombinedAttributes(child
->GetAttributes());
2360 if (wxTextAttrEqPartial(textAttr
, style
, style
.GetFlags()))
2364 node2
= node2
->GetNext();
2369 node
= node
->GetNext();
2372 return foundCount
== matchingCount
;
2375 /// Test if this whole range has paragraph attributes of the specified kind. If any
2376 /// of the attributes are different within the range, the test fails. You
2377 /// can use this to implement, for example, centering button updating. style must have
2378 /// flags indicating which attributes are of interest.
2379 bool wxRichTextParagraphLayoutBox::HasParagraphAttributes(const wxRichTextRange
& range
, const wxTextAttr
& style
) const
2382 int matchingCount
= 0;
2384 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2387 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2388 wxASSERT (para
!= NULL
);
2392 // Stop searching if we're beyond the range of interest
2393 if (para
->GetRange().GetStart() > range
.GetEnd())
2394 return foundCount
== matchingCount
;
2396 if (!para
->GetRange().IsOutside(range
))
2398 wxTextAttr textAttr
= GetAttributes();
2399 // Apply the paragraph style
2400 wxRichTextApplyStyle(textAttr
, para
->GetAttributes());
2403 if (wxTextAttrEqPartial(textAttr
, style
, style
.GetFlags()))
2408 node
= node
->GetNext();
2410 return foundCount
== matchingCount
;
2413 void wxRichTextParagraphLayoutBox::Clear()
2418 void wxRichTextParagraphLayoutBox::Reset()
2422 wxRichTextBuffer
* buffer
= wxDynamicCast(this, wxRichTextBuffer
);
2423 if (buffer
&& GetRichTextCtrl())
2425 wxRichTextEvent
event(wxEVT_COMMAND_RICHTEXT_BUFFER_RESET
, GetRichTextCtrl()->GetId());
2426 event
.SetEventObject(GetRichTextCtrl());
2428 buffer
->SendEvent(event
, true);
2431 AddParagraph(wxEmptyString
);
2433 Invalidate(wxRICHTEXT_ALL
);
2436 /// Invalidate the buffer. With no argument, invalidates whole buffer.
2437 void wxRichTextParagraphLayoutBox::Invalidate(const wxRichTextRange
& invalidRange
)
2441 if (invalidRange
== wxRICHTEXT_ALL
)
2443 m_invalidRange
= wxRICHTEXT_ALL
;
2447 // Already invalidating everything
2448 if (m_invalidRange
== wxRICHTEXT_ALL
)
2451 if ((invalidRange
.GetStart() < m_invalidRange
.GetStart()) || m_invalidRange
.GetStart() == -1)
2452 m_invalidRange
.SetStart(invalidRange
.GetStart());
2453 if (invalidRange
.GetEnd() > m_invalidRange
.GetEnd())
2454 m_invalidRange
.SetEnd(invalidRange
.GetEnd());
2457 /// Get invalid range, rounding to entire paragraphs if argument is true.
2458 wxRichTextRange
wxRichTextParagraphLayoutBox::GetInvalidRange(bool wholeParagraphs
) const
2460 if (m_invalidRange
== wxRICHTEXT_ALL
|| m_invalidRange
== wxRICHTEXT_NONE
)
2461 return m_invalidRange
;
2463 wxRichTextRange range
= m_invalidRange
;
2465 if (wholeParagraphs
)
2467 wxRichTextParagraph
* para1
= GetParagraphAtPosition(range
.GetStart());
2468 wxRichTextParagraph
* para2
= GetParagraphAtPosition(range
.GetEnd());
2470 range
.SetStart(para1
->GetRange().GetStart());
2472 range
.SetEnd(para2
->GetRange().GetEnd());
2477 /// Apply the style sheet to the buffer, for example if the styles have changed.
2478 bool wxRichTextParagraphLayoutBox::ApplyStyleSheet(wxRichTextStyleSheet
* styleSheet
)
2480 wxASSERT(styleSheet
!= NULL
);
2486 wxRichTextAttr
attr(GetBasicStyle());
2487 if (GetBasicStyle().HasParagraphStyleName())
2489 wxRichTextParagraphStyleDefinition
* paraDef
= styleSheet
->FindParagraphStyle(GetBasicStyle().GetParagraphStyleName());
2492 attr
.Apply(paraDef
->GetStyleMergedWithBase(styleSheet
));
2493 SetBasicStyle(attr
);
2498 if (GetBasicStyle().HasCharacterStyleName())
2500 wxRichTextCharacterStyleDefinition
* charDef
= styleSheet
->FindCharacterStyle(GetBasicStyle().GetCharacterStyleName());
2503 attr
.Apply(charDef
->GetStyleMergedWithBase(styleSheet
));
2504 SetBasicStyle(attr
);
2509 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2512 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2513 wxASSERT (para
!= NULL
);
2517 // Combine paragraph and list styles. If there is a list style in the original attributes,
2518 // the current indentation overrides anything else and is used to find the item indentation.
2519 // Also, for applying paragraph styles, consider having 2 modes: (1) we merge with what we have,
2520 // thereby taking into account all user changes, (2) reset the style completely (except for indentation/list
2521 // exception as above).
2522 // Problem: when changing from one list style to another, there's a danger that the level info will get lost.
2523 // So when changing a list style interactively, could retrieve level based on current style, then
2524 // set appropriate indent and apply new style.
2526 if (!para
->GetAttributes().GetParagraphStyleName().IsEmpty() && !para
->GetAttributes().GetListStyleName().IsEmpty())
2528 int currentIndent
= para
->GetAttributes().GetLeftIndent();
2530 wxRichTextParagraphStyleDefinition
* paraDef
= styleSheet
->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
2531 wxRichTextListStyleDefinition
* listDef
= styleSheet
->FindListStyle(para
->GetAttributes().GetListStyleName());
2532 if (paraDef
&& !listDef
)
2534 para
->GetAttributes() = paraDef
->GetStyleMergedWithBase(styleSheet
);
2537 else if (listDef
&& !paraDef
)
2539 // Set overall style defined for the list style definition
2540 para
->GetAttributes() = listDef
->GetStyleMergedWithBase(styleSheet
);
2542 // Apply the style for this level
2543 wxRichTextApplyStyle(para
->GetAttributes(), * listDef
->GetLevelAttributes(listDef
->FindLevelForIndent(currentIndent
)));
2546 else if (listDef
&& paraDef
)
2548 // Combines overall list style, style for level, and paragraph style
2549 para
->GetAttributes() = listDef
->CombineWithParagraphStyle(currentIndent
, paraDef
->GetStyleMergedWithBase(styleSheet
));
2553 else if (para
->GetAttributes().GetParagraphStyleName().IsEmpty() && !para
->GetAttributes().GetListStyleName().IsEmpty())
2555 int currentIndent
= para
->GetAttributes().GetLeftIndent();
2557 wxRichTextListStyleDefinition
* listDef
= styleSheet
->FindListStyle(para
->GetAttributes().GetListStyleName());
2559 // Overall list definition style
2560 para
->GetAttributes() = listDef
->GetStyleMergedWithBase(styleSheet
);
2562 // Style for this level
2563 wxRichTextApplyStyle(para
->GetAttributes(), * listDef
->GetLevelAttributes(listDef
->FindLevelForIndent(currentIndent
)));
2567 else if (!para
->GetAttributes().GetParagraphStyleName().IsEmpty() && para
->GetAttributes().GetListStyleName().IsEmpty())
2569 wxRichTextParagraphStyleDefinition
* def
= styleSheet
->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
2572 para
->GetAttributes() = def
->GetStyleMergedWithBase(styleSheet
);
2578 node
= node
->GetNext();
2580 return foundCount
!= 0;
2584 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2586 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2588 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
2589 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2590 bool specifyLevel
= ((flags
& wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL
) != 0);
2591 bool renumber
= ((flags
& wxRICHTEXT_SETSTYLE_RENUMBER
) != 0);
2593 // Current number, if numbering
2596 wxASSERT (!specifyLevel
|| (specifyLevel
&& (specifiedLevel
>= 0)));
2598 // If we are associated with a control, make undoable; otherwise, apply immediately
2601 bool haveControl
= (GetRichTextCtrl() != NULL
);
2603 wxRichTextAction
* action
= NULL
;
2605 if (haveControl
&& withUndo
)
2607 action
= new wxRichTextAction(NULL
, _("Change List Style"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2608 action
->SetRange(range
);
2609 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2612 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2615 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2616 wxASSERT (para
!= NULL
);
2618 if (para
&& para
->GetChildCount() > 0)
2620 // Stop searching if we're beyond the range of interest
2621 if (para
->GetRange().GetStart() > range
.GetEnd())
2624 if (!para
->GetRange().IsOutside(range
))
2626 // We'll be using a copy of the paragraph to make style changes,
2627 // not updating the buffer directly.
2628 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
2630 if (haveControl
&& withUndo
)
2632 newPara
= new wxRichTextParagraph(*para
);
2633 action
->GetNewParagraphs().AppendChild(newPara
);
2635 // Also store the old ones for Undo
2636 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
2643 int thisIndent
= newPara
->GetAttributes().GetLeftIndent();
2644 int thisLevel
= specifyLevel
? specifiedLevel
: def
->FindLevelForIndent(thisIndent
);
2646 // How is numbering going to work?
2647 // If we are renumbering, or numbering for the first time, we need to keep
2648 // track of the number for each level. But we might be simply applying a different
2650 // In Word, applying a style to several paragraphs, even if at different levels,
2651 // reverts the level back to the same one. So we could do the same here.
2652 // Renumbering will need to be done when we promote/demote a paragraph.
2654 // Apply the overall list style, and item style for this level
2655 wxTextAttr
listStyle(def
->GetCombinedStyleForLevel(thisLevel
, styleSheet
));
2656 wxRichTextApplyStyle(newPara
->GetAttributes(), listStyle
);
2658 // Now we need to do numbering
2661 newPara
->GetAttributes().SetBulletNumber(n
);
2666 else if (!newPara
->GetAttributes().GetListStyleName().IsEmpty())
2668 // if def is NULL, remove list style, applying any associated paragraph style
2669 // to restore the attributes
2671 newPara
->GetAttributes().SetListStyleName(wxEmptyString
);
2672 newPara
->GetAttributes().SetLeftIndent(0, 0);
2673 newPara
->GetAttributes().SetBulletText(wxEmptyString
);
2675 // Eliminate the main list-related attributes
2676 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
);
2678 if (styleSheet
&& !newPara
->GetAttributes().GetParagraphStyleName().IsEmpty())
2680 wxRichTextParagraphStyleDefinition
* def
= styleSheet
->FindParagraphStyle(newPara
->GetAttributes().GetParagraphStyleName());
2683 newPara
->GetAttributes() = def
->GetStyleMergedWithBase(styleSheet
);
2690 node
= node
->GetNext();
2693 // Do action, or delay it until end of batch.
2694 if (haveControl
&& withUndo
)
2695 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
2700 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int startFrom
, int specifiedLevel
)
2702 if (GetStyleSheet())
2704 wxRichTextListStyleDefinition
* def
= GetStyleSheet()->FindListStyle(defName
);
2706 return SetListStyle(range
, def
, flags
, startFrom
, specifiedLevel
);
2711 /// Clear list for given range
2712 bool wxRichTextParagraphLayoutBox::ClearListStyle(const wxRichTextRange
& range
, int flags
)
2714 return SetListStyle(range
, NULL
, flags
);
2717 /// Number/renumber any list elements in the given range
2718 bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2720 return DoNumberList(range
, range
, 0, def
, flags
, startFrom
, specifiedLevel
);
2723 /// Number/renumber any list elements in the given range. Also do promotion or demotion of items, if specified
2724 bool wxRichTextParagraphLayoutBox::DoNumberList(const wxRichTextRange
& range
, const wxRichTextRange
& promotionRange
, int promoteBy
,
2725 wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2727 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2729 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
2730 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2732 bool specifyLevel
= ((flags
& wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL
) != 0);
2735 bool renumber
= ((flags
& wxRICHTEXT_SETSTYLE_RENUMBER
) != 0);
2737 // Max number of levels
2738 const int maxLevels
= 10;
2740 // The level we're looking at now
2741 int currentLevel
= -1;
2743 // The item number for each level
2744 int levels
[maxLevels
];
2747 // Reset all numbering
2748 for (i
= 0; i
< maxLevels
; i
++)
2750 if (startFrom
!= -1)
2751 levels
[i
] = startFrom
-1;
2752 else if (renumber
) // start again
2755 levels
[i
] = -1; // start from the number we found, if any
2758 wxASSERT(!specifyLevel
|| (specifyLevel
&& (specifiedLevel
>= 0)));
2760 // If we are associated with a control, make undoable; otherwise, apply immediately
2763 bool haveControl
= (GetRichTextCtrl() != NULL
);
2765 wxRichTextAction
* action
= NULL
;
2767 if (haveControl
&& withUndo
)
2769 action
= new wxRichTextAction(NULL
, _("Renumber List"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2770 action
->SetRange(range
);
2771 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2774 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2777 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2778 wxASSERT (para
!= NULL
);
2780 if (para
&& para
->GetChildCount() > 0)
2782 // Stop searching if we're beyond the range of interest
2783 if (para
->GetRange().GetStart() > range
.GetEnd())
2786 if (!para
->GetRange().IsOutside(range
))
2788 // We'll be using a copy of the paragraph to make style changes,
2789 // not updating the buffer directly.
2790 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
2792 if (haveControl
&& withUndo
)
2794 newPara
= new wxRichTextParagraph(*para
);
2795 action
->GetNewParagraphs().AppendChild(newPara
);
2797 // Also store the old ones for Undo
2798 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
2803 wxRichTextListStyleDefinition
* defToUse
= def
;
2806 if (styleSheet
&& !newPara
->GetAttributes().GetListStyleName().IsEmpty())
2807 defToUse
= styleSheet
->FindListStyle(newPara
->GetAttributes().GetListStyleName());
2812 int thisIndent
= newPara
->GetAttributes().GetLeftIndent();
2813 int thisLevel
= defToUse
->FindLevelForIndent(thisIndent
);
2815 // If we've specified a level to apply to all, change the level.
2816 if (specifiedLevel
!= -1)
2817 thisLevel
= specifiedLevel
;
2819 // Do promotion if specified
2820 if ((promoteBy
!= 0) && !para
->GetRange().IsOutside(promotionRange
))
2822 thisLevel
= thisLevel
- promoteBy
;
2829 // Apply the overall list style, and item style for this level
2830 wxTextAttr
listStyle(defToUse
->GetCombinedStyleForLevel(thisLevel
, styleSheet
));
2831 wxRichTextApplyStyle(newPara
->GetAttributes(), listStyle
);
2833 // OK, we've (re)applied the style, now let's get the numbering right.
2835 if (currentLevel
== -1)
2836 currentLevel
= thisLevel
;
2838 // Same level as before, do nothing except increment level's number afterwards
2839 if (currentLevel
== thisLevel
)
2842 // A deeper level: start renumbering all levels after current level
2843 else if (thisLevel
> currentLevel
)
2845 for (i
= currentLevel
+1; i
<= thisLevel
; i
++)
2849 currentLevel
= thisLevel
;
2851 else if (thisLevel
< currentLevel
)
2853 currentLevel
= thisLevel
;
2856 // Use the current numbering if -1 and we have a bullet number already
2857 if (levels
[currentLevel
] == -1)
2859 if (newPara
->GetAttributes().HasBulletNumber())
2860 levels
[currentLevel
] = newPara
->GetAttributes().GetBulletNumber();
2862 levels
[currentLevel
] = 1;
2866 levels
[currentLevel
] ++;
2869 newPara
->GetAttributes().SetBulletNumber(levels
[currentLevel
]);
2871 // Create the bullet text if an outline list
2872 if (listStyle
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
)
2875 for (i
= 0; i
<= currentLevel
; i
++)
2877 if (!text
.IsEmpty())
2879 text
+= wxString::Format(wxT("%d"), levels
[i
]);
2881 newPara
->GetAttributes().SetBulletText(text
);
2887 node
= node
->GetNext();
2890 // Do action, or delay it until end of batch.
2891 if (haveControl
&& withUndo
)
2892 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
2897 bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int startFrom
, int specifiedLevel
)
2899 if (GetStyleSheet())
2901 wxRichTextListStyleDefinition
* def
= NULL
;
2902 if (!defName
.IsEmpty())
2903 def
= GetStyleSheet()->FindListStyle(defName
);
2904 return NumberList(range
, def
, flags
, startFrom
, specifiedLevel
);
2909 /// Promote the list items within the given range. promoteBy can be a positive or negative number, e.g. 1 or -1
2910 bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy
, const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int specifiedLevel
)
2913 // One strategy is to first work out the range within which renumbering must occur. Then could pass these two ranges
2914 // to NumberList with a flag indicating promotion is required within one of the ranges.
2915 // Find first and last paragraphs in range. Then for first, calculate new indentation and look back until we find
2916 // a paragraph that either has no list style, or has one that is different or whose indentation is less.
2917 // We start renumbering from the para after that different para we found. We specify that the numbering of that
2918 // list position will start from 1.
2919 // Similarly, we look after the last para in the promote range for an indentation that is less (or no list style).
2920 // We can end the renumbering at this point.
2922 // For now, only renumber within the promotion range.
2924 return DoNumberList(range
, range
, promoteBy
, def
, flags
, 1, specifiedLevel
);
2927 bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy
, const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int specifiedLevel
)
2929 if (GetStyleSheet())
2931 wxRichTextListStyleDefinition
* def
= NULL
;
2932 if (!defName
.IsEmpty())
2933 def
= GetStyleSheet()->FindListStyle(defName
);
2934 return PromoteList(promoteBy
, range
, def
, flags
, specifiedLevel
);
2939 /// Fills in the attributes for numbering a paragraph after previousParagraph. It also finds the
2940 /// position of the paragraph that it had to start looking from.
2941 bool wxRichTextParagraphLayoutBox::FindNextParagraphNumber(wxRichTextParagraph
* previousParagraph
, wxTextAttr
& attr
) const
2943 if (!previousParagraph
->GetAttributes().HasFlag(wxTEXT_ATTR_BULLET_STYLE
) || previousParagraph
->GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE
)
2946 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2947 if (styleSheet
&& !previousParagraph
->GetAttributes().GetListStyleName().IsEmpty())
2949 wxRichTextListStyleDefinition
* def
= styleSheet
->FindListStyle(previousParagraph
->GetAttributes().GetListStyleName());
2952 // int thisIndent = previousParagraph->GetAttributes().GetLeftIndent();
2953 // int thisLevel = def->FindLevelForIndent(thisIndent);
2955 bool isOutline
= (previousParagraph
->GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
) != 0;
2957 attr
.SetFlags(previousParagraph
->GetAttributes().GetFlags() & (wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_BULLET_NUMBER
|wxTEXT_ATTR_BULLET_TEXT
|wxTEXT_ATTR_BULLET_NAME
));
2958 if (previousParagraph
->GetAttributes().HasBulletName())
2959 attr
.SetBulletName(previousParagraph
->GetAttributes().GetBulletName());
2960 attr
.SetBulletStyle(previousParagraph
->GetAttributes().GetBulletStyle());
2961 attr
.SetListStyleName(previousParagraph
->GetAttributes().GetListStyleName());
2963 int nextNumber
= previousParagraph
->GetAttributes().GetBulletNumber() + 1;
2964 attr
.SetBulletNumber(nextNumber
);
2968 wxString text
= previousParagraph
->GetAttributes().GetBulletText();
2969 if (!text
.IsEmpty())
2971 int pos
= text
.Find(wxT('.'), true);
2972 if (pos
!= wxNOT_FOUND
)
2974 text
= text
.Mid(0, text
.Length() - pos
- 1);
2977 text
= wxEmptyString
;
2978 if (!text
.IsEmpty())
2980 text
+= wxString::Format(wxT("%d"), nextNumber
);
2981 attr
.SetBulletText(text
);
2995 * wxRichTextParagraph
2996 * This object represents a single paragraph (or in a straight text editor, a line).
2999 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraph
, wxRichTextBox
)
3001 wxArrayInt
wxRichTextParagraph::sm_defaultTabs
;
3003 wxRichTextParagraph::wxRichTextParagraph(wxRichTextObject
* parent
, wxTextAttr
* style
):
3004 wxRichTextBox(parent
)
3007 SetAttributes(*style
);
3010 wxRichTextParagraph::wxRichTextParagraph(const wxString
& text
, wxRichTextObject
* parent
, wxTextAttr
* paraStyle
, wxTextAttr
* charStyle
):
3011 wxRichTextBox(parent
)
3014 SetAttributes(*paraStyle
);
3016 AppendChild(new wxRichTextPlainText(text
, this, charStyle
));
3019 wxRichTextParagraph::~wxRichTextParagraph()
3025 bool wxRichTextParagraph::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& WXUNUSED(rect
), int WXUNUSED(descent
), int style
)
3027 wxTextAttr attr
= GetCombinedAttributes();
3029 // Draw the bullet, if any
3030 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3032 if (attr
.GetLeftSubIndent() != 0)
3034 int spaceBeforePara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingBefore());
3035 int leftIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftIndent());
3037 wxTextAttr
bulletAttr(GetCombinedAttributes());
3039 // Combine with the font of the first piece of content, if one is specified
3040 if (GetChildren().GetCount() > 0)
3042 wxRichTextObject
* firstObj
= (wxRichTextObject
*) GetChildren().GetFirst()->GetData();
3043 if (firstObj
->GetAttributes().HasFont())
3045 wxRichTextApplyStyle(bulletAttr
, firstObj
->GetAttributes());
3049 // Get line height from first line, if any
3050 wxRichTextLine
* line
= m_cachedLines
.GetFirst() ? (wxRichTextLine
* ) m_cachedLines
.GetFirst()->GetData() : (wxRichTextLine
*) NULL
;
3053 int lineHeight
wxDUMMY_INITIALIZE(0);
3056 lineHeight
= line
->GetSize().y
;
3057 linePos
= line
->GetPosition() + GetPosition();
3062 if (bulletAttr
.HasFont() && GetBuffer())
3063 font
= GetBuffer()->GetFontTable().FindFont(bulletAttr
);
3065 font
= (*wxNORMAL_FONT
);
3067 wxCheckSetFont(dc
, font
);
3069 lineHeight
= dc
.GetCharHeight();
3070 linePos
= GetPosition();
3071 linePos
.y
+= spaceBeforePara
;
3074 wxRect
bulletRect(GetPosition().x
+ leftIndent
, linePos
.y
, linePos
.x
- (GetPosition().x
+ leftIndent
), lineHeight
);
3076 if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP
)
3078 if (wxRichTextBuffer::GetRenderer())
3079 wxRichTextBuffer::GetRenderer()->DrawBitmapBullet(this, dc
, bulletAttr
, bulletRect
);
3081 else if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_STANDARD
)
3083 if (wxRichTextBuffer::GetRenderer())
3084 wxRichTextBuffer::GetRenderer()->DrawStandardBullet(this, dc
, bulletAttr
, bulletRect
);
3088 wxString bulletText
= GetBulletText();
3090 if (!bulletText
.empty() && wxRichTextBuffer::GetRenderer())
3091 wxRichTextBuffer::GetRenderer()->DrawTextBullet(this, dc
, bulletAttr
, bulletRect
, bulletText
);
3096 // Draw the range for each line, one object at a time.
3098 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3101 wxRichTextLine
* line
= node
->GetData();
3102 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3104 int maxDescent
= line
->GetDescent();
3106 // Lines are specified relative to the paragraph
3108 wxPoint linePosition
= line
->GetPosition() + GetPosition();
3109 wxPoint objectPosition
= linePosition
;
3111 // Loop through objects until we get to the one within range
3112 wxRichTextObjectList::compatibility_iterator node2
= m_children
.GetFirst();
3115 wxRichTextObject
* child
= node2
->GetData();
3117 if (!child
->GetRange().IsOutside(lineRange
) && !lineRange
.IsOutside(range
))
3119 // Draw this part of the line at the correct position
3120 wxRichTextRange
objectRange(child
->GetRange());
3121 objectRange
.LimitTo(lineRange
);
3125 child
->GetRangeSize(objectRange
, objectSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, objectPosition
);
3127 // Use the child object's width, but the whole line's height
3128 wxRect
childRect(objectPosition
, wxSize(objectSize
.x
, line
->GetSize().y
));
3129 child
->Draw(dc
, objectRange
, selectionRange
, childRect
, maxDescent
, style
);
3131 objectPosition
.x
+= objectSize
.x
;
3133 else if (child
->GetRange().GetStart() > lineRange
.GetEnd())
3134 // Can break out of inner loop now since we've passed this line's range
3137 node2
= node2
->GetNext();
3140 node
= node
->GetNext();
3146 /// Lay the item out
3147 bool wxRichTextParagraph::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
3149 wxTextAttr attr
= GetCombinedAttributes();
3153 // Increase the size of the paragraph due to spacing
3154 int spaceBeforePara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingBefore());
3155 int spaceAfterPara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingAfter());
3156 int leftIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftIndent());
3157 int leftSubIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftSubIndent());
3158 int rightIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetRightIndent());
3160 int lineSpacing
= 0;
3162 // Let's assume line spacing of 10 is normal, 15 is 1.5, 20 is 2, etc.
3163 if (attr
.GetLineSpacing() != 10 && GetBuffer())
3165 wxFont
font(GetBuffer()->GetFontTable().FindFont(attr
));
3166 wxCheckSetFont(dc
, font
);
3167 lineSpacing
= (ConvertTenthsMMToPixels(dc
, dc
.GetCharHeight()) * attr
.GetLineSpacing())/10;
3170 // Available space for text on each line differs.
3171 int availableTextSpaceFirstLine
= rect
.GetWidth() - leftIndent
- rightIndent
;
3173 // Bullets start the text at the same position as subsequent lines
3174 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3175 availableTextSpaceFirstLine
-= leftSubIndent
;
3177 int availableTextSpaceSubsequentLines
= rect
.GetWidth() - leftIndent
- rightIndent
- leftSubIndent
;
3179 // Start position for each line relative to the paragraph
3180 int startPositionFirstLine
= leftIndent
;
3181 int startPositionSubsequentLines
= leftIndent
+ leftSubIndent
;
3183 // If we have a bullet in this paragraph, the start position for the first line's text
3184 // is actually leftIndent + leftSubIndent.
3185 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3186 startPositionFirstLine
= startPositionSubsequentLines
;
3188 long lastEndPos
= GetRange().GetStart()-1;
3189 long lastCompletedEndPos
= lastEndPos
;
3191 int currentWidth
= 0;
3192 SetPosition(rect
.GetPosition());
3194 wxPoint
currentPosition(0, spaceBeforePara
); // We will calculate lines relative to paragraph
3201 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3204 wxRichTextObject
* child
= node
->GetData();
3206 child
->SetCachedSize(wxDefaultSize
);
3207 child
->Layout(dc
, rect
, style
);
3209 node
= node
->GetNext();
3214 // We may need to go back to a previous child, in which case create the new line,
3215 // find the child corresponding to the start position of the string, and
3218 node
= m_children
.GetFirst();
3221 wxRichTextObject
* child
= node
->GetData();
3223 // If this is e.g. a composite text box, it will need to be laid out itself.
3224 // But if just a text fragment or image, for example, this will
3225 // do nothing. NB: won't we need to set the position after layout?
3226 // since for example if position is dependent on vertical line size, we
3227 // can't tell the position until the size is determined. So possibly introduce
3228 // another layout phase.
3230 // Available width depends on whether we're on the first or subsequent lines
3231 int availableSpaceForText
= (lineCount
== 0 ? availableTextSpaceFirstLine
: availableTextSpaceSubsequentLines
);
3233 currentPosition
.x
= (lineCount
== 0 ? startPositionFirstLine
: startPositionSubsequentLines
);
3235 // We may only be looking at part of a child, if we searched back for wrapping
3236 // and found a suitable point some way into the child. So get the size for the fragment
3239 long nextBreakPos
= GetFirstLineBreakPosition(lastEndPos
+1);
3240 long lastPosToUse
= child
->GetRange().GetEnd();
3241 bool lineBreakInThisObject
= (nextBreakPos
> -1 && nextBreakPos
<= child
->GetRange().GetEnd());
3243 if (lineBreakInThisObject
)
3244 lastPosToUse
= nextBreakPos
;
3247 int childDescent
= 0;
3249 if ((nextBreakPos
== -1) && (lastEndPos
== child
->GetRange().GetStart() - 1)) // i.e. we want to get the whole thing
3251 childSize
= child
->GetCachedSize();
3252 childDescent
= child
->GetDescent();
3255 GetRangeSize(wxRichTextRange(lastEndPos
+1, lastPosToUse
), childSize
, childDescent
, dc
, wxRICHTEXT_UNFORMATTED
, rect
.GetPosition());
3258 // 1) There was a line break BEFORE the natural break
3259 // 2) There was a line break AFTER the natural break
3260 // 3) The child still fits (carry on)
3262 if ((lineBreakInThisObject
&& (childSize
.x
+ currentWidth
<= availableSpaceForText
)) ||
3263 (childSize
.x
+ currentWidth
> availableSpaceForText
))
3265 long wrapPosition
= 0;
3267 // Find a place to wrap. This may walk back to previous children,
3268 // for example if a word spans several objects.
3269 if (!FindWrapPosition(wxRichTextRange(lastCompletedEndPos
+1, child
->GetRange().GetEnd()), dc
, availableSpaceForText
, wrapPosition
))
3271 // If the function failed, just cut it off at the end of this child.
3272 wrapPosition
= child
->GetRange().GetEnd();
3275 // FindWrapPosition can still return a value that will put us in an endless wrapping loop
3276 if (wrapPosition
<= lastCompletedEndPos
)
3277 wrapPosition
= wxMax(lastCompletedEndPos
+1,child
->GetRange().GetEnd());
3279 // wxLogDebug(wxT("Split at %ld"), wrapPosition);
3281 // Let's find the actual size of the current line now
3283 wxRichTextRange
actualRange(lastCompletedEndPos
+1, wrapPosition
);
3284 GetRangeSize(actualRange
, actualSize
, childDescent
, dc
, wxRICHTEXT_UNFORMATTED
);
3285 currentWidth
= actualSize
.x
;
3286 lineHeight
= wxMax(lineHeight
, actualSize
.y
);
3287 maxDescent
= wxMax(childDescent
, maxDescent
);
3290 wxRichTextLine
* line
= AllocateLine(lineCount
);
3292 // Set relative range so we won't have to change line ranges when paragraphs are moved
3293 line
->SetRange(wxRichTextRange(actualRange
.GetStart() - GetRange().GetStart(), actualRange
.GetEnd() - GetRange().GetStart()));
3294 line
->SetPosition(currentPosition
);
3295 line
->SetSize(wxSize(currentWidth
, lineHeight
));
3296 line
->SetDescent(maxDescent
);
3298 // Now move down a line. TODO: add margins, spacing
3299 currentPosition
.y
+= lineHeight
;
3300 currentPosition
.y
+= lineSpacing
;
3303 maxWidth
= wxMax(maxWidth
, currentWidth
);
3307 // TODO: account for zero-length objects, such as fields
3308 wxASSERT(wrapPosition
> lastCompletedEndPos
);
3310 lastEndPos
= wrapPosition
;
3311 lastCompletedEndPos
= lastEndPos
;
3315 // May need to set the node back to a previous one, due to searching back in wrapping
3316 wxRichTextObject
* childAfterWrapPosition
= FindObjectAtPosition(wrapPosition
+1);
3317 if (childAfterWrapPosition
)
3318 node
= m_children
.Find(childAfterWrapPosition
);
3320 node
= node
->GetNext();
3324 // We still fit, so don't add a line, and keep going
3325 currentWidth
+= childSize
.x
;
3326 lineHeight
= wxMax(lineHeight
, childSize
.y
);
3327 maxDescent
= wxMax(childDescent
, maxDescent
);
3329 maxWidth
= wxMax(maxWidth
, currentWidth
);
3330 lastEndPos
= child
->GetRange().GetEnd();
3332 node
= node
->GetNext();
3336 // Add the last line - it's the current pos -> last para pos
3337 // Substract -1 because the last position is always the end-paragraph position.
3338 if (lastCompletedEndPos
<= GetRange().GetEnd()-1)
3340 currentPosition
.x
= (lineCount
== 0 ? startPositionFirstLine
: startPositionSubsequentLines
);
3342 wxRichTextLine
* line
= AllocateLine(lineCount
);
3344 wxRichTextRange
actualRange(lastCompletedEndPos
+1, GetRange().GetEnd()-1);
3346 // Set relative range so we won't have to change line ranges when paragraphs are moved
3347 line
->SetRange(wxRichTextRange(actualRange
.GetStart() - GetRange().GetStart(), actualRange
.GetEnd() - GetRange().GetStart()));
3349 line
->SetPosition(currentPosition
);
3351 if (lineHeight
== 0 && GetBuffer())
3353 wxFont
font(GetBuffer()->GetFontTable().FindFont(attr
));
3354 wxCheckSetFont(dc
, font
);
3355 lineHeight
= dc
.GetCharHeight();
3357 if (maxDescent
== 0)
3360 dc
.GetTextExtent(wxT("X"), & w
, &h
, & maxDescent
);
3363 line
->SetSize(wxSize(currentWidth
, lineHeight
));
3364 line
->SetDescent(maxDescent
);
3365 currentPosition
.y
+= lineHeight
;
3366 currentPosition
.y
+= lineSpacing
;
3370 // Remove remaining unused line objects, if any
3371 ClearUnusedLines(lineCount
);
3373 // Apply styles to wrapped lines
3374 ApplyParagraphStyle(attr
, rect
);
3376 SetCachedSize(wxSize(maxWidth
, currentPosition
.y
+ spaceBeforePara
+ spaceAfterPara
));
3383 /// Apply paragraph styles, such as centering, to wrapped lines
3384 void wxRichTextParagraph::ApplyParagraphStyle(const wxTextAttr
& attr
, const wxRect
& rect
)
3386 if (!attr
.HasAlignment())
3389 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3392 wxRichTextLine
* line
= node
->GetData();
3394 wxPoint pos
= line
->GetPosition();
3395 wxSize size
= line
->GetSize();
3397 // centering, right-justification
3398 if (attr
.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_CENTRE
)
3400 pos
.x
= (rect
.GetWidth() - size
.x
)/2 + pos
.x
;
3401 line
->SetPosition(pos
);
3403 else if (attr
.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_RIGHT
)
3405 pos
.x
= pos
.x
+ rect
.GetWidth() - size
.x
;
3406 line
->SetPosition(pos
);
3409 node
= node
->GetNext();
3413 /// Insert text at the given position
3414 bool wxRichTextParagraph::InsertText(long pos
, const wxString
& text
)
3416 wxRichTextObject
* childToUse
= NULL
;
3417 wxRichTextObjectList::compatibility_iterator nodeToUse
= wxRichTextObjectList::compatibility_iterator();
3419 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3422 wxRichTextObject
* child
= node
->GetData();
3423 if (child
->GetRange().Contains(pos
) && child
->GetRange().GetLength() > 0)
3430 node
= node
->GetNext();
3435 wxRichTextPlainText
* textObject
= wxDynamicCast(childToUse
, wxRichTextPlainText
);
3438 int posInString
= pos
- textObject
->GetRange().GetStart();
3440 wxString newText
= textObject
->GetText().Mid(0, posInString
) +
3441 text
+ textObject
->GetText().Mid(posInString
);
3442 textObject
->SetText(newText
);
3444 int textLength
= text
.length();
3446 textObject
->SetRange(wxRichTextRange(textObject
->GetRange().GetStart(),
3447 textObject
->GetRange().GetEnd() + textLength
));
3449 // Increment the end range of subsequent fragments in this paragraph.
3450 // We'll set the paragraph range itself at a higher level.
3452 wxRichTextObjectList::compatibility_iterator node
= nodeToUse
->GetNext();
3455 wxRichTextObject
* child
= node
->GetData();
3456 child
->SetRange(wxRichTextRange(textObject
->GetRange().GetStart() + textLength
,
3457 textObject
->GetRange().GetEnd() + textLength
));
3459 node
= node
->GetNext();
3466 // TODO: if not a text object, insert at closest position, e.g. in front of it
3472 // Don't pass parent initially to suppress auto-setting of parent range.
3473 // We'll do that at a higher level.
3474 wxRichTextPlainText
* textObject
= new wxRichTextPlainText(text
, this);
3476 AppendChild(textObject
);
3483 void wxRichTextParagraph::Copy(const wxRichTextParagraph
& obj
)
3485 wxRichTextBox::Copy(obj
);
3488 /// Clear the cached lines
3489 void wxRichTextParagraph::ClearLines()
3491 WX_CLEAR_LIST(wxRichTextLineList
, m_cachedLines
);
3494 /// Get/set the object size for the given range. Returns false if the range
3495 /// is invalid for this object.
3496 bool wxRichTextParagraph::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
) const
3498 if (!range
.IsWithin(GetRange()))
3501 if (flags
& wxRICHTEXT_UNFORMATTED
)
3503 // Just use unformatted data, assume no line breaks
3504 // TODO: take into account line breaks
3508 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3511 wxRichTextObject
* child
= node
->GetData();
3512 if (!child
->GetRange().IsOutside(range
))
3516 wxRichTextRange rangeToUse
= range
;
3517 rangeToUse
.LimitTo(child
->GetRange());
3518 int childDescent
= 0;
3520 if (child
->GetRangeSize(rangeToUse
, childSize
, childDescent
, dc
, flags
, wxPoint(position
.x
+ sz
.x
, position
.y
)))
3522 sz
.y
= wxMax(sz
.y
, childSize
.y
);
3523 sz
.x
+= childSize
.x
;
3524 descent
= wxMax(descent
, childDescent
);
3528 node
= node
->GetNext();
3534 // Use formatted data, with line breaks
3537 // We're going to loop through each line, and then for each line,
3538 // call GetRangeSize for the fragment that comprises that line.
3539 // Only we have to do that multiple times within the line, because
3540 // the line may be broken into pieces. For now ignore line break commands
3541 // (so we can assume that getting the unformatted size for a fragment
3542 // within a line is the actual size)
3544 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3547 wxRichTextLine
* line
= node
->GetData();
3548 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3549 if (!lineRange
.IsOutside(range
))
3553 wxRichTextObjectList::compatibility_iterator node2
= m_children
.GetFirst();
3556 wxRichTextObject
* child
= node2
->GetData();
3558 if (!child
->GetRange().IsOutside(lineRange
))
3560 wxRichTextRange rangeToUse
= lineRange
;
3561 rangeToUse
.LimitTo(child
->GetRange());
3564 int childDescent
= 0;
3565 if (child
->GetRangeSize(rangeToUse
, childSize
, childDescent
, dc
, flags
, wxPoint(position
.x
+ sz
.x
, position
.y
)))
3567 lineSize
.y
= wxMax(lineSize
.y
, childSize
.y
);
3568 lineSize
.x
+= childSize
.x
;
3570 descent
= wxMax(descent
, childDescent
);
3573 node2
= node2
->GetNext();
3576 // Increase size by a line (TODO: paragraph spacing)
3578 sz
.x
= wxMax(sz
.x
, lineSize
.x
);
3580 node
= node
->GetNext();
3587 /// Finds the absolute position and row height for the given character position
3588 bool wxRichTextParagraph::FindPosition(wxDC
& dc
, long index
, wxPoint
& pt
, int* height
, bool forceLineStart
)
3592 wxRichTextLine
* line
= ((wxRichTextParagraphLayoutBox
*)GetParent())->GetLineAtPosition(0);
3594 *height
= line
->GetSize().y
;
3596 *height
= dc
.GetCharHeight();
3598 // -1 means 'the start of the buffer'.
3601 pt
= pt
+ line
->GetPosition();
3606 // The final position in a paragraph is taken to mean the position
3607 // at the start of the next paragraph.
3608 if (index
== GetRange().GetEnd())
3610 wxRichTextParagraphLayoutBox
* parent
= wxDynamicCast(GetParent(), wxRichTextParagraphLayoutBox
);
3611 wxASSERT( parent
!= NULL
);
3613 // Find the height at the next paragraph, if any
3614 wxRichTextLine
* line
= parent
->GetLineAtPosition(index
+ 1);
3617 *height
= line
->GetSize().y
;
3618 pt
= line
->GetAbsolutePosition();
3622 *height
= dc
.GetCharHeight();
3623 int indent
= ConvertTenthsMMToPixels(dc
, m_attributes
.GetLeftIndent());
3624 pt
= wxPoint(indent
, GetCachedSize().y
);
3630 if (index
< GetRange().GetStart() || index
> GetRange().GetEnd())
3633 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3636 wxRichTextLine
* line
= node
->GetData();
3637 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3638 if (index
>= lineRange
.GetStart() && index
<= lineRange
.GetEnd())
3640 // If this is the last point in the line, and we're forcing the
3641 // returned value to be the start of the next line, do the required
3643 if (index
== lineRange
.GetEnd() && forceLineStart
)
3645 if (node
->GetNext())
3647 wxRichTextLine
* nextLine
= node
->GetNext()->GetData();
3648 *height
= nextLine
->GetSize().y
;
3649 pt
= nextLine
->GetAbsolutePosition();
3654 pt
.y
= line
->GetPosition().y
+ GetPosition().y
;
3656 wxRichTextRange
r(lineRange
.GetStart(), index
);
3660 // We find the size of the line up to this point,
3661 // then we can add this size to the line start position and
3662 // paragraph start position to find the actual position.
3664 if (GetRangeSize(r
, rangeSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, line
->GetPosition()+ GetPosition()))
3666 pt
.x
= line
->GetPosition().x
+ GetPosition().x
+ rangeSize
.x
;
3667 *height
= line
->GetSize().y
;
3674 node
= node
->GetNext();
3680 /// Hit-testing: returns a flag indicating hit test details, plus
3681 /// information about position
3682 int wxRichTextParagraph::HitTest(wxDC
& dc
, const wxPoint
& pt
, long& textPosition
)
3684 wxPoint paraPos
= GetPosition();
3686 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3689 wxRichTextLine
* line
= node
->GetData();
3690 wxPoint linePos
= paraPos
+ line
->GetPosition();
3691 wxSize lineSize
= line
->GetSize();
3692 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3694 if (pt
.y
>= linePos
.y
&& pt
.y
<= linePos
.y
+ lineSize
.y
)
3696 if (pt
.x
< linePos
.x
)
3698 textPosition
= lineRange
.GetStart();
3699 return wxRICHTEXT_HITTEST_BEFORE
|wxRICHTEXT_HITTEST_OUTSIDE
;
3701 else if (pt
.x
>= (linePos
.x
+ lineSize
.x
))
3703 textPosition
= lineRange
.GetEnd();
3704 return wxRICHTEXT_HITTEST_AFTER
|wxRICHTEXT_HITTEST_OUTSIDE
;
3709 int lastX
= linePos
.x
;
3710 for (i
= lineRange
.GetStart(); i
<= lineRange
.GetEnd(); i
++)
3715 wxRichTextRange
rangeToUse(lineRange
.GetStart(), i
);
3717 GetRangeSize(rangeToUse
, childSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, linePos
);
3719 int nextX
= childSize
.x
+ linePos
.x
;
3721 if (pt
.x
>= lastX
&& pt
.x
<= nextX
)
3725 // So now we know it's between i-1 and i.
3726 // Let's see if we can be more precise about
3727 // which side of the position it's on.
3729 int midPoint
= (nextX
- lastX
)/2 + lastX
;
3730 if (pt
.x
>= midPoint
)
3731 return wxRICHTEXT_HITTEST_AFTER
;
3733 return wxRICHTEXT_HITTEST_BEFORE
;
3743 node
= node
->GetNext();
3746 return wxRICHTEXT_HITTEST_NONE
;
3749 /// Split an object at this position if necessary, and return
3750 /// the previous object, or NULL if inserting at beginning.
3751 wxRichTextObject
* wxRichTextParagraph::SplitAt(long pos
, wxRichTextObject
** previousObject
)
3753 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3756 wxRichTextObject
* child
= node
->GetData();
3758 if (pos
== child
->GetRange().GetStart())
3762 if (node
->GetPrevious())
3763 *previousObject
= node
->GetPrevious()->GetData();
3765 *previousObject
= NULL
;
3771 if (child
->GetRange().Contains(pos
))
3773 // This should create a new object, transferring part of
3774 // the content to the old object and the rest to the new object.
3775 wxRichTextObject
* newObject
= child
->DoSplit(pos
);
3777 // If we couldn't split this object, just insert in front of it.
3780 // Maybe this is an empty string, try the next one
3785 // Insert the new object after 'child'
3786 if (node
->GetNext())
3787 m_children
.Insert(node
->GetNext(), newObject
);
3789 m_children
.Append(newObject
);
3790 newObject
->SetParent(this);
3793 *previousObject
= child
;
3799 node
= node
->GetNext();
3802 *previousObject
= NULL
;
3806 /// Move content to a list from obj on
3807 void wxRichTextParagraph::MoveToList(wxRichTextObject
* obj
, wxList
& list
)
3809 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(obj
);
3812 wxRichTextObject
* child
= node
->GetData();
3815 wxRichTextObjectList::compatibility_iterator oldNode
= node
;
3817 node
= node
->GetNext();
3819 m_children
.DeleteNode(oldNode
);
3823 /// Add content back from list
3824 void wxRichTextParagraph::MoveFromList(wxList
& list
)
3826 for (wxList::compatibility_iterator node
= list
.GetFirst(); node
; node
= node
->GetNext())
3828 AppendChild((wxRichTextObject
*) node
->GetData());
3833 void wxRichTextParagraph::CalculateRange(long start
, long& end
)
3835 wxRichTextCompositeObject::CalculateRange(start
, end
);
3837 // Add one for end of paragraph
3840 m_range
.SetRange(start
, end
);
3843 /// Find the object at the given position
3844 wxRichTextObject
* wxRichTextParagraph::FindObjectAtPosition(long position
)
3846 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3849 wxRichTextObject
* obj
= node
->GetData();
3850 if (obj
->GetRange().Contains(position
))
3853 node
= node
->GetNext();
3858 /// Get the plain text searching from the start or end of the range.
3859 /// The resulting string may be shorter than the range given.
3860 bool wxRichTextParagraph::GetContiguousPlainText(wxString
& text
, const wxRichTextRange
& range
, bool fromStart
)
3862 text
= wxEmptyString
;
3866 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3869 wxRichTextObject
* obj
= node
->GetData();
3870 if (!obj
->GetRange().IsOutside(range
))
3872 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
3875 text
+= textObj
->GetTextForRange(range
);
3881 node
= node
->GetNext();
3886 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetLast();
3889 wxRichTextObject
* obj
= node
->GetData();
3890 if (!obj
->GetRange().IsOutside(range
))
3892 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
3895 text
= textObj
->GetTextForRange(range
) + text
;
3901 node
= node
->GetPrevious();
3908 /// Find a suitable wrap position.
3909 bool wxRichTextParagraph::FindWrapPosition(const wxRichTextRange
& range
, wxDC
& dc
, int availableSpace
, long& wrapPosition
)
3911 // Find the first position where the line exceeds the available space.
3913 long breakPosition
= range
.GetEnd();
3915 // Binary chop for speed
3916 long minPos
= range
.GetStart();
3917 long maxPos
= range
.GetEnd();
3920 if (minPos
== maxPos
)
3923 GetRangeSize(wxRichTextRange(range
.GetStart(), minPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
3925 if (sz
.x
> availableSpace
)
3926 breakPosition
= minPos
- 1;
3929 else if ((maxPos
- minPos
) == 1)
3932 GetRangeSize(wxRichTextRange(range
.GetStart(), minPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
3934 if (sz
.x
> availableSpace
)
3935 breakPosition
= minPos
- 1;
3938 GetRangeSize(wxRichTextRange(range
.GetStart(), maxPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
3939 if (sz
.x
> availableSpace
)
3940 breakPosition
= maxPos
-1;
3946 long nextPos
= minPos
+ ((maxPos
- minPos
) / 2);
3949 GetRangeSize(wxRichTextRange(range
.GetStart(), nextPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
3951 if (sz
.x
> availableSpace
)
3962 // Now we know the last position on the line.
3963 // Let's try to find a word break.
3966 if (GetContiguousPlainText(plainText
, wxRichTextRange(range
.GetStart(), breakPosition
), false))
3968 int newLinePos
= plainText
.Find(wxRichTextLineBreakChar
);
3969 if (newLinePos
!= wxNOT_FOUND
)
3971 breakPosition
= wxMax(0, range
.GetStart() + newLinePos
);
3975 int spacePos
= plainText
.Find(wxT(' '), true);
3976 int tabPos
= plainText
.Find(wxT('\t'), true);
3977 int pos
= wxMax(spacePos
, tabPos
);
3978 if (pos
!= wxNOT_FOUND
)
3980 int positionsFromEndOfString
= plainText
.length() - pos
- 1;
3981 breakPosition
= breakPosition
- positionsFromEndOfString
;
3986 wrapPosition
= breakPosition
;
3991 /// Get the bullet text for this paragraph.
3992 wxString
wxRichTextParagraph::GetBulletText()
3994 if (GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE
||
3995 (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP
))
3996 return wxEmptyString
;
3998 int number
= GetAttributes().GetBulletNumber();
4001 if ((GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ARABIC
) || (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
))
4003 text
.Printf(wxT("%d"), number
);
4005 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER
)
4007 // TODO: Unicode, and also check if number > 26
4008 text
.Printf(wxT("%c"), (wxChar
) (number
+64));
4010 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER
)
4012 // TODO: Unicode, and also check if number > 26
4013 text
.Printf(wxT("%c"), (wxChar
) (number
+96));
4015 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER
)
4017 text
= wxRichTextDecimalToRoman(number
);
4019 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER
)
4021 text
= wxRichTextDecimalToRoman(number
);
4024 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL
)
4026 text
= GetAttributes().GetBulletText();
4029 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
)
4031 // The outline style relies on the text being computed statically,
4032 // since it depends on other levels points (e.g. 1.2.1.1). So normally the bullet text
4033 // should be stored in the attributes; if not, just use the number for this
4034 // level, as previously computed.
4035 if (!GetAttributes().GetBulletText().IsEmpty())
4036 text
= GetAttributes().GetBulletText();
4039 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PARENTHESES
)
4041 text
= wxT("(") + text
+ wxT(")");
4043 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS
)
4045 text
= text
+ wxT(")");
4048 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PERIOD
)
4056 /// Allocate or reuse a line object
4057 wxRichTextLine
* wxRichTextParagraph::AllocateLine(int pos
)
4059 if (pos
< (int) m_cachedLines
.GetCount())
4061 wxRichTextLine
* line
= m_cachedLines
.Item(pos
)->GetData();
4067 wxRichTextLine
* line
= new wxRichTextLine(this);
4068 m_cachedLines
.Append(line
);
4073 /// Clear remaining unused line objects, if any
4074 bool wxRichTextParagraph::ClearUnusedLines(int lineCount
)
4076 int cachedLineCount
= m_cachedLines
.GetCount();
4077 if ((int) cachedLineCount
> lineCount
)
4079 for (int i
= 0; i
< (int) (cachedLineCount
- lineCount
); i
++)
4081 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetLast();
4082 wxRichTextLine
* line
= node
->GetData();
4083 m_cachedLines
.Erase(node
);
4090 /// Get combined attributes of the base style, paragraph style and character style. We use this to dynamically
4091 /// retrieve the actual style.
4092 wxTextAttr
wxRichTextParagraph::GetCombinedAttributes(const wxTextAttr
& contentStyle
) const
4095 wxRichTextBuffer
* buf
= wxDynamicCast(GetParent(), wxRichTextBuffer
);
4098 attr
= buf
->GetBasicStyle();
4099 wxRichTextApplyStyle(attr
, GetAttributes());
4102 attr
= GetAttributes();
4104 wxRichTextApplyStyle(attr
, contentStyle
);
4108 /// Get combined attributes of the base style and paragraph style.
4109 wxTextAttr
wxRichTextParagraph::GetCombinedAttributes() const
4112 wxRichTextBuffer
* buf
= wxDynamicCast(GetParent(), wxRichTextBuffer
);
4115 attr
= buf
->GetBasicStyle();
4116 wxRichTextApplyStyle(attr
, GetAttributes());
4119 attr
= GetAttributes();
4124 /// Create default tabstop array
4125 void wxRichTextParagraph::InitDefaultTabs()
4127 // create a default tab list at 10 mm each.
4128 for (int i
= 0; i
< 20; ++i
)
4130 sm_defaultTabs
.Add(i
*100);
4134 /// Clear default tabstop array
4135 void wxRichTextParagraph::ClearDefaultTabs()
4137 sm_defaultTabs
.Clear();
4140 /// Get the first position from pos that has a line break character.
4141 long wxRichTextParagraph::GetFirstLineBreakPosition(long pos
)
4143 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
4146 wxRichTextObject
* obj
= node
->GetData();
4147 if (pos
>= obj
->GetRange().GetStart() && pos
<= obj
->GetRange().GetEnd())
4149 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
4152 long breakPos
= textObj
->GetFirstLineBreakPosition(pos
);
4157 node
= node
->GetNext();
4164 * This object represents a line in a paragraph, and stores
4165 * offsets from the start of the paragraph representing the
4166 * start and end positions of the line.
4169 wxRichTextLine::wxRichTextLine(wxRichTextParagraph
* parent
)
4175 void wxRichTextLine::Init(wxRichTextParagraph
* parent
)
4178 m_range
.SetRange(-1, -1);
4179 m_pos
= wxPoint(0, 0);
4180 m_size
= wxSize(0, 0);
4185 void wxRichTextLine::Copy(const wxRichTextLine
& obj
)
4187 m_range
= obj
.m_range
;
4190 /// Get the absolute object position
4191 wxPoint
wxRichTextLine::GetAbsolutePosition() const
4193 return m_parent
->GetPosition() + m_pos
;
4196 /// Get the absolute range
4197 wxRichTextRange
wxRichTextLine::GetAbsoluteRange() const
4199 wxRichTextRange
range(m_range
.GetStart() + m_parent
->GetRange().GetStart(), 0);
4200 range
.SetEnd(range
.GetStart() + m_range
.GetLength()-1);
4205 * wxRichTextPlainText
4206 * This object represents a single piece of text.
4209 IMPLEMENT_DYNAMIC_CLASS(wxRichTextPlainText
, wxRichTextObject
)
4211 wxRichTextPlainText::wxRichTextPlainText(const wxString
& text
, wxRichTextObject
* parent
, wxTextAttr
* style
):
4212 wxRichTextObject(parent
)
4215 SetAttributes(*style
);
4220 #define USE_KERNING_FIX 1
4222 // If insufficient tabs are defined, this is the tab width used
4223 #define WIDTH_FOR_DEFAULT_TABS 50
4226 bool wxRichTextPlainText::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int descent
, int WXUNUSED(style
))
4228 wxRichTextParagraph
* para
= wxDynamicCast(GetParent(), wxRichTextParagraph
);
4229 wxASSERT (para
!= NULL
);
4231 wxTextAttr
textAttr(para
? para
->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4233 int offset
= GetRange().GetStart();
4235 // Replace line break characters with spaces
4236 wxString str
= m_text
;
4237 wxString toRemove
= wxRichTextLineBreakChar
;
4238 str
.Replace(toRemove
, wxT(" "));
4240 long len
= range
.GetLength();
4241 wxString stringChunk
= str
.Mid(range
.GetStart() - offset
, (size_t) len
);
4242 if (textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
4243 stringChunk
.MakeUpper();
4245 int charHeight
= dc
.GetCharHeight();
4248 int y
= rect
.y
+ (rect
.height
- charHeight
- (descent
- m_descent
));
4250 // Test for the optimized situations where all is selected, or none
4253 wxFont
font(GetBuffer()->GetFontTable().FindFont(textAttr
));
4254 wxCheckSetFont(dc
, font
);
4256 // (a) All selected.
4257 if (selectionRange
.GetStart() <= range
.GetStart() && selectionRange
.GetEnd() >= range
.GetEnd())
4259 DrawTabbedString(dc
, textAttr
, rect
, stringChunk
, x
, y
, true);
4261 // (b) None selected.
4262 else if (selectionRange
.GetEnd() < range
.GetStart() || selectionRange
.GetStart() > range
.GetEnd())
4264 // Draw all unselected
4265 DrawTabbedString(dc
, textAttr
, rect
, stringChunk
, x
, y
, false);
4269 // (c) Part selected, part not
4270 // Let's draw unselected chunk, selected chunk, then unselected chunk.
4272 dc
.SetBackgroundMode(wxTRANSPARENT
);
4274 // 1. Initial unselected chunk, if any, up until start of selection.
4275 if (selectionRange
.GetStart() > range
.GetStart() && selectionRange
.GetStart() <= range
.GetEnd())
4277 int r1
= range
.GetStart();
4278 int s1
= selectionRange
.GetStart()-1;
4279 int fragmentLen
= s1
- r1
+ 1;
4280 if (fragmentLen
< 0)
4281 wxLogDebug(wxT("Mid(%d, %d"), (int)(r1
- offset
), (int)fragmentLen
);
4282 wxString stringFragment
= str
.Mid(r1
- offset
, fragmentLen
);
4284 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, false);
4287 if (stringChunk
.Find(wxT("\t")) == wxNOT_FOUND
)
4289 // Compensate for kerning difference
4290 wxString
stringFragment2(str
.Mid(r1
- offset
, fragmentLen
+1));
4291 wxString
stringFragment3(str
.Mid(r1
- offset
+ fragmentLen
, 1));
4293 wxCoord w1
, h1
, w2
, h2
, w3
, h3
;
4294 dc
.GetTextExtent(stringFragment
, & w1
, & h1
);
4295 dc
.GetTextExtent(stringFragment2
, & w2
, & h2
);
4296 dc
.GetTextExtent(stringFragment3
, & w3
, & h3
);
4298 int kerningDiff
= (w1
+ w3
) - w2
;
4299 x
= x
- kerningDiff
;
4304 // 2. Selected chunk, if any.
4305 if (selectionRange
.GetEnd() >= range
.GetStart())
4307 int s1
= wxMax(selectionRange
.GetStart(), range
.GetStart());
4308 int s2
= wxMin(selectionRange
.GetEnd(), range
.GetEnd());
4310 int fragmentLen
= s2
- s1
+ 1;
4311 if (fragmentLen
< 0)
4312 wxLogDebug(wxT("Mid(%d, %d"), (int)(s1
- offset
), (int)fragmentLen
);
4313 wxString stringFragment
= str
.Mid(s1
- offset
, fragmentLen
);
4315 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, true);
4318 if (stringChunk
.Find(wxT("\t")) == wxNOT_FOUND
)
4320 // Compensate for kerning difference
4321 wxString
stringFragment2(str
.Mid(s1
- offset
, fragmentLen
+1));
4322 wxString
stringFragment3(str
.Mid(s1
- offset
+ fragmentLen
, 1));
4324 wxCoord w1
, h1
, w2
, h2
, w3
, h3
;
4325 dc
.GetTextExtent(stringFragment
, & w1
, & h1
);
4326 dc
.GetTextExtent(stringFragment2
, & w2
, & h2
);
4327 dc
.GetTextExtent(stringFragment3
, & w3
, & h3
);
4329 int kerningDiff
= (w1
+ w3
) - w2
;
4330 x
= x
- kerningDiff
;
4335 // 3. Remaining unselected chunk, if any
4336 if (selectionRange
.GetEnd() < range
.GetEnd())
4338 int s2
= wxMin(selectionRange
.GetEnd()+1, range
.GetEnd());
4339 int r2
= range
.GetEnd();
4341 int fragmentLen
= r2
- s2
+ 1;
4342 if (fragmentLen
< 0)
4343 wxLogDebug(wxT("Mid(%d, %d"), (int)(s2
- offset
), (int)fragmentLen
);
4344 wxString stringFragment
= str
.Mid(s2
- offset
, fragmentLen
);
4346 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, false);
4353 bool wxRichTextPlainText::DrawTabbedString(wxDC
& dc
, const wxTextAttr
& attr
, const wxRect
& rect
,wxString
& str
, wxCoord
& x
, wxCoord
& y
, bool selected
)
4355 bool hasTabs
= (str
.Find(wxT('\t')) != wxNOT_FOUND
);
4357 wxArrayInt tabArray
;
4361 if (attr
.GetTabs().IsEmpty())
4362 tabArray
= wxRichTextParagraph::GetDefaultTabs();
4364 tabArray
= attr
.GetTabs();
4365 tabCount
= tabArray
.GetCount();
4367 for (int i
= 0; i
< tabCount
; ++i
)
4369 int pos
= tabArray
[i
];
4370 pos
= ConvertTenthsMMToPixels(dc
, pos
);
4377 int nextTabPos
= -1;
4383 wxColour
highlightColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT
));
4384 wxColour
highlightTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT
));
4386 wxCheckSetBrush(dc
, wxBrush(highlightColour
));
4387 wxCheckSetPen(dc
, wxPen(highlightColour
));
4388 dc
.SetTextForeground(highlightTextColour
);
4389 dc
.SetBackgroundMode(wxTRANSPARENT
);
4393 dc
.SetTextForeground(attr
.GetTextColour());
4395 if (attr
.HasFlag(wxTEXT_ATTR_BACKGROUND_COLOUR
) && attr
.GetBackgroundColour().IsOk())
4397 dc
.SetBackgroundMode(wxSOLID
);
4398 dc
.SetTextBackground(attr
.GetBackgroundColour());
4401 dc
.SetBackgroundMode(wxTRANSPARENT
);
4406 // the string has a tab
4407 // break up the string at the Tab
4408 wxString stringChunk
= str
.BeforeFirst(wxT('\t'));
4409 str
= str
.AfterFirst(wxT('\t'));
4410 dc
.GetTextExtent(stringChunk
, & w
, & h
);
4412 bool not_found
= true;
4413 for (int i
= 0; i
< tabCount
&& not_found
; ++i
)
4415 nextTabPos
= tabArray
.Item(i
);
4417 // Find the next tab position.
4418 // Even if we're at the end of the tab array, we must still draw the chunk.
4420 if (nextTabPos
> tabPos
|| (i
== (tabCount
- 1)))
4422 if (nextTabPos
<= tabPos
)
4424 int defaultTabWidth
= ConvertTenthsMMToPixels(dc
, WIDTH_FOR_DEFAULT_TABS
);
4425 nextTabPos
= tabPos
+ defaultTabWidth
;
4432 wxRect
selRect(x
, rect
.y
, w
, rect
.GetHeight());
4433 dc
.DrawRectangle(selRect
);
4435 dc
.DrawText(stringChunk
, x
, y
);
4437 if (attr
.HasTextEffects() && (attr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH
))
4439 wxPen oldPen
= dc
.GetPen();
4440 wxCheckSetPen(dc
, wxPen(attr
.GetTextColour(), 1));
4441 dc
.DrawLine(x
, (int) (y
+(h
/2)+0.5), x
+w
, (int) (y
+(h
/2)+0.5));
4442 wxCheckSetPen(dc
, oldPen
);
4448 hasTabs
= (str
.Find(wxT('\t')) != wxNOT_FOUND
);
4453 dc
.GetTextExtent(str
, & w
, & h
);
4456 wxRect
selRect(x
, rect
.y
, w
, rect
.GetHeight());
4457 dc
.DrawRectangle(selRect
);
4459 dc
.DrawText(str
, x
, y
);
4461 if (attr
.HasTextEffects() && (attr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH
))
4463 wxPen oldPen
= dc
.GetPen();
4464 wxCheckSetPen(dc
, wxPen(attr
.GetTextColour(), 1));
4465 dc
.DrawLine(x
, (int) (y
+(h
/2)+0.5), x
+w
, (int) (y
+(h
/2)+0.5));
4466 wxCheckSetPen(dc
, oldPen
);
4475 /// Lay the item out
4476 bool wxRichTextPlainText::Layout(wxDC
& dc
, const wxRect
& WXUNUSED(rect
), int WXUNUSED(style
))
4478 // Only lay out if we haven't already cached the size
4480 GetRangeSize(GetRange(), m_size
, m_descent
, dc
, 0, wxPoint(0, 0));
4486 void wxRichTextPlainText::Copy(const wxRichTextPlainText
& obj
)
4488 wxRichTextObject::Copy(obj
);
4490 m_text
= obj
.m_text
;
4493 /// Get/set the object size for the given range. Returns false if the range
4494 /// is invalid for this object.
4495 bool wxRichTextPlainText::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int WXUNUSED(flags
), wxPoint position
) const
4497 if (!range
.IsWithin(GetRange()))
4500 wxRichTextParagraph
* para
= wxDynamicCast(GetParent(), wxRichTextParagraph
);
4501 wxASSERT (para
!= NULL
);
4503 wxTextAttr
textAttr(para
? para
->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4505 // Always assume unformatted text, since at this level we have no knowledge
4506 // of line breaks - and we don't need it, since we'll calculate size within
4507 // formatted text by doing it in chunks according to the line ranges
4509 wxFont
font(GetBuffer()->GetFontTable().FindFont(textAttr
));
4510 wxCheckSetFont(dc
, font
);
4512 int startPos
= range
.GetStart() - GetRange().GetStart();
4513 long len
= range
.GetLength();
4515 wxString
str(m_text
);
4516 wxString toReplace
= wxRichTextLineBreakChar
;
4517 str
.Replace(toReplace
, wxT(" "));
4519 wxString stringChunk
= str
.Mid(startPos
, (size_t) len
);
4521 if (textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
4522 stringChunk
.MakeUpper();
4526 if (stringChunk
.Find(wxT('\t')) != wxNOT_FOUND
)
4528 // the string has a tab
4529 wxArrayInt tabArray
;
4530 if (textAttr
.GetTabs().IsEmpty())
4531 tabArray
= wxRichTextParagraph::GetDefaultTabs();
4533 tabArray
= textAttr
.GetTabs();
4535 int tabCount
= tabArray
.GetCount();
4537 for (int i
= 0; i
< tabCount
; ++i
)
4539 int pos
= tabArray
[i
];
4540 pos
= ((wxRichTextPlainText
*) this)->ConvertTenthsMMToPixels(dc
, pos
);
4544 int nextTabPos
= -1;
4546 while (stringChunk
.Find(wxT('\t')) >= 0)
4548 // the string has a tab
4549 // break up the string at the Tab
4550 wxString stringFragment
= stringChunk
.BeforeFirst(wxT('\t'));
4551 stringChunk
= stringChunk
.AfterFirst(wxT('\t'));
4552 dc
.GetTextExtent(stringFragment
, & w
, & h
);
4554 int absoluteWidth
= width
+ position
.x
;
4556 bool notFound
= true;
4557 for (int i
= 0; i
< tabCount
&& notFound
; ++i
)
4559 nextTabPos
= tabArray
.Item(i
);
4561 // Find the next tab position.
4562 // Even if we're at the end of the tab array, we must still process the chunk.
4564 if (nextTabPos
> absoluteWidth
|| (i
== (tabCount
- 1)))
4566 if (nextTabPos
<= absoluteWidth
)
4568 int defaultTabWidth
= ((wxRichTextPlainText
*) this)->ConvertTenthsMMToPixels(dc
, WIDTH_FOR_DEFAULT_TABS
);
4569 nextTabPos
= absoluteWidth
+ defaultTabWidth
;
4573 width
= nextTabPos
- position
.x
;
4578 dc
.GetTextExtent(stringChunk
, & w
, & h
, & descent
);
4580 size
= wxSize(width
, dc
.GetCharHeight());
4585 /// Do a split, returning an object containing the second part, and setting
4586 /// the first part in 'this'.
4587 wxRichTextObject
* wxRichTextPlainText::DoSplit(long pos
)
4589 long index
= pos
- GetRange().GetStart();
4591 if (index
< 0 || index
>= (int) m_text
.length())
4594 wxString firstPart
= m_text
.Mid(0, index
);
4595 wxString secondPart
= m_text
.Mid(index
);
4599 wxRichTextPlainText
* newObject
= new wxRichTextPlainText(secondPart
);
4600 newObject
->SetAttributes(GetAttributes());
4602 newObject
->SetRange(wxRichTextRange(pos
, GetRange().GetEnd()));
4603 GetRange().SetEnd(pos
-1);
4609 void wxRichTextPlainText::CalculateRange(long start
, long& end
)
4611 end
= start
+ m_text
.length() - 1;
4612 m_range
.SetRange(start
, end
);
4616 bool wxRichTextPlainText::DeleteRange(const wxRichTextRange
& range
)
4618 wxRichTextRange r
= range
;
4620 r
.LimitTo(GetRange());
4622 if (r
.GetStart() == GetRange().GetStart() && r
.GetEnd() == GetRange().GetEnd())
4628 long startIndex
= r
.GetStart() - GetRange().GetStart();
4629 long len
= r
.GetLength();
4631 m_text
= m_text
.Mid(0, startIndex
) + m_text
.Mid(startIndex
+len
);
4635 /// Get text for the given range.
4636 wxString
wxRichTextPlainText::GetTextForRange(const wxRichTextRange
& range
) const
4638 wxRichTextRange r
= range
;
4640 r
.LimitTo(GetRange());
4642 long startIndex
= r
.GetStart() - GetRange().GetStart();
4643 long len
= r
.GetLength();
4645 return m_text
.Mid(startIndex
, len
);
4648 /// Returns true if this object can merge itself with the given one.
4649 bool wxRichTextPlainText::CanMerge(wxRichTextObject
* object
) const
4651 return object
->GetClassInfo() == CLASSINFO(wxRichTextPlainText
) &&
4652 (m_text
.empty() || wxTextAttrEq(GetAttributes(), object
->GetAttributes()));
4655 /// Returns true if this object merged itself with the given one.
4656 /// The calling code will then delete the given object.
4657 bool wxRichTextPlainText::Merge(wxRichTextObject
* object
)
4659 wxRichTextPlainText
* textObject
= wxDynamicCast(object
, wxRichTextPlainText
);
4660 wxASSERT( textObject
!= NULL
);
4664 m_text
+= textObject
->GetText();
4671 /// Dump to output stream for debugging
4672 void wxRichTextPlainText::Dump(wxTextOutputStream
& stream
)
4674 wxRichTextObject::Dump(stream
);
4675 stream
<< m_text
<< wxT("\n");
4678 /// Get the first position from pos that has a line break character.
4679 long wxRichTextPlainText::GetFirstLineBreakPosition(long pos
)
4682 int len
= m_text
.length();
4683 int startPos
= pos
- m_range
.GetStart();
4684 for (i
= startPos
; i
< len
; i
++)
4686 wxChar ch
= m_text
[i
];
4687 if (ch
== wxRichTextLineBreakChar
)
4689 return i
+ m_range
.GetStart();
4697 * This is a kind of box, used to represent the whole buffer
4700 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBuffer
, wxRichTextParagraphLayoutBox
)
4702 wxList
wxRichTextBuffer::sm_handlers
;
4703 wxRichTextRenderer
* wxRichTextBuffer::sm_renderer
= NULL
;
4704 int wxRichTextBuffer::sm_bulletRightMargin
= 20;
4705 float wxRichTextBuffer::sm_bulletProportion
= (float) 0.3;
4708 void wxRichTextBuffer::Init()
4710 m_commandProcessor
= new wxCommandProcessor
;
4711 m_styleSheet
= NULL
;
4713 m_batchedCommandDepth
= 0;
4714 m_batchedCommand
= NULL
;
4721 wxRichTextBuffer::~wxRichTextBuffer()
4723 delete m_commandProcessor
;
4724 delete m_batchedCommand
;
4727 ClearEventHandlers();
4730 void wxRichTextBuffer::ResetAndClearCommands()
4734 GetCommandProcessor()->ClearCommands();
4737 Invalidate(wxRICHTEXT_ALL
);
4740 void wxRichTextBuffer::Copy(const wxRichTextBuffer
& obj
)
4742 wxRichTextParagraphLayoutBox::Copy(obj
);
4744 m_styleSheet
= obj
.m_styleSheet
;
4745 m_modified
= obj
.m_modified
;
4746 m_batchedCommandDepth
= obj
.m_batchedCommandDepth
;
4747 m_batchedCommand
= obj
.m_batchedCommand
;
4748 m_suppressUndo
= obj
.m_suppressUndo
;
4751 /// Push style sheet to top of stack
4752 bool wxRichTextBuffer::PushStyleSheet(wxRichTextStyleSheet
* styleSheet
)
4755 styleSheet
->InsertSheet(m_styleSheet
);
4757 SetStyleSheet(styleSheet
);
4762 /// Pop style sheet from top of stack
4763 wxRichTextStyleSheet
* wxRichTextBuffer::PopStyleSheet()
4767 wxRichTextStyleSheet
* oldSheet
= m_styleSheet
;
4768 m_styleSheet
= oldSheet
->GetNextSheet();
4777 /// Submit command to insert paragraphs
4778 bool wxRichTextBuffer::InsertParagraphsWithUndo(long pos
, const wxRichTextParagraphLayoutBox
& paragraphs
, wxRichTextCtrl
* ctrl
, int flags
)
4780 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4782 wxTextAttr
attr(GetDefaultStyle());
4784 wxTextAttr
* p
= NULL
;
4785 wxTextAttr paraAttr
;
4786 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4788 paraAttr
= GetStyleForNewParagraph(pos
);
4789 if (!paraAttr
.IsDefault())
4795 action
->GetNewParagraphs() = paragraphs
;
4799 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetLast();
4802 wxRichTextParagraph
* obj
= (wxRichTextParagraph
*) node
->GetData();
4803 obj
->SetAttributes(*p
);
4804 node
= node
->GetPrevious();
4808 action
->SetPosition(pos
);
4810 // Set the range we'll need to delete in Undo
4811 action
->SetRange(wxRichTextRange(pos
, pos
+ paragraphs
.GetRange().GetEnd() - 1));
4813 SubmitAction(action
);
4818 /// Submit command to insert the given text
4819 bool wxRichTextBuffer::InsertTextWithUndo(long pos
, const wxString
& text
, wxRichTextCtrl
* ctrl
, int flags
)
4821 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4823 wxTextAttr
* p
= NULL
;
4824 wxTextAttr paraAttr
;
4825 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4827 // Get appropriate paragraph style
4828 paraAttr
= GetStyleForNewParagraph(pos
, false, false);
4829 if (!paraAttr
.IsDefault())
4833 action
->GetNewParagraphs().AddParagraphs(text
, p
);
4835 int length
= action
->GetNewParagraphs().GetRange().GetLength();
4837 if (text
.length() > 0 && text
.Last() != wxT('\n'))
4839 // Don't count the newline when undoing
4841 action
->GetNewParagraphs().SetPartialParagraph(true);
4843 else if (text
.length() > 0 && text
.Last() == wxT('\n'))
4846 action
->SetPosition(pos
);
4848 // Set the range we'll need to delete in Undo
4849 action
->SetRange(wxRichTextRange(pos
, pos
+ length
- 1));
4851 SubmitAction(action
);
4856 /// Submit command to insert the given text
4857 bool wxRichTextBuffer::InsertNewlineWithUndo(long pos
, wxRichTextCtrl
* ctrl
, int flags
)
4859 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4861 wxTextAttr
* p
= NULL
;
4862 wxTextAttr paraAttr
;
4863 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4865 paraAttr
= GetStyleForNewParagraph(pos
, false, true /* look for next paragraph style */);
4866 if (!paraAttr
.IsDefault())
4870 wxTextAttr
attr(GetDefaultStyle());
4872 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(wxEmptyString
, this, & attr
);
4873 action
->GetNewParagraphs().AppendChild(newPara
);
4874 action
->GetNewParagraphs().UpdateRanges();
4875 action
->GetNewParagraphs().SetPartialParagraph(false);
4876 action
->SetPosition(pos
);
4879 newPara
->SetAttributes(*p
);
4881 // Set the range we'll need to delete in Undo
4882 action
->SetRange(wxRichTextRange(pos
, pos
));
4884 SubmitAction(action
);
4889 /// Submit command to insert the given image
4890 bool wxRichTextBuffer::InsertImageWithUndo(long pos
, const wxRichTextImageBlock
& imageBlock
, wxRichTextCtrl
* ctrl
, int flags
)
4892 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Image"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4894 wxTextAttr
* p
= NULL
;
4895 wxTextAttr paraAttr
;
4896 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4898 paraAttr
= GetStyleForNewParagraph(pos
);
4899 if (!paraAttr
.IsDefault())
4903 wxTextAttr
attr(GetDefaultStyle());
4905 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(this, & attr
);
4907 newPara
->SetAttributes(*p
);
4909 wxRichTextImage
* imageObject
= new wxRichTextImage(imageBlock
, newPara
);
4910 newPara
->AppendChild(imageObject
);
4911 action
->GetNewParagraphs().AppendChild(newPara
);
4912 action
->GetNewParagraphs().UpdateRanges();
4914 action
->GetNewParagraphs().SetPartialParagraph(true);
4916 action
->SetPosition(pos
);
4918 // Set the range we'll need to delete in Undo
4919 action
->SetRange(wxRichTextRange(pos
, pos
));
4921 SubmitAction(action
);
4926 /// Get the style that is appropriate for a new paragraph at this position.
4927 /// If the previous paragraph has a paragraph style name, look up the next-paragraph
4929 wxTextAttr
wxRichTextBuffer::GetStyleForNewParagraph(long pos
, bool caretPosition
, bool lookUpNewParaStyle
) const
4931 wxRichTextParagraph
* para
= GetParagraphAtPosition(pos
, caretPosition
);
4935 bool foundAttributes
= false;
4937 // Look for a matching paragraph style
4938 if (lookUpNewParaStyle
&& !para
->GetAttributes().GetParagraphStyleName().IsEmpty() && GetStyleSheet())
4940 wxRichTextParagraphStyleDefinition
* paraDef
= GetStyleSheet()->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
4943 // If we're not at the end of the paragraph, then we apply THIS style, and not the designated next style.
4944 if (para
->GetRange().GetEnd() == pos
&& !paraDef
->GetNextStyle().IsEmpty())
4946 wxRichTextParagraphStyleDefinition
* nextParaDef
= GetStyleSheet()->FindParagraphStyle(paraDef
->GetNextStyle());
4949 foundAttributes
= true;
4950 attr
= nextParaDef
->GetStyleMergedWithBase(GetStyleSheet());
4954 // If we didn't find the 'next style', use this style instead.
4955 if (!foundAttributes
)
4957 foundAttributes
= true;
4958 attr
= paraDef
->GetStyleMergedWithBase(GetStyleSheet());
4962 if (!foundAttributes
)
4964 attr
= para
->GetAttributes();
4965 int flags
= attr
.GetFlags();
4967 // Eliminate character styles
4968 flags
&= ( (~ wxTEXT_ATTR_FONT
) |
4969 (~ wxTEXT_ATTR_TEXT_COLOUR
) |
4970 (~ wxTEXT_ATTR_BACKGROUND_COLOUR
) );
4971 attr
.SetFlags(flags
);
4974 // Now see if we need to number the paragraph.
4975 if (attr
.HasBulletStyle())
4977 wxTextAttr numberingAttr
;
4978 if (FindNextParagraphNumber(para
, numberingAttr
))
4979 wxRichTextApplyStyle(attr
, (const wxTextAttr
&) numberingAttr
);
4985 return wxTextAttr();
4988 /// Submit command to delete this range
4989 bool wxRichTextBuffer::DeleteRangeWithUndo(const wxRichTextRange
& range
, wxRichTextCtrl
* ctrl
)
4991 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Delete"), wxRICHTEXT_DELETE
, this, ctrl
);
4993 action
->SetPosition(ctrl
->GetCaretPosition());
4995 // Set the range to delete
4996 action
->SetRange(range
);
4998 // Copy the fragment that we'll need to restore in Undo
4999 CopyFragment(range
, action
->GetOldParagraphs());
5001 // Special case: if there is only one (non-partial) paragraph,
5002 // we must save the *next* paragraph's style, because that
5003 // is the style we must apply when inserting the content back
5004 // when undoing the delete. (This is because we're merging the
5005 // paragraph with the previous paragraph and throwing away
5006 // the style, and we need to restore it.)
5007 if (!action
->GetOldParagraphs().GetPartialParagraph() && action
->GetOldParagraphs().GetChildCount() == 1)
5009 wxRichTextParagraph
* lastPara
= GetParagraphAtPosition(range
.GetStart());
5012 wxRichTextParagraph
* nextPara
= GetParagraphAtPosition(range
.GetEnd()+1);
5015 wxRichTextParagraph
* para
= (wxRichTextParagraph
*) action
->GetOldParagraphs().GetChild(0);
5016 para
->SetAttributes(nextPara
->GetAttributes());
5021 SubmitAction(action
);
5026 /// Collapse undo/redo commands
5027 bool wxRichTextBuffer::BeginBatchUndo(const wxString
& cmdName
)
5029 if (m_batchedCommandDepth
== 0)
5031 wxASSERT(m_batchedCommand
== NULL
);
5032 if (m_batchedCommand
)
5034 GetCommandProcessor()->Submit(m_batchedCommand
);
5036 m_batchedCommand
= new wxRichTextCommand(cmdName
);
5039 m_batchedCommandDepth
++;
5044 /// Collapse undo/redo commands
5045 bool wxRichTextBuffer::EndBatchUndo()
5047 m_batchedCommandDepth
--;
5049 wxASSERT(m_batchedCommandDepth
>= 0);
5050 wxASSERT(m_batchedCommand
!= NULL
);
5052 if (m_batchedCommandDepth
== 0)
5054 GetCommandProcessor()->Submit(m_batchedCommand
);
5055 m_batchedCommand
= NULL
;
5061 /// Submit immediately, or delay according to whether collapsing is on
5062 bool wxRichTextBuffer::SubmitAction(wxRichTextAction
* action
)
5064 if (BatchingUndo() && m_batchedCommand
&& !SuppressingUndo())
5065 m_batchedCommand
->AddAction(action
);
5068 wxRichTextCommand
* cmd
= new wxRichTextCommand(action
->GetName());
5069 cmd
->AddAction(action
);
5071 // Only store it if we're not suppressing undo.
5072 return GetCommandProcessor()->Submit(cmd
, !SuppressingUndo());
5078 /// Begin suppressing undo/redo commands.
5079 bool wxRichTextBuffer::BeginSuppressUndo()
5086 /// End suppressing undo/redo commands.
5087 bool wxRichTextBuffer::EndSuppressUndo()
5094 /// Begin using a style
5095 bool wxRichTextBuffer::BeginStyle(const wxTextAttr
& style
)
5097 wxTextAttr
newStyle(GetDefaultStyle());
5099 // Save the old default style
5100 m_attributeStack
.Append((wxObject
*) new wxTextAttr(GetDefaultStyle()));
5102 wxRichTextApplyStyle(newStyle
, style
);
5103 newStyle
.SetFlags(style
.GetFlags()|newStyle
.GetFlags());
5105 SetDefaultStyle(newStyle
);
5107 // wxLogDebug("Default style size = %d", GetDefaultStyle().GetFont().GetPointSize());
5113 bool wxRichTextBuffer::EndStyle()
5115 if (!m_attributeStack
.GetFirst())
5117 wxLogDebug(_("Too many EndStyle calls!"));
5121 wxList::compatibility_iterator node
= m_attributeStack
.GetLast();
5122 wxTextAttr
* attr
= (wxTextAttr
*)node
->GetData();
5123 m_attributeStack
.Erase(node
);
5125 SetDefaultStyle(*attr
);
5132 bool wxRichTextBuffer::EndAllStyles()
5134 while (m_attributeStack
.GetCount() != 0)
5139 /// Clear the style stack
5140 void wxRichTextBuffer::ClearStyleStack()
5142 for (wxList::compatibility_iterator node
= m_attributeStack
.GetFirst(); node
; node
= node
->GetNext())
5143 delete (wxTextAttr
*) node
->GetData();
5144 m_attributeStack
.Clear();
5147 /// Begin using bold
5148 bool wxRichTextBuffer::BeginBold()
5151 attr
.SetFontWeight(wxBOLD
);
5153 return BeginStyle(attr
);
5156 /// Begin using italic
5157 bool wxRichTextBuffer::BeginItalic()
5160 attr
.SetFontStyle(wxITALIC
);
5162 return BeginStyle(attr
);
5165 /// Begin using underline
5166 bool wxRichTextBuffer::BeginUnderline()
5169 attr
.SetFontUnderlined(true);
5171 return BeginStyle(attr
);
5174 /// Begin using point size
5175 bool wxRichTextBuffer::BeginFontSize(int pointSize
)
5178 attr
.SetFontSize(pointSize
);
5180 return BeginStyle(attr
);
5183 /// Begin using this font
5184 bool wxRichTextBuffer::BeginFont(const wxFont
& font
)
5189 return BeginStyle(attr
);
5192 /// Begin using this colour
5193 bool wxRichTextBuffer::BeginTextColour(const wxColour
& colour
)
5196 attr
.SetFlags(wxTEXT_ATTR_TEXT_COLOUR
);
5197 attr
.SetTextColour(colour
);
5199 return BeginStyle(attr
);
5202 /// Begin using alignment
5203 bool wxRichTextBuffer::BeginAlignment(wxTextAttrAlignment alignment
)
5206 attr
.SetFlags(wxTEXT_ATTR_ALIGNMENT
);
5207 attr
.SetAlignment(alignment
);
5209 return BeginStyle(attr
);
5212 /// Begin left indent
5213 bool wxRichTextBuffer::BeginLeftIndent(int leftIndent
, int leftSubIndent
)
5216 attr
.SetFlags(wxTEXT_ATTR_LEFT_INDENT
);
5217 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5219 return BeginStyle(attr
);
5222 /// Begin right indent
5223 bool wxRichTextBuffer::BeginRightIndent(int rightIndent
)
5226 attr
.SetFlags(wxTEXT_ATTR_RIGHT_INDENT
);
5227 attr
.SetRightIndent(rightIndent
);
5229 return BeginStyle(attr
);
5232 /// Begin paragraph spacing
5233 bool wxRichTextBuffer::BeginParagraphSpacing(int before
, int after
)
5237 flags
|= wxTEXT_ATTR_PARA_SPACING_BEFORE
;
5239 flags
|= wxTEXT_ATTR_PARA_SPACING_AFTER
;
5242 attr
.SetFlags(flags
);
5243 attr
.SetParagraphSpacingBefore(before
);
5244 attr
.SetParagraphSpacingAfter(after
);
5246 return BeginStyle(attr
);
5249 /// Begin line spacing
5250 bool wxRichTextBuffer::BeginLineSpacing(int lineSpacing
)
5253 attr
.SetFlags(wxTEXT_ATTR_LINE_SPACING
);
5254 attr
.SetLineSpacing(lineSpacing
);
5256 return BeginStyle(attr
);
5259 /// Begin numbered bullet
5260 bool wxRichTextBuffer::BeginNumberedBullet(int bulletNumber
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5263 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5264 attr
.SetBulletStyle(bulletStyle
);
5265 attr
.SetBulletNumber(bulletNumber
);
5266 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5268 return BeginStyle(attr
);
5271 /// Begin symbol bullet
5272 bool wxRichTextBuffer::BeginSymbolBullet(const wxString
& symbol
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5275 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5276 attr
.SetBulletStyle(bulletStyle
);
5277 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5278 attr
.SetBulletText(symbol
);
5280 return BeginStyle(attr
);
5283 /// Begin standard bullet
5284 bool wxRichTextBuffer::BeginStandardBullet(const wxString
& bulletName
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5287 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5288 attr
.SetBulletStyle(bulletStyle
);
5289 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5290 attr
.SetBulletName(bulletName
);
5292 return BeginStyle(attr
);
5295 /// Begin named character style
5296 bool wxRichTextBuffer::BeginCharacterStyle(const wxString
& characterStyle
)
5298 if (GetStyleSheet())
5300 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterStyle
);
5303 wxTextAttr attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5304 return BeginStyle(attr
);
5310 /// Begin named paragraph style
5311 bool wxRichTextBuffer::BeginParagraphStyle(const wxString
& paragraphStyle
)
5313 if (GetStyleSheet())
5315 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(paragraphStyle
);
5318 wxTextAttr attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5319 return BeginStyle(attr
);
5325 /// Begin named list style
5326 bool wxRichTextBuffer::BeginListStyle(const wxString
& listStyle
, int level
, int number
)
5328 if (GetStyleSheet())
5330 wxRichTextListStyleDefinition
* def
= GetStyleSheet()->FindListStyle(listStyle
);
5333 wxTextAttr
attr(def
->GetCombinedStyleForLevel(level
));
5335 attr
.SetBulletNumber(number
);
5337 return BeginStyle(attr
);
5344 bool wxRichTextBuffer::BeginURL(const wxString
& url
, const wxString
& characterStyle
)
5348 if (!characterStyle
.IsEmpty() && GetStyleSheet())
5350 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterStyle
);
5353 attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5358 return BeginStyle(attr
);
5361 /// Adds a handler to the end
5362 void wxRichTextBuffer::AddHandler(wxRichTextFileHandler
*handler
)
5364 sm_handlers
.Append(handler
);
5367 /// Inserts a handler at the front
5368 void wxRichTextBuffer::InsertHandler(wxRichTextFileHandler
*handler
)
5370 sm_handlers
.Insert( handler
);
5373 /// Removes a handler
5374 bool wxRichTextBuffer::RemoveHandler(const wxString
& name
)
5376 wxRichTextFileHandler
*handler
= FindHandler(name
);
5379 sm_handlers
.DeleteObject(handler
);
5387 /// Finds a handler by filename or, if supplied, type
5388 wxRichTextFileHandler
*wxRichTextBuffer::FindHandlerFilenameOrType(const wxString
& filename
, int imageType
)
5390 if (imageType
!= wxRICHTEXT_TYPE_ANY
)
5391 return FindHandler(imageType
);
5392 else if (!filename
.IsEmpty())
5394 wxString path
, file
, ext
;
5395 wxSplitPath(filename
, & path
, & file
, & ext
);
5396 return FindHandler(ext
, imageType
);
5403 /// Finds a handler by name
5404 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(const wxString
& name
)
5406 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5409 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5410 if (handler
->GetName().Lower() == name
.Lower()) return handler
;
5412 node
= node
->GetNext();
5417 /// Finds a handler by extension and type
5418 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(const wxString
& extension
, int type
)
5420 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5423 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5424 if ( handler
->GetExtension().Lower() == extension
.Lower() &&
5425 (type
== wxRICHTEXT_TYPE_ANY
|| handler
->GetType() == type
) )
5427 node
= node
->GetNext();
5432 /// Finds a handler by type
5433 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(int type
)
5435 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5438 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5439 if (handler
->GetType() == type
) return handler
;
5440 node
= node
->GetNext();
5445 void wxRichTextBuffer::InitStandardHandlers()
5447 if (!FindHandler(wxRICHTEXT_TYPE_TEXT
))
5448 AddHandler(new wxRichTextPlainTextHandler
);
5451 void wxRichTextBuffer::CleanUpHandlers()
5453 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5456 wxRichTextFileHandler
* handler
= (wxRichTextFileHandler
*)node
->GetData();
5457 wxList::compatibility_iterator next
= node
->GetNext();
5462 sm_handlers
.Clear();
5465 wxString
wxRichTextBuffer::GetExtWildcard(bool combine
, bool save
, wxArrayInt
* types
)
5472 wxList::compatibility_iterator node
= GetHandlers().GetFirst();
5476 wxRichTextFileHandler
* handler
= (wxRichTextFileHandler
*) node
->GetData();
5477 if (handler
->IsVisible() && ((save
&& handler
->CanSave()) || !save
&& handler
->CanLoad()))
5482 wildcard
+= wxT(";");
5483 wildcard
+= wxT("*.") + handler
->GetExtension();
5488 wildcard
+= wxT("|");
5489 wildcard
+= handler
->GetName();
5490 wildcard
+= wxT(" ");
5491 wildcard
+= _("files");
5492 wildcard
+= wxT(" (*.");
5493 wildcard
+= handler
->GetExtension();
5494 wildcard
+= wxT(")|*.");
5495 wildcard
+= handler
->GetExtension();
5497 types
->Add(handler
->GetType());
5502 node
= node
->GetNext();
5506 wildcard
= wxT("(") + wildcard
+ wxT(")|") + wildcard
;
5511 bool wxRichTextBuffer::LoadFile(const wxString
& filename
, int type
)
5513 wxRichTextFileHandler
* handler
= FindHandlerFilenameOrType(filename
, type
);
5516 SetDefaultStyle(wxTextAttr());
5517 handler
->SetFlags(GetHandlerFlags());
5518 bool success
= handler
->LoadFile(this, filename
);
5519 Invalidate(wxRICHTEXT_ALL
);
5527 bool wxRichTextBuffer::SaveFile(const wxString
& filename
, int type
)
5529 wxRichTextFileHandler
* handler
= FindHandlerFilenameOrType(filename
, type
);
5532 handler
->SetFlags(GetHandlerFlags());
5533 return handler
->SaveFile(this, filename
);
5539 /// Load from a stream
5540 bool wxRichTextBuffer::LoadFile(wxInputStream
& stream
, int type
)
5542 wxRichTextFileHandler
* handler
= FindHandler(type
);
5545 SetDefaultStyle(wxTextAttr());
5546 handler
->SetFlags(GetHandlerFlags());
5547 bool success
= handler
->LoadFile(this, stream
);
5548 Invalidate(wxRICHTEXT_ALL
);
5555 /// Save to a stream
5556 bool wxRichTextBuffer::SaveFile(wxOutputStream
& stream
, int type
)
5558 wxRichTextFileHandler
* handler
= FindHandler(type
);
5561 handler
->SetFlags(GetHandlerFlags());
5562 return handler
->SaveFile(this, stream
);
5568 /// Copy the range to the clipboard
5569 bool wxRichTextBuffer::CopyToClipboard(const wxRichTextRange
& range
)
5571 bool success
= false;
5572 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5574 if (!wxTheClipboard
->IsOpened() && wxTheClipboard
->Open())
5576 wxTheClipboard
->Clear();
5578 // Add composite object
5580 wxDataObjectComposite
* compositeObject
= new wxDataObjectComposite();
5583 wxString text
= GetTextForRange(range
);
5586 text
= wxTextFile::Translate(text
, wxTextFileType_Dos
);
5589 compositeObject
->Add(new wxTextDataObject(text
), false /* not preferred */);
5592 // Add rich text buffer data object. This needs the XML handler to be present.
5594 if (FindHandler(wxRICHTEXT_TYPE_XML
))
5596 wxRichTextBuffer
* richTextBuf
= new wxRichTextBuffer
;
5597 CopyFragment(range
, *richTextBuf
);
5599 compositeObject
->Add(new wxRichTextBufferDataObject(richTextBuf
), true /* preferred */);
5602 if (wxTheClipboard
->SetData(compositeObject
))
5605 wxTheClipboard
->Close();
5614 /// Paste the clipboard content to the buffer
5615 bool wxRichTextBuffer::PasteFromClipboard(long position
)
5617 bool success
= false;
5618 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5619 if (CanPasteFromClipboard())
5621 if (wxTheClipboard
->Open())
5623 if (wxTheClipboard
->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())))
5625 wxRichTextBufferDataObject data
;
5626 wxTheClipboard
->GetData(data
);
5627 wxRichTextBuffer
* richTextBuffer
= data
.GetRichTextBuffer();
5630 InsertParagraphsWithUndo(position
+1, *richTextBuffer
, GetRichTextCtrl(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
);
5631 delete richTextBuffer
;
5634 else if (wxTheClipboard
->IsSupported(wxDF_TEXT
) || wxTheClipboard
->IsSupported(wxDF_UNICODETEXT
))
5636 wxTextDataObject data
;
5637 wxTheClipboard
->GetData(data
);
5638 wxString
text(data
.GetText());
5641 text2
.Alloc(text
.Length()+1);
5643 for (i
= 0; i
< text
.Length(); i
++)
5645 wxChar ch
= text
[i
];
5646 if (ch
!= wxT('\r'))
5650 wxString text2
= text
;
5652 InsertTextWithUndo(position
+1, text2
, GetRichTextCtrl());
5656 else if (wxTheClipboard
->IsSupported(wxDF_BITMAP
))
5658 wxBitmapDataObject data
;
5659 wxTheClipboard
->GetData(data
);
5660 wxBitmap
bitmap(data
.GetBitmap());
5661 wxImage
image(bitmap
.ConvertToImage());
5663 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Image"), wxRICHTEXT_INSERT
, this, GetRichTextCtrl(), false);
5665 action
->GetNewParagraphs().AddImage(image
);
5667 if (action
->GetNewParagraphs().GetChildCount() == 1)
5668 action
->GetNewParagraphs().SetPartialParagraph(true);
5670 action
->SetPosition(position
);
5672 // Set the range we'll need to delete in Undo
5673 action
->SetRange(wxRichTextRange(position
, position
));
5675 SubmitAction(action
);
5679 wxTheClipboard
->Close();
5683 wxUnusedVar(position
);
5688 /// Can we paste from the clipboard?
5689 bool wxRichTextBuffer::CanPasteFromClipboard() const
5691 bool canPaste
= false;
5692 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5693 if (!wxTheClipboard
->IsOpened() && wxTheClipboard
->Open())
5695 if (wxTheClipboard
->IsSupported(wxDF_TEXT
) || wxTheClipboard
->IsSupported(wxDF_UNICODETEXT
) ||
5696 wxTheClipboard
->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())) ||
5697 wxTheClipboard
->IsSupported(wxDF_BITMAP
))
5701 wxTheClipboard
->Close();
5707 /// Dumps contents of buffer for debugging purposes
5708 void wxRichTextBuffer::Dump()
5712 wxStringOutputStream
stream(& text
);
5713 wxTextOutputStream
textStream(stream
);
5720 /// Add an event handler
5721 bool wxRichTextBuffer::AddEventHandler(wxEvtHandler
* handler
)
5723 m_eventHandlers
.Append(handler
);
5727 /// Remove an event handler
5728 bool wxRichTextBuffer::RemoveEventHandler(wxEvtHandler
* handler
, bool deleteHandler
)
5730 wxList::compatibility_iterator node
= m_eventHandlers
.Find(handler
);
5733 m_eventHandlers
.Erase(node
);
5743 /// Clear event handlers
5744 void wxRichTextBuffer::ClearEventHandlers()
5746 m_eventHandlers
.Clear();
5749 /// Send event to event handlers. If sendToAll is true, will send to all event handlers,
5750 /// otherwise will stop at the first successful one.
5751 bool wxRichTextBuffer::SendEvent(wxEvent
& event
, bool sendToAll
)
5753 bool success
= false;
5754 for (wxList::compatibility_iterator node
= m_eventHandlers
.GetFirst(); node
; node
= node
->GetNext())
5756 wxEvtHandler
* handler
= (wxEvtHandler
*) node
->GetData();
5757 if (handler
->ProcessEvent(event
))
5767 /// Set style sheet and notify of the change
5768 bool wxRichTextBuffer::SetStyleSheetAndNotify(wxRichTextStyleSheet
* sheet
)
5770 wxRichTextStyleSheet
* oldSheet
= GetStyleSheet();
5772 wxWindowID id
= wxID_ANY
;
5773 if (GetRichTextCtrl())
5774 id
= GetRichTextCtrl()->GetId();
5776 wxRichTextEvent
event(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING
, id
);
5777 event
.SetEventObject(GetRichTextCtrl());
5778 event
.SetOldStyleSheet(oldSheet
);
5779 event
.SetNewStyleSheet(sheet
);
5782 if (SendEvent(event
) && !event
.IsAllowed())
5784 if (sheet
!= oldSheet
)
5790 if (oldSheet
&& oldSheet
!= sheet
)
5793 SetStyleSheet(sheet
);
5795 event
.SetEventType(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED
);
5796 event
.SetOldStyleSheet(NULL
);
5799 return SendEvent(event
);
5802 /// Set renderer, deleting old one
5803 void wxRichTextBuffer::SetRenderer(wxRichTextRenderer
* renderer
)
5807 sm_renderer
= renderer
;
5810 bool wxRichTextStdRenderer::DrawStandardBullet(wxRichTextParagraph
* paragraph
, wxDC
& dc
, const wxTextAttr
& bulletAttr
, const wxRect
& rect
)
5812 if (bulletAttr
.GetTextColour().Ok())
5814 wxCheckSetPen(dc
, wxPen(bulletAttr
.GetTextColour()));
5815 wxCheckSetBrush(dc
, wxBrush(bulletAttr
.GetTextColour()));
5819 wxCheckSetPen(dc
, *wxBLACK_PEN
);
5820 wxCheckSetBrush(dc
, *wxBLACK_BRUSH
);
5824 if (bulletAttr
.HasFont())
5826 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(bulletAttr
);
5829 font
= (*wxNORMAL_FONT
);
5831 wxCheckSetFont(dc
, font
);
5833 int charHeight
= dc
.GetCharHeight();
5835 int bulletWidth
= (int) (((float) charHeight
) * wxRichTextBuffer::GetBulletProportion());
5836 int bulletHeight
= bulletWidth
;
5840 // Calculate the top position of the character (as opposed to the whole line height)
5841 int y
= rect
.y
+ (rect
.height
- charHeight
);
5843 // Calculate where the bullet should be positioned
5844 y
= y
+ (charHeight
+1)/2 - (bulletHeight
+1)/2;
5846 // The margin between a bullet and text.
5847 int margin
= paragraph
->ConvertTenthsMMToPixels(dc
, wxRichTextBuffer::GetBulletRightMargin());
5849 if (bulletAttr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT
)
5850 x
= rect
.x
+ rect
.width
- bulletWidth
- margin
;
5851 else if (bulletAttr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE
)
5852 x
= x
+ (rect
.width
)/2 - bulletWidth
/2;
5854 if (bulletAttr
.GetBulletName() == wxT("standard/square"))
5856 dc
.DrawRectangle(x
, y
, bulletWidth
, bulletHeight
);
5858 else if (bulletAttr
.GetBulletName() == wxT("standard/diamond"))
5861 pts
[0].x
= x
; pts
[0].y
= y
+ bulletHeight
/2;
5862 pts
[1].x
= x
+ bulletWidth
/2; pts
[1].y
= y
;
5863 pts
[2].x
= x
+ bulletWidth
; pts
[2].y
= y
+ bulletHeight
/2;
5864 pts
[3].x
= x
+ bulletWidth
/2; pts
[3].y
= y
+ bulletHeight
;
5866 dc
.DrawPolygon(4, pts
);
5868 else if (bulletAttr
.GetBulletName() == wxT("standard/triangle"))
5871 pts
[0].x
= x
; pts
[0].y
= y
;
5872 pts
[1].x
= x
+ bulletWidth
; pts
[1].y
= y
+ bulletHeight
/2;
5873 pts
[2].x
= x
; pts
[2].y
= y
+ bulletHeight
;
5875 dc
.DrawPolygon(3, pts
);
5877 else // "standard/circle", and catch-all
5879 dc
.DrawEllipse(x
, y
, bulletWidth
, bulletHeight
);
5885 bool wxRichTextStdRenderer::DrawTextBullet(wxRichTextParagraph
* paragraph
, wxDC
& dc
, const wxTextAttr
& attr
, const wxRect
& rect
, const wxString
& text
)
5890 if ((attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL
) && !attr
.GetBulletFont().IsEmpty() && attr
.HasFont())
5892 wxTextAttr fontAttr
;
5893 fontAttr
.SetFontSize(attr
.GetFontSize());
5894 fontAttr
.SetFontStyle(attr
.GetFontStyle());
5895 fontAttr
.SetFontWeight(attr
.GetFontWeight());
5896 fontAttr
.SetFontUnderlined(attr
.GetFontUnderlined());
5897 fontAttr
.SetFontFaceName(attr
.GetBulletFont());
5898 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(fontAttr
);
5900 else if (attr
.HasFont())
5901 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(attr
);
5903 font
= (*wxNORMAL_FONT
);
5905 wxCheckSetFont(dc
, font
);
5907 if (attr
.GetTextColour().Ok())
5908 dc
.SetTextForeground(attr
.GetTextColour());
5910 dc
.SetBackgroundMode(wxTRANSPARENT
);
5912 int charHeight
= dc
.GetCharHeight();
5914 dc
.GetTextExtent(text
, & tw
, & th
);
5918 // Calculate the top position of the character (as opposed to the whole line height)
5919 int y
= rect
.y
+ (rect
.height
- charHeight
);
5921 // The margin between a bullet and text.
5922 int margin
= paragraph
->ConvertTenthsMMToPixels(dc
, wxRichTextBuffer::GetBulletRightMargin());
5924 if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT
)
5925 x
= (rect
.x
+ rect
.width
) - tw
- margin
;
5926 else if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE
)
5927 x
= x
+ (rect
.width
)/2 - tw
/2;
5929 dc
.DrawText(text
, x
, y
);
5937 bool wxRichTextStdRenderer::DrawBitmapBullet(wxRichTextParagraph
* WXUNUSED(paragraph
), wxDC
& WXUNUSED(dc
), const wxTextAttr
& WXUNUSED(attr
), const wxRect
& WXUNUSED(rect
))
5939 // Currently unimplemented. The intention is to store bitmaps by name in a media store associated
5940 // with the buffer. The store will allow retrieval from memory, disk or other means.
5944 /// Enumerate the standard bullet names currently supported
5945 bool wxRichTextStdRenderer::EnumerateStandardBulletNames(wxArrayString
& bulletNames
)
5947 bulletNames
.Add(wxT("standard/circle"));
5948 bulletNames
.Add(wxT("standard/square"));
5949 bulletNames
.Add(wxT("standard/diamond"));
5950 bulletNames
.Add(wxT("standard/triangle"));
5956 * Module to initialise and clean up handlers
5959 class wxRichTextModule
: public wxModule
5961 DECLARE_DYNAMIC_CLASS(wxRichTextModule
)
5963 wxRichTextModule() {}
5966 wxRichTextBuffer::SetRenderer(new wxRichTextStdRenderer
);
5967 wxRichTextBuffer::InitStandardHandlers();
5968 wxRichTextParagraph::InitDefaultTabs();
5973 wxRichTextBuffer::CleanUpHandlers();
5974 wxRichTextDecimalToRoman(-1);
5975 wxRichTextParagraph::ClearDefaultTabs();
5976 wxRichTextCtrl::ClearAvailableFontNames();
5977 wxRichTextBuffer::SetRenderer(NULL
);
5981 IMPLEMENT_DYNAMIC_CLASS(wxRichTextModule
, wxModule
)
5984 // If the richtext lib is dynamically loaded after the app has already started
5985 // (such as from wxPython) then the built-in module system will not init this
5986 // module. Provide this function to do it manually.
5987 void wxRichTextModuleInit()
5989 wxModule
* module = new wxRichTextModule
;
5991 wxModule::RegisterModule(module);
5996 * Commands for undo/redo
6000 wxRichTextCommand::wxRichTextCommand(const wxString
& name
, wxRichTextCommandId id
, wxRichTextBuffer
* buffer
,
6001 wxRichTextCtrl
* ctrl
, bool ignoreFirstTime
): wxCommand(true, name
)
6003 /* wxRichTextAction* action = */ new wxRichTextAction(this, name
, id
, buffer
, ctrl
, ignoreFirstTime
);
6006 wxRichTextCommand::wxRichTextCommand(const wxString
& name
): wxCommand(true, name
)
6010 wxRichTextCommand::~wxRichTextCommand()
6015 void wxRichTextCommand::AddAction(wxRichTextAction
* action
)
6017 if (!m_actions
.Member(action
))
6018 m_actions
.Append(action
);
6021 bool wxRichTextCommand::Do()
6023 for (wxList::compatibility_iterator node
= m_actions
.GetFirst(); node
; node
= node
->GetNext())
6025 wxRichTextAction
* action
= (wxRichTextAction
*) node
->GetData();
6032 bool wxRichTextCommand::Undo()
6034 for (wxList::compatibility_iterator node
= m_actions
.GetLast(); node
; node
= node
->GetPrevious())
6036 wxRichTextAction
* action
= (wxRichTextAction
*) node
->GetData();
6043 void wxRichTextCommand::ClearActions()
6045 WX_CLEAR_LIST(wxList
, m_actions
);
6053 wxRichTextAction::wxRichTextAction(wxRichTextCommand
* cmd
, const wxString
& name
, wxRichTextCommandId id
, wxRichTextBuffer
* buffer
,
6054 wxRichTextCtrl
* ctrl
, bool ignoreFirstTime
)
6057 m_ignoreThis
= ignoreFirstTime
;
6062 m_newParagraphs
.SetDefaultStyle(buffer
->GetDefaultStyle());
6063 m_newParagraphs
.SetBasicStyle(buffer
->GetBasicStyle());
6065 cmd
->AddAction(this);
6068 wxRichTextAction::~wxRichTextAction()
6072 bool wxRichTextAction::Do()
6074 m_buffer
->Modify(true);
6078 case wxRICHTEXT_INSERT
:
6080 // Store a list of line start character and y positions so we can figure out which area
6081 // we need to refresh
6082 wxArrayInt optimizationLineCharPositions
;
6083 wxArrayInt optimizationLineYPositions
;
6085 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6086 // NOTE: we're assuming that the buffer is laid out correctly at this point.
6087 // If we had several actions, which only invalidate and leave layout until the
6088 // paint handler is called, then this might not be true. So we may need to switch
6089 // optimisation on only when we're simply adding text and not simultaneously
6090 // deleting a selection, for example. Or, we make sure the buffer is laid out correctly
6091 // first, but of course this means we'll be doing it twice.
6092 if (!m_buffer
->GetDirty() && m_ctrl
) // can only do optimisation if the buffer is already laid out correctly
6094 wxSize clientSize
= m_ctrl
->GetClientSize();
6095 wxPoint firstVisiblePt
= m_ctrl
->GetFirstVisiblePoint();
6096 int lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6098 wxRichTextParagraph
* para
= m_buffer
->GetParagraphAtPosition(GetPosition());
6099 wxRichTextObjectList::compatibility_iterator node
= m_buffer
->GetChildren().Find(para
);
6102 wxRichTextParagraph
* child
= (wxRichTextParagraph
*) node
->GetData();
6103 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
6106 wxRichTextLine
* line
= node2
->GetData();
6107 wxPoint pt
= line
->GetAbsolutePosition();
6108 wxRichTextRange range
= line
->GetAbsoluteRange();
6112 node2
= wxRichTextLineList::compatibility_iterator();
6113 node
= wxRichTextObjectList::compatibility_iterator();
6115 else if (range
.GetStart() > GetPosition() && pt
.y
>= firstVisiblePt
.y
)
6117 optimizationLineCharPositions
.Add(range
.GetStart());
6118 optimizationLineYPositions
.Add(pt
.y
);
6122 node2
= node2
->GetNext();
6126 node
= node
->GetNext();
6131 m_buffer
->InsertFragment(GetPosition(), m_newParagraphs
);
6132 m_buffer
->UpdateRanges();
6133 m_buffer
->Invalidate(GetRange());
6135 long newCaretPosition
= GetPosition() + m_newParagraphs
.GetRange().GetLength();
6137 // Character position to caret position
6138 newCaretPosition
--;
6140 // Don't take into account the last newline
6141 if (m_newParagraphs
.GetPartialParagraph())
6142 newCaretPosition
--;
6144 if (m_newParagraphs
.GetChildren().GetCount() > 1)
6146 wxRichTextObject
* p
= (wxRichTextObject
*) m_newParagraphs
.GetChildren().GetLast()->GetData();
6147 if (p
->GetRange().GetLength() == 1)
6148 newCaretPosition
--;
6151 newCaretPosition
= wxMin(newCaretPosition
, (m_buffer
->GetRange().GetEnd()-1));
6153 if (optimizationLineCharPositions
.GetCount() > 0)
6154 UpdateAppearance(newCaretPosition
, true /* send update event */, & optimizationLineCharPositions
, & optimizationLineYPositions
);
6156 UpdateAppearance(newCaretPosition
, true /* send update event */);
6158 wxRichTextEvent
cmdEvent(
6159 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED
,
6160 m_ctrl
? m_ctrl
->GetId() : -1);
6161 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6162 cmdEvent
.SetRange(GetRange());
6163 cmdEvent
.SetPosition(GetRange().GetStart());
6165 m_buffer
->SendEvent(cmdEvent
);
6169 case wxRICHTEXT_DELETE
:
6171 m_buffer
->DeleteRange(GetRange());
6172 m_buffer
->UpdateRanges();
6173 m_buffer
->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6175 UpdateAppearance(GetRange().GetStart()-1, true /* send update event */);
6177 wxRichTextEvent
cmdEvent(
6178 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED
,
6179 m_ctrl
? m_ctrl
->GetId() : -1);
6180 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6181 cmdEvent
.SetRange(GetRange());
6182 cmdEvent
.SetPosition(GetRange().GetStart());
6184 m_buffer
->SendEvent(cmdEvent
);
6188 case wxRICHTEXT_CHANGE_STYLE
:
6190 ApplyParagraphs(GetNewParagraphs());
6191 m_buffer
->Invalidate(GetRange());
6193 UpdateAppearance(GetPosition());
6195 wxRichTextEvent
cmdEvent(
6196 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED
,
6197 m_ctrl
? m_ctrl
->GetId() : -1);
6198 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6199 cmdEvent
.SetRange(GetRange());
6200 cmdEvent
.SetPosition(GetRange().GetStart());
6202 m_buffer
->SendEvent(cmdEvent
);
6213 bool wxRichTextAction::Undo()
6215 m_buffer
->Modify(true);
6219 case wxRICHTEXT_INSERT
:
6221 m_buffer
->DeleteRange(GetRange());
6222 m_buffer
->UpdateRanges();
6223 m_buffer
->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6225 long newCaretPosition
= GetPosition() - 1;
6227 UpdateAppearance(newCaretPosition
, true /* send update event */);
6229 wxRichTextEvent
cmdEvent(
6230 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED
,
6231 m_ctrl
? m_ctrl
->GetId() : -1);
6232 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6233 cmdEvent
.SetRange(GetRange());
6234 cmdEvent
.SetPosition(GetRange().GetStart());
6236 m_buffer
->SendEvent(cmdEvent
);
6240 case wxRICHTEXT_DELETE
:
6242 m_buffer
->InsertFragment(GetRange().GetStart(), m_oldParagraphs
);
6243 m_buffer
->UpdateRanges();
6244 m_buffer
->Invalidate(GetRange());
6246 UpdateAppearance(GetPosition(), true /* send update event */);
6248 wxRichTextEvent
cmdEvent(
6249 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED
,
6250 m_ctrl
? m_ctrl
->GetId() : -1);
6251 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6252 cmdEvent
.SetRange(GetRange());
6253 cmdEvent
.SetPosition(GetRange().GetStart());
6255 m_buffer
->SendEvent(cmdEvent
);
6259 case wxRICHTEXT_CHANGE_STYLE
:
6261 ApplyParagraphs(GetOldParagraphs());
6262 m_buffer
->Invalidate(GetRange());
6264 UpdateAppearance(GetPosition());
6266 wxRichTextEvent
cmdEvent(
6267 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED
,
6268 m_ctrl
? m_ctrl
->GetId() : -1);
6269 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6270 cmdEvent
.SetRange(GetRange());
6271 cmdEvent
.SetPosition(GetRange().GetStart());
6273 m_buffer
->SendEvent(cmdEvent
);
6284 /// Update the control appearance
6285 void wxRichTextAction::UpdateAppearance(long caretPosition
, bool sendUpdateEvent
, wxArrayInt
* optimizationLineCharPositions
, wxArrayInt
* optimizationLineYPositions
)
6289 m_ctrl
->SetCaretPosition(caretPosition
);
6290 if (!m_ctrl
->IsFrozen())
6292 m_ctrl
->LayoutContent();
6293 m_ctrl
->PositionCaret();
6295 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6296 // Find refresh rectangle if we are in a position to optimise refresh
6297 if (m_cmdId
== wxRICHTEXT_INSERT
&& optimizationLineCharPositions
&& optimizationLineCharPositions
->GetCount() > 0)
6301 wxSize clientSize
= m_ctrl
->GetClientSize();
6302 wxPoint firstVisiblePt
= m_ctrl
->GetFirstVisiblePoint();
6304 // Start/end positions
6306 int lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6308 bool foundStart
= false;
6309 bool foundEnd
= false;
6311 // position offset - how many characters were inserted
6312 int positionOffset
= GetRange().GetLength();
6314 // find the first line which is being drawn at the same position as it was
6315 // before. Since we're talking about a simple insertion, we can assume
6316 // that the rest of the window does not need to be redrawn.
6318 wxRichTextParagraph
* para
= m_buffer
->GetParagraphAtPosition(GetPosition());
6319 wxRichTextObjectList::compatibility_iterator node
= m_buffer
->GetChildren().Find(para
);
6322 wxRichTextParagraph
* child
= (wxRichTextParagraph
*) node
->GetData();
6323 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
6326 wxRichTextLine
* line
= node2
->GetData();
6327 wxPoint pt
= line
->GetAbsolutePosition();
6328 wxRichTextRange range
= line
->GetAbsoluteRange();
6330 // we want to find the first line that is in the same position
6331 // as before. This will mean we're at the end of the changed text.
6333 if (pt
.y
> lastY
) // going past the end of the window, no more info
6335 node2
= wxRichTextLineList::compatibility_iterator();
6336 node
= wxRichTextObjectList::compatibility_iterator();
6342 firstY
= pt
.y
- firstVisiblePt
.y
;
6346 // search for this line being at the same position as before
6347 for (i
= 0; i
< optimizationLineCharPositions
->GetCount(); i
++)
6349 if (((*optimizationLineCharPositions
)[i
] + positionOffset
== range
.GetStart()) &&
6350 ((*optimizationLineYPositions
)[i
] == pt
.y
))
6352 // Stop, we're now the same as we were
6354 lastY
= pt
.y
- firstVisiblePt
.y
;
6356 node2
= wxRichTextLineList::compatibility_iterator();
6357 node
= wxRichTextObjectList::compatibility_iterator();
6365 node2
= node2
->GetNext();
6369 node
= node
->GetNext();
6373 firstY
= firstVisiblePt
.y
;
6375 lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6377 wxRect
rect(firstVisiblePt
.x
, firstY
, firstVisiblePt
.x
+ clientSize
.x
, lastY
- firstY
);
6378 m_ctrl
->RefreshRect(rect
);
6380 // TODO: we need to make sure that lines are only drawn if in the update region. The rect
6381 // passed to Draw is currently used in different ways (to pass the position the content should
6382 // be drawn at as well as the relevant region).
6386 m_ctrl
->Refresh(false);
6388 if (sendUpdateEvent
)
6389 wxTextCtrl::SendTextUpdatedEvent(m_ctrl
);
6394 /// Replace the buffer paragraphs with the new ones.
6395 void wxRichTextAction::ApplyParagraphs(const wxRichTextParagraphLayoutBox
& fragment
)
6397 wxRichTextObjectList::compatibility_iterator node
= fragment
.GetChildren().GetFirst();
6400 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
6401 wxASSERT (para
!= NULL
);
6403 // We'll replace the existing paragraph by finding the paragraph at this position,
6404 // delete its node data, and setting a copy as the new node data.
6405 // TODO: make more efficient by simply swapping old and new paragraph objects.
6407 wxRichTextParagraph
* existingPara
= m_buffer
->GetParagraphAtPosition(para
->GetRange().GetStart());
6410 wxRichTextObjectList::compatibility_iterator bufferParaNode
= m_buffer
->GetChildren().Find(existingPara
);
6413 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(*para
);
6414 newPara
->SetParent(m_buffer
);
6416 bufferParaNode
->SetData(newPara
);
6418 delete existingPara
;
6422 node
= node
->GetNext();
6429 * This stores beginning and end positions for a range of data.
6432 /// Limit this range to be within 'range'
6433 bool wxRichTextRange::LimitTo(const wxRichTextRange
& range
)
6435 if (m_start
< range
.m_start
)
6436 m_start
= range
.m_start
;
6438 if (m_end
> range
.m_end
)
6439 m_end
= range
.m_end
;
6445 * wxRichTextImage implementation
6446 * This object represents an image.
6449 IMPLEMENT_DYNAMIC_CLASS(wxRichTextImage
, wxRichTextObject
)
6451 wxRichTextImage::wxRichTextImage(const wxImage
& image
, wxRichTextObject
* parent
, wxTextAttr
* charStyle
):
6452 wxRichTextObject(parent
)
6456 SetAttributes(*charStyle
);
6459 wxRichTextImage::wxRichTextImage(const wxRichTextImageBlock
& imageBlock
, wxRichTextObject
* parent
, wxTextAttr
* charStyle
):
6460 wxRichTextObject(parent
)
6462 m_imageBlock
= imageBlock
;
6463 m_imageBlock
.Load(m_image
);
6465 SetAttributes(*charStyle
);
6468 /// Load wxImage from the block
6469 bool wxRichTextImage::LoadFromBlock()
6471 m_imageBlock
.Load(m_image
);
6472 return m_imageBlock
.Ok();
6475 /// Make block from the wxImage
6476 bool wxRichTextImage::MakeBlock()
6478 if (m_imageBlock
.GetImageType() == wxBITMAP_TYPE_ANY
|| m_imageBlock
.GetImageType() == -1)
6479 m_imageBlock
.SetImageType(wxBITMAP_TYPE_PNG
);
6481 m_imageBlock
.MakeImageBlock(m_image
, m_imageBlock
.GetImageType());
6482 return m_imageBlock
.Ok();
6487 bool wxRichTextImage::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int WXUNUSED(descent
), int WXUNUSED(style
))
6489 if (!m_image
.Ok() && m_imageBlock
.Ok())
6495 if (m_image
.Ok() && !m_bitmap
.Ok())
6496 m_bitmap
= wxBitmap(m_image
);
6498 int y
= rect
.y
+ (rect
.height
- m_image
.GetHeight());
6501 dc
.DrawBitmap(m_bitmap
, rect
.x
, y
, true);
6503 if (selectionRange
.Contains(range
.GetStart()))
6505 wxCheckSetBrush(dc
, *wxBLACK_BRUSH
);
6506 wxCheckSetPen(dc
, *wxBLACK_PEN
);
6507 dc
.SetLogicalFunction(wxINVERT
);
6508 dc
.DrawRectangle(rect
);
6509 dc
.SetLogicalFunction(wxCOPY
);
6515 /// Lay the item out
6516 bool wxRichTextImage::Layout(wxDC
& WXUNUSED(dc
), const wxRect
& rect
, int WXUNUSED(style
))
6523 SetCachedSize(wxSize(m_image
.GetWidth(), m_image
.GetHeight()));
6524 SetPosition(rect
.GetPosition());
6530 /// Get/set the object size for the given range. Returns false if the range
6531 /// is invalid for this object.
6532 bool wxRichTextImage::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& WXUNUSED(descent
), wxDC
& WXUNUSED(dc
), int WXUNUSED(flags
), wxPoint
WXUNUSED(position
)) const
6534 if (!range
.IsWithin(GetRange()))
6540 size
.x
= m_image
.GetWidth();
6541 size
.y
= m_image
.GetHeight();
6547 void wxRichTextImage::Copy(const wxRichTextImage
& obj
)
6549 wxRichTextObject::Copy(obj
);
6551 m_image
= obj
.m_image
;
6552 m_imageBlock
= obj
.m_imageBlock
;
6560 /// Compare two attribute objects
6561 bool wxTextAttrEq(const wxTextAttr
& attr1
, const wxTextAttr
& attr2
)
6563 return (attr1
== attr2
);
6566 // Partial equality test taking flags into account
6567 bool wxTextAttrEqPartial(const wxTextAttr
& attr1
, const wxTextAttr
& attr2
, int flags
)
6569 return attr1
.EqPartial(attr2
, flags
);
6573 bool wxRichTextTabsEq(const wxArrayInt
& tabs1
, const wxArrayInt
& tabs2
)
6575 if (tabs1
.GetCount() != tabs2
.GetCount())
6579 for (i
= 0; i
< tabs1
.GetCount(); i
++)
6581 if (tabs1
[i
] != tabs2
[i
])
6587 bool wxRichTextApplyStyle(wxTextAttr
& destStyle
, const wxTextAttr
& style
, wxTextAttr
* compareWith
)
6589 return destStyle
.Apply(style
, compareWith
);
6592 // Remove attributes
6593 bool wxRichTextRemoveStyle(wxTextAttr
& destStyle
, const wxTextAttr
& style
)
6595 return wxTextAttr::RemoveStyle(destStyle
, style
);
6598 /// Combine two bitlists, specifying the bits of interest with separate flags.
6599 bool wxRichTextCombineBitlists(int& valueA
, int valueB
, int& flagsA
, int flagsB
)
6601 return wxTextAttr::CombineBitlists(valueA
, valueB
, flagsA
, flagsB
);
6604 /// Compare two bitlists
6605 bool wxRichTextBitlistsEqPartial(int valueA
, int valueB
, int flags
)
6607 return wxTextAttr::BitlistsEqPartial(valueA
, valueB
, flags
);
6610 /// Split into paragraph and character styles
6611 bool wxRichTextSplitParaCharStyles(const wxTextAttr
& style
, wxTextAttr
& parStyle
, wxTextAttr
& charStyle
)
6613 return wxTextAttr::SplitParaCharStyles(style
, parStyle
, charStyle
);
6616 /// Convert a decimal to Roman numerals
6617 wxString
wxRichTextDecimalToRoman(long n
)
6619 static wxArrayInt decimalNumbers
;
6620 static wxArrayString romanNumbers
;
6625 decimalNumbers
.Clear();
6626 romanNumbers
.Clear();
6627 return wxEmptyString
;
6630 if (decimalNumbers
.GetCount() == 0)
6632 #define wxRichTextAddDecRom(n, r) decimalNumbers.Add(n); romanNumbers.Add(r);
6634 wxRichTextAddDecRom(1000, wxT("M"));
6635 wxRichTextAddDecRom(900, wxT("CM"));
6636 wxRichTextAddDecRom(500, wxT("D"));
6637 wxRichTextAddDecRom(400, wxT("CD"));
6638 wxRichTextAddDecRom(100, wxT("C"));
6639 wxRichTextAddDecRom(90, wxT("XC"));
6640 wxRichTextAddDecRom(50, wxT("L"));
6641 wxRichTextAddDecRom(40, wxT("XL"));
6642 wxRichTextAddDecRom(10, wxT("X"));
6643 wxRichTextAddDecRom(9, wxT("IX"));
6644 wxRichTextAddDecRom(5, wxT("V"));
6645 wxRichTextAddDecRom(4, wxT("IV"));
6646 wxRichTextAddDecRom(1, wxT("I"));
6652 while (n
> 0 && i
< 13)
6654 if (n
>= decimalNumbers
[i
])
6656 n
-= decimalNumbers
[i
];
6657 roman
+= romanNumbers
[i
];
6664 if (roman
.IsEmpty())
6670 * wxRichTextFileHandler
6671 * Base class for file handlers
6674 IMPLEMENT_CLASS(wxRichTextFileHandler
, wxObject
)
6676 #if wxUSE_FFILE && wxUSE_STREAMS
6677 bool wxRichTextFileHandler::LoadFile(wxRichTextBuffer
*buffer
, const wxString
& filename
)
6679 wxFFileInputStream
stream(filename
);
6681 return LoadFile(buffer
, stream
);
6686 bool wxRichTextFileHandler::SaveFile(wxRichTextBuffer
*buffer
, const wxString
& filename
)
6688 wxFFileOutputStream
stream(filename
);
6690 return SaveFile(buffer
, stream
);
6694 #endif // wxUSE_FFILE && wxUSE_STREAMS
6696 /// Can we handle this filename (if using files)? By default, checks the extension.
6697 bool wxRichTextFileHandler::CanHandle(const wxString
& filename
) const
6699 wxString path
, file
, ext
;
6700 wxSplitPath(filename
, & path
, & file
, & ext
);
6702 return (ext
.Lower() == GetExtension());
6706 * wxRichTextTextHandler
6707 * Plain text handler
6710 IMPLEMENT_CLASS(wxRichTextPlainTextHandler
, wxRichTextFileHandler
)
6713 bool wxRichTextPlainTextHandler::DoLoadFile(wxRichTextBuffer
*buffer
, wxInputStream
& stream
)
6721 while (!stream
.Eof())
6723 int ch
= stream
.GetC();
6727 if (ch
== 10 && lastCh
!= 13)
6730 if (ch
> 0 && ch
!= 10)
6737 buffer
->ResetAndClearCommands();
6739 buffer
->AddParagraphs(str
);
6740 buffer
->UpdateRanges();
6745 bool wxRichTextPlainTextHandler::DoSaveFile(wxRichTextBuffer
*buffer
, wxOutputStream
& stream
)
6750 wxString text
= buffer
->GetText();
6752 wxString newLine
= wxRichTextLineBreakChar
;
6753 text
.Replace(newLine
, wxT("\n"));
6755 wxCharBuffer buf
= text
.ToAscii();
6757 stream
.Write((const char*) buf
, text
.length());
6760 #endif // wxUSE_STREAMS
6763 * Stores information about an image, in binary in-memory form
6766 wxRichTextImageBlock::wxRichTextImageBlock()
6771 wxRichTextImageBlock::wxRichTextImageBlock(const wxRichTextImageBlock
& block
):wxObject()
6777 wxRichTextImageBlock::~wxRichTextImageBlock()
6786 void wxRichTextImageBlock::Init()
6793 void wxRichTextImageBlock::Clear()
6802 // Load the original image into a memory block.
6803 // If the image is not a JPEG, we must convert it into a JPEG
6804 // to conserve space.
6805 // If it's not a JPEG we can make use of 'image', already scaled, so we don't have to
6806 // load the image a 2nd time.
6808 bool wxRichTextImageBlock::MakeImageBlock(const wxString
& filename
, int imageType
, wxImage
& image
, bool convertToJPEG
)
6810 m_imageType
= imageType
;
6812 wxString
filenameToRead(filename
);
6813 bool removeFile
= false;
6815 if (imageType
== -1)
6816 return false; // Could not determine image type
6818 if ((imageType
!= wxBITMAP_TYPE_JPEG
) && convertToJPEG
)
6821 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
6825 wxUnusedVar(success
);
6827 image
.SaveFile(tempFile
, wxBITMAP_TYPE_JPEG
);
6828 filenameToRead
= tempFile
;
6831 m_imageType
= wxBITMAP_TYPE_JPEG
;
6834 if (!file
.Open(filenameToRead
))
6837 m_dataSize
= (size_t) file
.Length();
6842 m_data
= ReadBlock(filenameToRead
, m_dataSize
);
6845 wxRemoveFile(filenameToRead
);
6847 return (m_data
!= NULL
);
6850 // Make an image block from the wxImage in the given
6852 bool wxRichTextImageBlock::MakeImageBlock(wxImage
& image
, int imageType
, int quality
)
6854 m_imageType
= imageType
;
6855 image
.SetOption(wxT("quality"), quality
);
6857 if (imageType
== -1)
6858 return false; // Could not determine image type
6861 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
6864 wxUnusedVar(success
);
6866 if (!image
.SaveFile(tempFile
, m_imageType
))
6868 if (wxFileExists(tempFile
))
6869 wxRemoveFile(tempFile
);
6874 if (!file
.Open(tempFile
))
6877 m_dataSize
= (size_t) file
.Length();
6882 m_data
= ReadBlock(tempFile
, m_dataSize
);
6884 wxRemoveFile(tempFile
);
6886 return (m_data
!= NULL
);
6891 bool wxRichTextImageBlock::Write(const wxString
& filename
)
6893 return WriteBlock(filename
, m_data
, m_dataSize
);
6896 void wxRichTextImageBlock::Copy(const wxRichTextImageBlock
& block
)
6898 m_imageType
= block
.m_imageType
;
6904 m_dataSize
= block
.m_dataSize
;
6905 if (m_dataSize
== 0)
6908 m_data
= new unsigned char[m_dataSize
];
6910 for (i
= 0; i
< m_dataSize
; i
++)
6911 m_data
[i
] = block
.m_data
[i
];
6915 void wxRichTextImageBlock::operator=(const wxRichTextImageBlock
& block
)
6920 // Load a wxImage from the block
6921 bool wxRichTextImageBlock::Load(wxImage
& image
)
6926 // Read in the image.
6928 wxMemoryInputStream
mstream(m_data
, m_dataSize
);
6929 bool success
= image
.LoadFile(mstream
, GetImageType());
6932 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
6935 if (!WriteBlock(tempFile
, m_data
, m_dataSize
))
6939 success
= image
.LoadFile(tempFile
, GetImageType());
6940 wxRemoveFile(tempFile
);
6946 // Write data in hex to a stream
6947 bool wxRichTextImageBlock::WriteHex(wxOutputStream
& stream
)
6949 const int bufSize
= 512;
6950 char buf
[bufSize
+1];
6952 int left
= m_dataSize
;
6957 if (left
*2 > bufSize
)
6959 n
= bufSize
; left
-= (bufSize
/2);
6963 n
= left
*2; left
= 0;
6967 for (i
= 0; i
< (n
/2); i
++)
6969 wxDecToHex(m_data
[j
], b
, b
+1);
6974 stream
.Write((const char*) buf
, n
);
6979 // Read data in hex from a stream
6980 bool wxRichTextImageBlock::ReadHex(wxInputStream
& stream
, int length
, int imageType
)
6982 int dataSize
= length
/2;
6988 m_data
= new unsigned char[dataSize
];
6990 for (i
= 0; i
< dataSize
; i
++)
6992 str
[0] = (char)stream
.GetC();
6993 str
[1] = (char)stream
.GetC();
6995 m_data
[i
] = (unsigned char)wxHexToDec(str
);
6998 m_dataSize
= dataSize
;
6999 m_imageType
= imageType
;
7004 // Allocate and read from stream as a block of memory
7005 unsigned char* wxRichTextImageBlock::ReadBlock(wxInputStream
& stream
, size_t size
)
7007 unsigned char* block
= new unsigned char[size
];
7011 stream
.Read(block
, size
);
7016 unsigned char* wxRichTextImageBlock::ReadBlock(const wxString
& filename
, size_t size
)
7018 wxFileInputStream
stream(filename
);
7022 return ReadBlock(stream
, size
);
7025 // Write memory block to stream
7026 bool wxRichTextImageBlock::WriteBlock(wxOutputStream
& stream
, unsigned char* block
, size_t size
)
7028 stream
.Write((void*) block
, size
);
7029 return stream
.IsOk();
7033 // Write memory block to file
7034 bool wxRichTextImageBlock::WriteBlock(const wxString
& filename
, unsigned char* block
, size_t size
)
7036 wxFileOutputStream
outStream(filename
);
7037 if (!outStream
.Ok())
7040 return WriteBlock(outStream
, block
, size
);
7043 // Gets the extension for the block's type
7044 wxString
wxRichTextImageBlock::GetExtension() const
7046 wxImageHandler
* handler
= wxImage::FindHandler(GetImageType());
7048 return handler
->GetExtension();
7050 return wxEmptyString
;
7056 * The data object for a wxRichTextBuffer
7059 const wxChar
*wxRichTextBufferDataObject::ms_richTextBufferFormatId
= wxT("wxShape");
7061 wxRichTextBufferDataObject::wxRichTextBufferDataObject(wxRichTextBuffer
* richTextBuffer
)
7063 m_richTextBuffer
= richTextBuffer
;
7065 // this string should uniquely identify our format, but is otherwise
7067 m_formatRichTextBuffer
.SetId(GetRichTextBufferFormatId());
7069 SetFormat(m_formatRichTextBuffer
);
7072 wxRichTextBufferDataObject::~wxRichTextBufferDataObject()
7074 delete m_richTextBuffer
;
7077 // after a call to this function, the richTextBuffer is owned by the caller and it
7078 // is responsible for deleting it!
7079 wxRichTextBuffer
* wxRichTextBufferDataObject::GetRichTextBuffer()
7081 wxRichTextBuffer
* richTextBuffer
= m_richTextBuffer
;
7082 m_richTextBuffer
= NULL
;
7084 return richTextBuffer
;
7087 wxDataFormat
wxRichTextBufferDataObject::GetPreferredFormat(Direction
WXUNUSED(dir
)) const
7089 return m_formatRichTextBuffer
;
7092 size_t wxRichTextBufferDataObject::GetDataSize() const
7094 if (!m_richTextBuffer
)
7100 wxStringOutputStream
stream(& bufXML
);
7101 if (!m_richTextBuffer
->SaveFile(stream
, wxRICHTEXT_TYPE_XML
))
7103 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
7109 wxCharBuffer buffer
= bufXML
.mb_str(wxConvUTF8
);
7110 return strlen(buffer
) + 1;
7112 return bufXML
.Length()+1;
7116 bool wxRichTextBufferDataObject::GetDataHere(void *pBuf
) const
7118 if (!pBuf
|| !m_richTextBuffer
)
7124 wxStringOutputStream
stream(& bufXML
);
7125 if (!m_richTextBuffer
->SaveFile(stream
, wxRICHTEXT_TYPE_XML
))
7127 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
7133 wxCharBuffer buffer
= bufXML
.mb_str(wxConvUTF8
);
7134 size_t len
= strlen(buffer
);
7135 memcpy((char*) pBuf
, (const char*) buffer
, len
);
7136 ((char*) pBuf
)[len
] = 0;
7138 size_t len
= bufXML
.Length();
7139 memcpy((char*) pBuf
, (const char*) bufXML
.c_str(), len
);
7140 ((char*) pBuf
)[len
] = 0;
7146 bool wxRichTextBufferDataObject::SetData(size_t WXUNUSED(len
), const void *buf
)
7148 delete m_richTextBuffer
;
7149 m_richTextBuffer
= NULL
;
7151 wxString
bufXML((const char*) buf
, wxConvUTF8
);
7153 m_richTextBuffer
= new wxRichTextBuffer
;
7155 wxStringInputStream
stream(bufXML
);
7156 if (!m_richTextBuffer
->LoadFile(stream
, wxRICHTEXT_TYPE_XML
))
7158 wxLogError(wxT("Could not read the buffer from an XML stream.\nYou may have forgotten to add the XML file handler."));
7160 delete m_richTextBuffer
;
7161 m_richTextBuffer
= NULL
;
7173 * wxRichTextFontTable
7174 * Manages quick access to a pool of fonts for rendering rich text
7177 WX_DECLARE_STRING_HASH_MAP_WITH_DECL(wxFont
, wxRichTextFontTableHashMap
, class WXDLLIMPEXP_RICHTEXT
);
7179 class wxRichTextFontTableData
: public wxObjectRefData
7182 wxRichTextFontTableData() {}
7184 wxFont
FindFont(const wxTextAttr
& fontSpec
);
7186 wxRichTextFontTableHashMap m_hashMap
;
7189 wxFont
wxRichTextFontTableData::FindFont(const wxTextAttr
& fontSpec
)
7191 wxString
facename(fontSpec
.GetFontFaceName());
7192 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()));
7193 wxRichTextFontTableHashMap::iterator entry
= m_hashMap
.find(spec
);
7195 if ( entry
== m_hashMap
.end() )
7197 wxFont
font(fontSpec
.GetFontSize(), wxDEFAULT
, fontSpec
.GetFontStyle(), fontSpec
.GetFontWeight(), fontSpec
.GetFontUnderlined(), facename
.c_str());
7198 m_hashMap
[spec
] = font
;
7203 return entry
->second
;
7207 IMPLEMENT_DYNAMIC_CLASS(wxRichTextFontTable
, wxObject
)
7209 wxRichTextFontTable::wxRichTextFontTable()
7211 m_refData
= new wxRichTextFontTableData
;
7212 m_refData
->IncRef();
7215 wxRichTextFontTable::wxRichTextFontTable(const wxRichTextFontTable
& table
)
7220 wxRichTextFontTable::~wxRichTextFontTable()
7225 bool wxRichTextFontTable::operator == (const wxRichTextFontTable
& table
) const
7227 return (m_refData
== table
.m_refData
);
7230 void wxRichTextFontTable::operator= (const wxRichTextFontTable
& table
)
7235 wxFont
wxRichTextFontTable::FindFont(const wxTextAttr
& fontSpec
)
7237 wxRichTextFontTableData
* data
= (wxRichTextFontTableData
*) m_refData
;
7239 return data
->FindFont(fontSpec
);
7244 void wxRichTextFontTable::Clear()
7246 wxRichTextFontTableData
* data
= (wxRichTextFontTableData
*) m_refData
;
7248 data
->m_hashMap
.clear();