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 AddParagraph(wxEmptyString
);
2424 Invalidate(wxRICHTEXT_ALL
);
2427 /// Invalidate the buffer. With no argument, invalidates whole buffer.
2428 void wxRichTextParagraphLayoutBox::Invalidate(const wxRichTextRange
& invalidRange
)
2432 if (invalidRange
== wxRICHTEXT_ALL
)
2434 m_invalidRange
= wxRICHTEXT_ALL
;
2438 // Already invalidating everything
2439 if (m_invalidRange
== wxRICHTEXT_ALL
)
2442 if ((invalidRange
.GetStart() < m_invalidRange
.GetStart()) || m_invalidRange
.GetStart() == -1)
2443 m_invalidRange
.SetStart(invalidRange
.GetStart());
2444 if (invalidRange
.GetEnd() > m_invalidRange
.GetEnd())
2445 m_invalidRange
.SetEnd(invalidRange
.GetEnd());
2448 /// Get invalid range, rounding to entire paragraphs if argument is true.
2449 wxRichTextRange
wxRichTextParagraphLayoutBox::GetInvalidRange(bool wholeParagraphs
) const
2451 if (m_invalidRange
== wxRICHTEXT_ALL
|| m_invalidRange
== wxRICHTEXT_NONE
)
2452 return m_invalidRange
;
2454 wxRichTextRange range
= m_invalidRange
;
2456 if (wholeParagraphs
)
2458 wxRichTextParagraph
* para1
= GetParagraphAtPosition(range
.GetStart());
2459 wxRichTextParagraph
* para2
= GetParagraphAtPosition(range
.GetEnd());
2461 range
.SetStart(para1
->GetRange().GetStart());
2463 range
.SetEnd(para2
->GetRange().GetEnd());
2468 /// Apply the style sheet to the buffer, for example if the styles have changed.
2469 bool wxRichTextParagraphLayoutBox::ApplyStyleSheet(wxRichTextStyleSheet
* styleSheet
)
2471 wxASSERT(styleSheet
!= NULL
);
2477 wxRichTextAttr
attr(GetBasicStyle());
2478 if (GetBasicStyle().HasParagraphStyleName())
2480 wxRichTextParagraphStyleDefinition
* paraDef
= styleSheet
->FindParagraphStyle(GetBasicStyle().GetParagraphStyleName());
2483 attr
.Apply(paraDef
->GetStyleMergedWithBase(styleSheet
));
2484 SetBasicStyle(attr
);
2489 if (GetBasicStyle().HasCharacterStyleName())
2491 wxRichTextCharacterStyleDefinition
* charDef
= styleSheet
->FindCharacterStyle(GetBasicStyle().GetCharacterStyleName());
2494 attr
.Apply(charDef
->GetStyleMergedWithBase(styleSheet
));
2495 SetBasicStyle(attr
);
2500 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2503 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2504 wxASSERT (para
!= NULL
);
2508 // Combine paragraph and list styles. If there is a list style in the original attributes,
2509 // the current indentation overrides anything else and is used to find the item indentation.
2510 // Also, for applying paragraph styles, consider having 2 modes: (1) we merge with what we have,
2511 // thereby taking into account all user changes, (2) reset the style completely (except for indentation/list
2512 // exception as above).
2513 // Problem: when changing from one list style to another, there's a danger that the level info will get lost.
2514 // So when changing a list style interactively, could retrieve level based on current style, then
2515 // set appropriate indent and apply new style.
2517 if (!para
->GetAttributes().GetParagraphStyleName().IsEmpty() && !para
->GetAttributes().GetListStyleName().IsEmpty())
2519 int currentIndent
= para
->GetAttributes().GetLeftIndent();
2521 wxRichTextParagraphStyleDefinition
* paraDef
= styleSheet
->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
2522 wxRichTextListStyleDefinition
* listDef
= styleSheet
->FindListStyle(para
->GetAttributes().GetListStyleName());
2523 if (paraDef
&& !listDef
)
2525 para
->GetAttributes() = paraDef
->GetStyleMergedWithBase(styleSheet
);
2528 else if (listDef
&& !paraDef
)
2530 // Set overall style defined for the list style definition
2531 para
->GetAttributes() = listDef
->GetStyleMergedWithBase(styleSheet
);
2533 // Apply the style for this level
2534 wxRichTextApplyStyle(para
->GetAttributes(), * listDef
->GetLevelAttributes(listDef
->FindLevelForIndent(currentIndent
)));
2537 else if (listDef
&& paraDef
)
2539 // Combines overall list style, style for level, and paragraph style
2540 para
->GetAttributes() = listDef
->CombineWithParagraphStyle(currentIndent
, paraDef
->GetStyleMergedWithBase(styleSheet
));
2544 else if (para
->GetAttributes().GetParagraphStyleName().IsEmpty() && !para
->GetAttributes().GetListStyleName().IsEmpty())
2546 int currentIndent
= para
->GetAttributes().GetLeftIndent();
2548 wxRichTextListStyleDefinition
* listDef
= styleSheet
->FindListStyle(para
->GetAttributes().GetListStyleName());
2550 // Overall list definition style
2551 para
->GetAttributes() = listDef
->GetStyleMergedWithBase(styleSheet
);
2553 // Style for this level
2554 wxRichTextApplyStyle(para
->GetAttributes(), * listDef
->GetLevelAttributes(listDef
->FindLevelForIndent(currentIndent
)));
2558 else if (!para
->GetAttributes().GetParagraphStyleName().IsEmpty() && para
->GetAttributes().GetListStyleName().IsEmpty())
2560 wxRichTextParagraphStyleDefinition
* def
= styleSheet
->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
2563 para
->GetAttributes() = def
->GetStyleMergedWithBase(styleSheet
);
2569 node
= node
->GetNext();
2571 return foundCount
!= 0;
2575 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2577 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2579 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
2580 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2581 bool specifyLevel
= ((flags
& wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL
) != 0);
2582 bool renumber
= ((flags
& wxRICHTEXT_SETSTYLE_RENUMBER
) != 0);
2584 // Current number, if numbering
2587 wxASSERT (!specifyLevel
|| (specifyLevel
&& (specifiedLevel
>= 0)));
2589 // If we are associated with a control, make undoable; otherwise, apply immediately
2592 bool haveControl
= (GetRichTextCtrl() != NULL
);
2594 wxRichTextAction
* action
= NULL
;
2596 if (haveControl
&& withUndo
)
2598 action
= new wxRichTextAction(NULL
, _("Change List Style"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2599 action
->SetRange(range
);
2600 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2603 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2606 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2607 wxASSERT (para
!= NULL
);
2609 if (para
&& para
->GetChildCount() > 0)
2611 // Stop searching if we're beyond the range of interest
2612 if (para
->GetRange().GetStart() > range
.GetEnd())
2615 if (!para
->GetRange().IsOutside(range
))
2617 // We'll be using a copy of the paragraph to make style changes,
2618 // not updating the buffer directly.
2619 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
2621 if (haveControl
&& withUndo
)
2623 newPara
= new wxRichTextParagraph(*para
);
2624 action
->GetNewParagraphs().AppendChild(newPara
);
2626 // Also store the old ones for Undo
2627 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
2634 int thisIndent
= newPara
->GetAttributes().GetLeftIndent();
2635 int thisLevel
= specifyLevel
? specifiedLevel
: def
->FindLevelForIndent(thisIndent
);
2637 // How is numbering going to work?
2638 // If we are renumbering, or numbering for the first time, we need to keep
2639 // track of the number for each level. But we might be simply applying a different
2641 // In Word, applying a style to several paragraphs, even if at different levels,
2642 // reverts the level back to the same one. So we could do the same here.
2643 // Renumbering will need to be done when we promote/demote a paragraph.
2645 // Apply the overall list style, and item style for this level
2646 wxTextAttr
listStyle(def
->GetCombinedStyleForLevel(thisLevel
, styleSheet
));
2647 wxRichTextApplyStyle(newPara
->GetAttributes(), listStyle
);
2649 // Now we need to do numbering
2652 newPara
->GetAttributes().SetBulletNumber(n
);
2657 else if (!newPara
->GetAttributes().GetListStyleName().IsEmpty())
2659 // if def is NULL, remove list style, applying any associated paragraph style
2660 // to restore the attributes
2662 newPara
->GetAttributes().SetListStyleName(wxEmptyString
);
2663 newPara
->GetAttributes().SetLeftIndent(0, 0);
2664 newPara
->GetAttributes().SetBulletText(wxEmptyString
);
2666 // Eliminate the main list-related attributes
2667 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
);
2669 if (styleSheet
&& !newPara
->GetAttributes().GetParagraphStyleName().IsEmpty())
2671 wxRichTextParagraphStyleDefinition
* def
= styleSheet
->FindParagraphStyle(newPara
->GetAttributes().GetParagraphStyleName());
2674 newPara
->GetAttributes() = def
->GetStyleMergedWithBase(styleSheet
);
2681 node
= node
->GetNext();
2684 // Do action, or delay it until end of batch.
2685 if (haveControl
&& withUndo
)
2686 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
2691 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int startFrom
, int specifiedLevel
)
2693 if (GetStyleSheet())
2695 wxRichTextListStyleDefinition
* def
= GetStyleSheet()->FindListStyle(defName
);
2697 return SetListStyle(range
, def
, flags
, startFrom
, specifiedLevel
);
2702 /// Clear list for given range
2703 bool wxRichTextParagraphLayoutBox::ClearListStyle(const wxRichTextRange
& range
, int flags
)
2705 return SetListStyle(range
, NULL
, flags
);
2708 /// Number/renumber any list elements in the given range
2709 bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2711 return DoNumberList(range
, range
, 0, def
, flags
, startFrom
, specifiedLevel
);
2714 /// Number/renumber any list elements in the given range. Also do promotion or demotion of items, if specified
2715 bool wxRichTextParagraphLayoutBox::DoNumberList(const wxRichTextRange
& range
, const wxRichTextRange
& promotionRange
, int promoteBy
,
2716 wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2718 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2720 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
2721 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2723 bool specifyLevel
= ((flags
& wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL
) != 0);
2726 bool renumber
= ((flags
& wxRICHTEXT_SETSTYLE_RENUMBER
) != 0);
2728 // Max number of levels
2729 const int maxLevels
= 10;
2731 // The level we're looking at now
2732 int currentLevel
= -1;
2734 // The item number for each level
2735 int levels
[maxLevels
];
2738 // Reset all numbering
2739 for (i
= 0; i
< maxLevels
; i
++)
2741 if (startFrom
!= -1)
2742 levels
[i
] = startFrom
-1;
2743 else if (renumber
) // start again
2746 levels
[i
] = -1; // start from the number we found, if any
2749 wxASSERT(!specifyLevel
|| (specifyLevel
&& (specifiedLevel
>= 0)));
2751 // If we are associated with a control, make undoable; otherwise, apply immediately
2754 bool haveControl
= (GetRichTextCtrl() != NULL
);
2756 wxRichTextAction
* action
= NULL
;
2758 if (haveControl
&& withUndo
)
2760 action
= new wxRichTextAction(NULL
, _("Renumber List"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2761 action
->SetRange(range
);
2762 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2765 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2768 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2769 wxASSERT (para
!= NULL
);
2771 if (para
&& para
->GetChildCount() > 0)
2773 // Stop searching if we're beyond the range of interest
2774 if (para
->GetRange().GetStart() > range
.GetEnd())
2777 if (!para
->GetRange().IsOutside(range
))
2779 // We'll be using a copy of the paragraph to make style changes,
2780 // not updating the buffer directly.
2781 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
2783 if (haveControl
&& withUndo
)
2785 newPara
= new wxRichTextParagraph(*para
);
2786 action
->GetNewParagraphs().AppendChild(newPara
);
2788 // Also store the old ones for Undo
2789 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
2794 wxRichTextListStyleDefinition
* defToUse
= def
;
2797 if (styleSheet
&& !newPara
->GetAttributes().GetListStyleName().IsEmpty())
2798 defToUse
= styleSheet
->FindListStyle(newPara
->GetAttributes().GetListStyleName());
2803 int thisIndent
= newPara
->GetAttributes().GetLeftIndent();
2804 int thisLevel
= defToUse
->FindLevelForIndent(thisIndent
);
2806 // If we've specified a level to apply to all, change the level.
2807 if (specifiedLevel
!= -1)
2808 thisLevel
= specifiedLevel
;
2810 // Do promotion if specified
2811 if ((promoteBy
!= 0) && !para
->GetRange().IsOutside(promotionRange
))
2813 thisLevel
= thisLevel
- promoteBy
;
2820 // Apply the overall list style, and item style for this level
2821 wxTextAttr
listStyle(defToUse
->GetCombinedStyleForLevel(thisLevel
, styleSheet
));
2822 wxRichTextApplyStyle(newPara
->GetAttributes(), listStyle
);
2824 // OK, we've (re)applied the style, now let's get the numbering right.
2826 if (currentLevel
== -1)
2827 currentLevel
= thisLevel
;
2829 // Same level as before, do nothing except increment level's number afterwards
2830 if (currentLevel
== thisLevel
)
2833 // A deeper level: start renumbering all levels after current level
2834 else if (thisLevel
> currentLevel
)
2836 for (i
= currentLevel
+1; i
<= thisLevel
; i
++)
2840 currentLevel
= thisLevel
;
2842 else if (thisLevel
< currentLevel
)
2844 currentLevel
= thisLevel
;
2847 // Use the current numbering if -1 and we have a bullet number already
2848 if (levels
[currentLevel
] == -1)
2850 if (newPara
->GetAttributes().HasBulletNumber())
2851 levels
[currentLevel
] = newPara
->GetAttributes().GetBulletNumber();
2853 levels
[currentLevel
] = 1;
2857 levels
[currentLevel
] ++;
2860 newPara
->GetAttributes().SetBulletNumber(levels
[currentLevel
]);
2862 // Create the bullet text if an outline list
2863 if (listStyle
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
)
2866 for (i
= 0; i
<= currentLevel
; i
++)
2868 if (!text
.IsEmpty())
2870 text
+= wxString::Format(wxT("%d"), levels
[i
]);
2872 newPara
->GetAttributes().SetBulletText(text
);
2878 node
= node
->GetNext();
2881 // Do action, or delay it until end of batch.
2882 if (haveControl
&& withUndo
)
2883 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
2888 bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int startFrom
, int specifiedLevel
)
2890 if (GetStyleSheet())
2892 wxRichTextListStyleDefinition
* def
= NULL
;
2893 if (!defName
.IsEmpty())
2894 def
= GetStyleSheet()->FindListStyle(defName
);
2895 return NumberList(range
, def
, flags
, startFrom
, specifiedLevel
);
2900 /// Promote the list items within the given range. promoteBy can be a positive or negative number, e.g. 1 or -1
2901 bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy
, const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int specifiedLevel
)
2904 // One strategy is to first work out the range within which renumbering must occur. Then could pass these two ranges
2905 // to NumberList with a flag indicating promotion is required within one of the ranges.
2906 // Find first and last paragraphs in range. Then for first, calculate new indentation and look back until we find
2907 // a paragraph that either has no list style, or has one that is different or whose indentation is less.
2908 // We start renumbering from the para after that different para we found. We specify that the numbering of that
2909 // list position will start from 1.
2910 // Similarly, we look after the last para in the promote range for an indentation that is less (or no list style).
2911 // We can end the renumbering at this point.
2913 // For now, only renumber within the promotion range.
2915 return DoNumberList(range
, range
, promoteBy
, def
, flags
, 1, specifiedLevel
);
2918 bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy
, const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int specifiedLevel
)
2920 if (GetStyleSheet())
2922 wxRichTextListStyleDefinition
* def
= NULL
;
2923 if (!defName
.IsEmpty())
2924 def
= GetStyleSheet()->FindListStyle(defName
);
2925 return PromoteList(promoteBy
, range
, def
, flags
, specifiedLevel
);
2930 /// Fills in the attributes for numbering a paragraph after previousParagraph. It also finds the
2931 /// position of the paragraph that it had to start looking from.
2932 bool wxRichTextParagraphLayoutBox::FindNextParagraphNumber(wxRichTextParagraph
* previousParagraph
, wxTextAttr
& attr
) const
2934 if (!previousParagraph
->GetAttributes().HasFlag(wxTEXT_ATTR_BULLET_STYLE
) || previousParagraph
->GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE
)
2937 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2938 if (styleSheet
&& !previousParagraph
->GetAttributes().GetListStyleName().IsEmpty())
2940 wxRichTextListStyleDefinition
* def
= styleSheet
->FindListStyle(previousParagraph
->GetAttributes().GetListStyleName());
2943 // int thisIndent = previousParagraph->GetAttributes().GetLeftIndent();
2944 // int thisLevel = def->FindLevelForIndent(thisIndent);
2946 bool isOutline
= (previousParagraph
->GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
) != 0;
2948 attr
.SetFlags(previousParagraph
->GetAttributes().GetFlags() & (wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_BULLET_NUMBER
|wxTEXT_ATTR_BULLET_TEXT
|wxTEXT_ATTR_BULLET_NAME
));
2949 if (previousParagraph
->GetAttributes().HasBulletName())
2950 attr
.SetBulletName(previousParagraph
->GetAttributes().GetBulletName());
2951 attr
.SetBulletStyle(previousParagraph
->GetAttributes().GetBulletStyle());
2952 attr
.SetListStyleName(previousParagraph
->GetAttributes().GetListStyleName());
2954 int nextNumber
= previousParagraph
->GetAttributes().GetBulletNumber() + 1;
2955 attr
.SetBulletNumber(nextNumber
);
2959 wxString text
= previousParagraph
->GetAttributes().GetBulletText();
2960 if (!text
.IsEmpty())
2962 int pos
= text
.Find(wxT('.'), true);
2963 if (pos
!= wxNOT_FOUND
)
2965 text
= text
.Mid(0, text
.Length() - pos
- 1);
2968 text
= wxEmptyString
;
2969 if (!text
.IsEmpty())
2971 text
+= wxString::Format(wxT("%d"), nextNumber
);
2972 attr
.SetBulletText(text
);
2986 * wxRichTextParagraph
2987 * This object represents a single paragraph (or in a straight text editor, a line).
2990 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraph
, wxRichTextBox
)
2992 wxArrayInt
wxRichTextParagraph::sm_defaultTabs
;
2994 wxRichTextParagraph::wxRichTextParagraph(wxRichTextObject
* parent
, wxTextAttr
* style
):
2995 wxRichTextBox(parent
)
2998 SetAttributes(*style
);
3001 wxRichTextParagraph::wxRichTextParagraph(const wxString
& text
, wxRichTextObject
* parent
, wxTextAttr
* paraStyle
, wxTextAttr
* charStyle
):
3002 wxRichTextBox(parent
)
3005 SetAttributes(*paraStyle
);
3007 AppendChild(new wxRichTextPlainText(text
, this, charStyle
));
3010 wxRichTextParagraph::~wxRichTextParagraph()
3016 bool wxRichTextParagraph::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& WXUNUSED(rect
), int WXUNUSED(descent
), int style
)
3018 wxTextAttr attr
= GetCombinedAttributes();
3020 // Draw the bullet, if any
3021 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3023 if (attr
.GetLeftSubIndent() != 0)
3025 int spaceBeforePara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingBefore());
3026 int leftIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftIndent());
3028 wxTextAttr
bulletAttr(GetCombinedAttributes());
3030 // Combine with the font of the first piece of content, if one is specified
3031 if (GetChildren().GetCount() > 0)
3033 wxRichTextObject
* firstObj
= (wxRichTextObject
*) GetChildren().GetFirst()->GetData();
3034 if (firstObj
->GetAttributes().HasFont())
3036 wxRichTextApplyStyle(bulletAttr
, firstObj
->GetAttributes());
3040 // Get line height from first line, if any
3041 wxRichTextLine
* line
= m_cachedLines
.GetFirst() ? (wxRichTextLine
* ) m_cachedLines
.GetFirst()->GetData() : (wxRichTextLine
*) NULL
;
3044 int lineHeight
wxDUMMY_INITIALIZE(0);
3047 lineHeight
= line
->GetSize().y
;
3048 linePos
= line
->GetPosition() + GetPosition();
3053 if (bulletAttr
.HasFont() && GetBuffer())
3054 font
= GetBuffer()->GetFontTable().FindFont(bulletAttr
);
3056 font
= (*wxNORMAL_FONT
);
3058 wxCheckSetFont(dc
, font
);
3060 lineHeight
= dc
.GetCharHeight();
3061 linePos
= GetPosition();
3062 linePos
.y
+= spaceBeforePara
;
3065 wxRect
bulletRect(GetPosition().x
+ leftIndent
, linePos
.y
, linePos
.x
- (GetPosition().x
+ leftIndent
), lineHeight
);
3067 if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP
)
3069 if (wxRichTextBuffer::GetRenderer())
3070 wxRichTextBuffer::GetRenderer()->DrawBitmapBullet(this, dc
, bulletAttr
, bulletRect
);
3072 else if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_STANDARD
)
3074 if (wxRichTextBuffer::GetRenderer())
3075 wxRichTextBuffer::GetRenderer()->DrawStandardBullet(this, dc
, bulletAttr
, bulletRect
);
3079 wxString bulletText
= GetBulletText();
3081 if (!bulletText
.empty() && wxRichTextBuffer::GetRenderer())
3082 wxRichTextBuffer::GetRenderer()->DrawTextBullet(this, dc
, bulletAttr
, bulletRect
, bulletText
);
3087 // Draw the range for each line, one object at a time.
3089 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3092 wxRichTextLine
* line
= node
->GetData();
3093 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3095 int maxDescent
= line
->GetDescent();
3097 // Lines are specified relative to the paragraph
3099 wxPoint linePosition
= line
->GetPosition() + GetPosition();
3100 wxPoint objectPosition
= linePosition
;
3102 // Loop through objects until we get to the one within range
3103 wxRichTextObjectList::compatibility_iterator node2
= m_children
.GetFirst();
3106 wxRichTextObject
* child
= node2
->GetData();
3108 if (!child
->GetRange().IsOutside(lineRange
) && !lineRange
.IsOutside(range
))
3110 // Draw this part of the line at the correct position
3111 wxRichTextRange
objectRange(child
->GetRange());
3112 objectRange
.LimitTo(lineRange
);
3116 child
->GetRangeSize(objectRange
, objectSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, objectPosition
);
3118 // Use the child object's width, but the whole line's height
3119 wxRect
childRect(objectPosition
, wxSize(objectSize
.x
, line
->GetSize().y
));
3120 child
->Draw(dc
, objectRange
, selectionRange
, childRect
, maxDescent
, style
);
3122 objectPosition
.x
+= objectSize
.x
;
3124 else if (child
->GetRange().GetStart() > lineRange
.GetEnd())
3125 // Can break out of inner loop now since we've passed this line's range
3128 node2
= node2
->GetNext();
3131 node
= node
->GetNext();
3137 /// Lay the item out
3138 bool wxRichTextParagraph::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
3140 wxTextAttr attr
= GetCombinedAttributes();
3144 // Increase the size of the paragraph due to spacing
3145 int spaceBeforePara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingBefore());
3146 int spaceAfterPara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingAfter());
3147 int leftIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftIndent());
3148 int leftSubIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftSubIndent());
3149 int rightIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetRightIndent());
3151 int lineSpacing
= 0;
3153 // Let's assume line spacing of 10 is normal, 15 is 1.5, 20 is 2, etc.
3154 if (attr
.GetLineSpacing() != 10 && GetBuffer())
3156 wxFont
font(GetBuffer()->GetFontTable().FindFont(attr
));
3157 wxCheckSetFont(dc
, font
);
3158 lineSpacing
= (ConvertTenthsMMToPixels(dc
, dc
.GetCharHeight()) * attr
.GetLineSpacing())/10;
3161 // Available space for text on each line differs.
3162 int availableTextSpaceFirstLine
= rect
.GetWidth() - leftIndent
- rightIndent
;
3164 // Bullets start the text at the same position as subsequent lines
3165 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3166 availableTextSpaceFirstLine
-= leftSubIndent
;
3168 int availableTextSpaceSubsequentLines
= rect
.GetWidth() - leftIndent
- rightIndent
- leftSubIndent
;
3170 // Start position for each line relative to the paragraph
3171 int startPositionFirstLine
= leftIndent
;
3172 int startPositionSubsequentLines
= leftIndent
+ leftSubIndent
;
3174 // If we have a bullet in this paragraph, the start position for the first line's text
3175 // is actually leftIndent + leftSubIndent.
3176 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3177 startPositionFirstLine
= startPositionSubsequentLines
;
3179 long lastEndPos
= GetRange().GetStart()-1;
3180 long lastCompletedEndPos
= lastEndPos
;
3182 int currentWidth
= 0;
3183 SetPosition(rect
.GetPosition());
3185 wxPoint
currentPosition(0, spaceBeforePara
); // We will calculate lines relative to paragraph
3192 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3195 wxRichTextObject
* child
= node
->GetData();
3197 child
->SetCachedSize(wxDefaultSize
);
3198 child
->Layout(dc
, rect
, style
);
3200 node
= node
->GetNext();
3205 // We may need to go back to a previous child, in which case create the new line,
3206 // find the child corresponding to the start position of the string, and
3209 node
= m_children
.GetFirst();
3212 wxRichTextObject
* child
= node
->GetData();
3214 // If this is e.g. a composite text box, it will need to be laid out itself.
3215 // But if just a text fragment or image, for example, this will
3216 // do nothing. NB: won't we need to set the position after layout?
3217 // since for example if position is dependent on vertical line size, we
3218 // can't tell the position until the size is determined. So possibly introduce
3219 // another layout phase.
3221 // Available width depends on whether we're on the first or subsequent lines
3222 int availableSpaceForText
= (lineCount
== 0 ? availableTextSpaceFirstLine
: availableTextSpaceSubsequentLines
);
3224 currentPosition
.x
= (lineCount
== 0 ? startPositionFirstLine
: startPositionSubsequentLines
);
3226 // We may only be looking at part of a child, if we searched back for wrapping
3227 // and found a suitable point some way into the child. So get the size for the fragment
3230 long nextBreakPos
= GetFirstLineBreakPosition(lastEndPos
+1);
3231 long lastPosToUse
= child
->GetRange().GetEnd();
3232 bool lineBreakInThisObject
= (nextBreakPos
> -1 && nextBreakPos
<= child
->GetRange().GetEnd());
3234 if (lineBreakInThisObject
)
3235 lastPosToUse
= nextBreakPos
;
3238 int childDescent
= 0;
3240 if ((nextBreakPos
== -1) && (lastEndPos
== child
->GetRange().GetStart() - 1)) // i.e. we want to get the whole thing
3242 childSize
= child
->GetCachedSize();
3243 childDescent
= child
->GetDescent();
3246 GetRangeSize(wxRichTextRange(lastEndPos
+1, lastPosToUse
), childSize
, childDescent
, dc
, wxRICHTEXT_UNFORMATTED
, rect
.GetPosition());
3249 // 1) There was a line break BEFORE the natural break
3250 // 2) There was a line break AFTER the natural break
3251 // 3) The child still fits (carry on)
3253 if ((lineBreakInThisObject
&& (childSize
.x
+ currentWidth
<= availableSpaceForText
)) ||
3254 (childSize
.x
+ currentWidth
> availableSpaceForText
))
3256 long wrapPosition
= 0;
3258 // Find a place to wrap. This may walk back to previous children,
3259 // for example if a word spans several objects.
3260 if (!FindWrapPosition(wxRichTextRange(lastCompletedEndPos
+1, child
->GetRange().GetEnd()), dc
, availableSpaceForText
, wrapPosition
))
3262 // If the function failed, just cut it off at the end of this child.
3263 wrapPosition
= child
->GetRange().GetEnd();
3266 // FindWrapPosition can still return a value that will put us in an endless wrapping loop
3267 if (wrapPosition
<= lastCompletedEndPos
)
3268 wrapPosition
= wxMax(lastCompletedEndPos
+1,child
->GetRange().GetEnd());
3270 // wxLogDebug(wxT("Split at %ld"), wrapPosition);
3272 // Let's find the actual size of the current line now
3274 wxRichTextRange
actualRange(lastCompletedEndPos
+1, wrapPosition
);
3275 GetRangeSize(actualRange
, actualSize
, childDescent
, dc
, wxRICHTEXT_UNFORMATTED
);
3276 currentWidth
= actualSize
.x
;
3277 lineHeight
= wxMax(lineHeight
, actualSize
.y
);
3278 maxDescent
= wxMax(childDescent
, maxDescent
);
3281 wxRichTextLine
* line
= AllocateLine(lineCount
);
3283 // Set relative range so we won't have to change line ranges when paragraphs are moved
3284 line
->SetRange(wxRichTextRange(actualRange
.GetStart() - GetRange().GetStart(), actualRange
.GetEnd() - GetRange().GetStart()));
3285 line
->SetPosition(currentPosition
);
3286 line
->SetSize(wxSize(currentWidth
, lineHeight
));
3287 line
->SetDescent(maxDescent
);
3289 // Now move down a line. TODO: add margins, spacing
3290 currentPosition
.y
+= lineHeight
;
3291 currentPosition
.y
+= lineSpacing
;
3294 maxWidth
= wxMax(maxWidth
, currentWidth
);
3298 // TODO: account for zero-length objects, such as fields
3299 wxASSERT(wrapPosition
> lastCompletedEndPos
);
3301 lastEndPos
= wrapPosition
;
3302 lastCompletedEndPos
= lastEndPos
;
3306 // May need to set the node back to a previous one, due to searching back in wrapping
3307 wxRichTextObject
* childAfterWrapPosition
= FindObjectAtPosition(wrapPosition
+1);
3308 if (childAfterWrapPosition
)
3309 node
= m_children
.Find(childAfterWrapPosition
);
3311 node
= node
->GetNext();
3315 // We still fit, so don't add a line, and keep going
3316 currentWidth
+= childSize
.x
;
3317 lineHeight
= wxMax(lineHeight
, childSize
.y
);
3318 maxDescent
= wxMax(childDescent
, maxDescent
);
3320 maxWidth
= wxMax(maxWidth
, currentWidth
);
3321 lastEndPos
= child
->GetRange().GetEnd();
3323 node
= node
->GetNext();
3327 // Add the last line - it's the current pos -> last para pos
3328 // Substract -1 because the last position is always the end-paragraph position.
3329 if (lastCompletedEndPos
<= GetRange().GetEnd()-1)
3331 currentPosition
.x
= (lineCount
== 0 ? startPositionFirstLine
: startPositionSubsequentLines
);
3333 wxRichTextLine
* line
= AllocateLine(lineCount
);
3335 wxRichTextRange
actualRange(lastCompletedEndPos
+1, GetRange().GetEnd()-1);
3337 // Set relative range so we won't have to change line ranges when paragraphs are moved
3338 line
->SetRange(wxRichTextRange(actualRange
.GetStart() - GetRange().GetStart(), actualRange
.GetEnd() - GetRange().GetStart()));
3340 line
->SetPosition(currentPosition
);
3342 if (lineHeight
== 0 && GetBuffer())
3344 wxFont
font(GetBuffer()->GetFontTable().FindFont(attr
));
3345 wxCheckSetFont(dc
, font
);
3346 lineHeight
= dc
.GetCharHeight();
3348 if (maxDescent
== 0)
3351 dc
.GetTextExtent(wxT("X"), & w
, &h
, & maxDescent
);
3354 line
->SetSize(wxSize(currentWidth
, lineHeight
));
3355 line
->SetDescent(maxDescent
);
3356 currentPosition
.y
+= lineHeight
;
3357 currentPosition
.y
+= lineSpacing
;
3361 // Remove remaining unused line objects, if any
3362 ClearUnusedLines(lineCount
);
3364 // Apply styles to wrapped lines
3365 ApplyParagraphStyle(attr
, rect
);
3367 SetCachedSize(wxSize(maxWidth
, currentPosition
.y
+ spaceBeforePara
+ spaceAfterPara
));
3374 /// Apply paragraph styles, such as centering, to wrapped lines
3375 void wxRichTextParagraph::ApplyParagraphStyle(const wxTextAttr
& attr
, const wxRect
& rect
)
3377 if (!attr
.HasAlignment())
3380 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3383 wxRichTextLine
* line
= node
->GetData();
3385 wxPoint pos
= line
->GetPosition();
3386 wxSize size
= line
->GetSize();
3388 // centering, right-justification
3389 if (attr
.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_CENTRE
)
3391 pos
.x
= (rect
.GetWidth() - size
.x
)/2 + pos
.x
;
3392 line
->SetPosition(pos
);
3394 else if (attr
.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_RIGHT
)
3396 pos
.x
= pos
.x
+ rect
.GetWidth() - size
.x
;
3397 line
->SetPosition(pos
);
3400 node
= node
->GetNext();
3404 /// Insert text at the given position
3405 bool wxRichTextParagraph::InsertText(long pos
, const wxString
& text
)
3407 wxRichTextObject
* childToUse
= NULL
;
3408 wxRichTextObjectList::compatibility_iterator nodeToUse
= wxRichTextObjectList::compatibility_iterator();
3410 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3413 wxRichTextObject
* child
= node
->GetData();
3414 if (child
->GetRange().Contains(pos
) && child
->GetRange().GetLength() > 0)
3421 node
= node
->GetNext();
3426 wxRichTextPlainText
* textObject
= wxDynamicCast(childToUse
, wxRichTextPlainText
);
3429 int posInString
= pos
- textObject
->GetRange().GetStart();
3431 wxString newText
= textObject
->GetText().Mid(0, posInString
) +
3432 text
+ textObject
->GetText().Mid(posInString
);
3433 textObject
->SetText(newText
);
3435 int textLength
= text
.length();
3437 textObject
->SetRange(wxRichTextRange(textObject
->GetRange().GetStart(),
3438 textObject
->GetRange().GetEnd() + textLength
));
3440 // Increment the end range of subsequent fragments in this paragraph.
3441 // We'll set the paragraph range itself at a higher level.
3443 wxRichTextObjectList::compatibility_iterator node
= nodeToUse
->GetNext();
3446 wxRichTextObject
* child
= node
->GetData();
3447 child
->SetRange(wxRichTextRange(textObject
->GetRange().GetStart() + textLength
,
3448 textObject
->GetRange().GetEnd() + textLength
));
3450 node
= node
->GetNext();
3457 // TODO: if not a text object, insert at closest position, e.g. in front of it
3463 // Don't pass parent initially to suppress auto-setting of parent range.
3464 // We'll do that at a higher level.
3465 wxRichTextPlainText
* textObject
= new wxRichTextPlainText(text
, this);
3467 AppendChild(textObject
);
3474 void wxRichTextParagraph::Copy(const wxRichTextParagraph
& obj
)
3476 wxRichTextBox::Copy(obj
);
3479 /// Clear the cached lines
3480 void wxRichTextParagraph::ClearLines()
3482 WX_CLEAR_LIST(wxRichTextLineList
, m_cachedLines
);
3485 /// Get/set the object size for the given range. Returns false if the range
3486 /// is invalid for this object.
3487 bool wxRichTextParagraph::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
) const
3489 if (!range
.IsWithin(GetRange()))
3492 if (flags
& wxRICHTEXT_UNFORMATTED
)
3494 // Just use unformatted data, assume no line breaks
3495 // TODO: take into account line breaks
3499 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3502 wxRichTextObject
* child
= node
->GetData();
3503 if (!child
->GetRange().IsOutside(range
))
3507 wxRichTextRange rangeToUse
= range
;
3508 rangeToUse
.LimitTo(child
->GetRange());
3509 int childDescent
= 0;
3511 if (child
->GetRangeSize(rangeToUse
, childSize
, childDescent
, dc
, flags
, wxPoint(position
.x
+ sz
.x
, position
.y
)))
3513 sz
.y
= wxMax(sz
.y
, childSize
.y
);
3514 sz
.x
+= childSize
.x
;
3515 descent
= wxMax(descent
, childDescent
);
3519 node
= node
->GetNext();
3525 // Use formatted data, with line breaks
3528 // We're going to loop through each line, and then for each line,
3529 // call GetRangeSize for the fragment that comprises that line.
3530 // Only we have to do that multiple times within the line, because
3531 // the line may be broken into pieces. For now ignore line break commands
3532 // (so we can assume that getting the unformatted size for a fragment
3533 // within a line is the actual size)
3535 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3538 wxRichTextLine
* line
= node
->GetData();
3539 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3540 if (!lineRange
.IsOutside(range
))
3544 wxRichTextObjectList::compatibility_iterator node2
= m_children
.GetFirst();
3547 wxRichTextObject
* child
= node2
->GetData();
3549 if (!child
->GetRange().IsOutside(lineRange
))
3551 wxRichTextRange rangeToUse
= lineRange
;
3552 rangeToUse
.LimitTo(child
->GetRange());
3555 int childDescent
= 0;
3556 if (child
->GetRangeSize(rangeToUse
, childSize
, childDescent
, dc
, flags
, wxPoint(position
.x
+ sz
.x
, position
.y
)))
3558 lineSize
.y
= wxMax(lineSize
.y
, childSize
.y
);
3559 lineSize
.x
+= childSize
.x
;
3561 descent
= wxMax(descent
, childDescent
);
3564 node2
= node2
->GetNext();
3567 // Increase size by a line (TODO: paragraph spacing)
3569 sz
.x
= wxMax(sz
.x
, lineSize
.x
);
3571 node
= node
->GetNext();
3578 /// Finds the absolute position and row height for the given character position
3579 bool wxRichTextParagraph::FindPosition(wxDC
& dc
, long index
, wxPoint
& pt
, int* height
, bool forceLineStart
)
3583 wxRichTextLine
* line
= ((wxRichTextParagraphLayoutBox
*)GetParent())->GetLineAtPosition(0);
3585 *height
= line
->GetSize().y
;
3587 *height
= dc
.GetCharHeight();
3589 // -1 means 'the start of the buffer'.
3592 pt
= pt
+ line
->GetPosition();
3597 // The final position in a paragraph is taken to mean the position
3598 // at the start of the next paragraph.
3599 if (index
== GetRange().GetEnd())
3601 wxRichTextParagraphLayoutBox
* parent
= wxDynamicCast(GetParent(), wxRichTextParagraphLayoutBox
);
3602 wxASSERT( parent
!= NULL
);
3604 // Find the height at the next paragraph, if any
3605 wxRichTextLine
* line
= parent
->GetLineAtPosition(index
+ 1);
3608 *height
= line
->GetSize().y
;
3609 pt
= line
->GetAbsolutePosition();
3613 *height
= dc
.GetCharHeight();
3614 int indent
= ConvertTenthsMMToPixels(dc
, m_attributes
.GetLeftIndent());
3615 pt
= wxPoint(indent
, GetCachedSize().y
);
3621 if (index
< GetRange().GetStart() || index
> GetRange().GetEnd())
3624 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3627 wxRichTextLine
* line
= node
->GetData();
3628 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3629 if (index
>= lineRange
.GetStart() && index
<= lineRange
.GetEnd())
3631 // If this is the last point in the line, and we're forcing the
3632 // returned value to be the start of the next line, do the required
3634 if (index
== lineRange
.GetEnd() && forceLineStart
)
3636 if (node
->GetNext())
3638 wxRichTextLine
* nextLine
= node
->GetNext()->GetData();
3639 *height
= nextLine
->GetSize().y
;
3640 pt
= nextLine
->GetAbsolutePosition();
3645 pt
.y
= line
->GetPosition().y
+ GetPosition().y
;
3647 wxRichTextRange
r(lineRange
.GetStart(), index
);
3651 // We find the size of the line up to this point,
3652 // then we can add this size to the line start position and
3653 // paragraph start position to find the actual position.
3655 if (GetRangeSize(r
, rangeSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, line
->GetPosition()+ GetPosition()))
3657 pt
.x
= line
->GetPosition().x
+ GetPosition().x
+ rangeSize
.x
;
3658 *height
= line
->GetSize().y
;
3665 node
= node
->GetNext();
3671 /// Hit-testing: returns a flag indicating hit test details, plus
3672 /// information about position
3673 int wxRichTextParagraph::HitTest(wxDC
& dc
, const wxPoint
& pt
, long& textPosition
)
3675 wxPoint paraPos
= GetPosition();
3677 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3680 wxRichTextLine
* line
= node
->GetData();
3681 wxPoint linePos
= paraPos
+ line
->GetPosition();
3682 wxSize lineSize
= line
->GetSize();
3683 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3685 if (pt
.y
>= linePos
.y
&& pt
.y
<= linePos
.y
+ lineSize
.y
)
3687 if (pt
.x
< linePos
.x
)
3689 textPosition
= lineRange
.GetStart();
3690 return wxRICHTEXT_HITTEST_BEFORE
|wxRICHTEXT_HITTEST_OUTSIDE
;
3692 else if (pt
.x
>= (linePos
.x
+ lineSize
.x
))
3694 textPosition
= lineRange
.GetEnd();
3695 return wxRICHTEXT_HITTEST_AFTER
|wxRICHTEXT_HITTEST_OUTSIDE
;
3700 int lastX
= linePos
.x
;
3701 for (i
= lineRange
.GetStart(); i
<= lineRange
.GetEnd(); i
++)
3706 wxRichTextRange
rangeToUse(lineRange
.GetStart(), i
);
3708 GetRangeSize(rangeToUse
, childSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, linePos
);
3710 int nextX
= childSize
.x
+ linePos
.x
;
3712 if (pt
.x
>= lastX
&& pt
.x
<= nextX
)
3716 // So now we know it's between i-1 and i.
3717 // Let's see if we can be more precise about
3718 // which side of the position it's on.
3720 int midPoint
= (nextX
- lastX
)/2 + lastX
;
3721 if (pt
.x
>= midPoint
)
3722 return wxRICHTEXT_HITTEST_AFTER
;
3724 return wxRICHTEXT_HITTEST_BEFORE
;
3734 node
= node
->GetNext();
3737 return wxRICHTEXT_HITTEST_NONE
;
3740 /// Split an object at this position if necessary, and return
3741 /// the previous object, or NULL if inserting at beginning.
3742 wxRichTextObject
* wxRichTextParagraph::SplitAt(long pos
, wxRichTextObject
** previousObject
)
3744 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3747 wxRichTextObject
* child
= node
->GetData();
3749 if (pos
== child
->GetRange().GetStart())
3753 if (node
->GetPrevious())
3754 *previousObject
= node
->GetPrevious()->GetData();
3756 *previousObject
= NULL
;
3762 if (child
->GetRange().Contains(pos
))
3764 // This should create a new object, transferring part of
3765 // the content to the old object and the rest to the new object.
3766 wxRichTextObject
* newObject
= child
->DoSplit(pos
);
3768 // If we couldn't split this object, just insert in front of it.
3771 // Maybe this is an empty string, try the next one
3776 // Insert the new object after 'child'
3777 if (node
->GetNext())
3778 m_children
.Insert(node
->GetNext(), newObject
);
3780 m_children
.Append(newObject
);
3781 newObject
->SetParent(this);
3784 *previousObject
= child
;
3790 node
= node
->GetNext();
3793 *previousObject
= NULL
;
3797 /// Move content to a list from obj on
3798 void wxRichTextParagraph::MoveToList(wxRichTextObject
* obj
, wxList
& list
)
3800 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(obj
);
3803 wxRichTextObject
* child
= node
->GetData();
3806 wxRichTextObjectList::compatibility_iterator oldNode
= node
;
3808 node
= node
->GetNext();
3810 m_children
.DeleteNode(oldNode
);
3814 /// Add content back from list
3815 void wxRichTextParagraph::MoveFromList(wxList
& list
)
3817 for (wxList::compatibility_iterator node
= list
.GetFirst(); node
; node
= node
->GetNext())
3819 AppendChild((wxRichTextObject
*) node
->GetData());
3824 void wxRichTextParagraph::CalculateRange(long start
, long& end
)
3826 wxRichTextCompositeObject::CalculateRange(start
, end
);
3828 // Add one for end of paragraph
3831 m_range
.SetRange(start
, end
);
3834 /// Find the object at the given position
3835 wxRichTextObject
* wxRichTextParagraph::FindObjectAtPosition(long position
)
3837 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3840 wxRichTextObject
* obj
= node
->GetData();
3841 if (obj
->GetRange().Contains(position
))
3844 node
= node
->GetNext();
3849 /// Get the plain text searching from the start or end of the range.
3850 /// The resulting string may be shorter than the range given.
3851 bool wxRichTextParagraph::GetContiguousPlainText(wxString
& text
, const wxRichTextRange
& range
, bool fromStart
)
3853 text
= wxEmptyString
;
3857 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3860 wxRichTextObject
* obj
= node
->GetData();
3861 if (!obj
->GetRange().IsOutside(range
))
3863 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
3866 text
+= textObj
->GetTextForRange(range
);
3872 node
= node
->GetNext();
3877 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetLast();
3880 wxRichTextObject
* obj
= node
->GetData();
3881 if (!obj
->GetRange().IsOutside(range
))
3883 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
3886 text
= textObj
->GetTextForRange(range
) + text
;
3892 node
= node
->GetPrevious();
3899 /// Find a suitable wrap position.
3900 bool wxRichTextParagraph::FindWrapPosition(const wxRichTextRange
& range
, wxDC
& dc
, int availableSpace
, long& wrapPosition
)
3902 // Find the first position where the line exceeds the available space.
3904 long breakPosition
= range
.GetEnd();
3906 // Binary chop for speed
3907 long minPos
= range
.GetStart();
3908 long maxPos
= range
.GetEnd();
3911 if (minPos
== maxPos
)
3914 GetRangeSize(wxRichTextRange(range
.GetStart(), minPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
3916 if (sz
.x
> availableSpace
)
3917 breakPosition
= minPos
- 1;
3920 else if ((maxPos
- minPos
) == 1)
3923 GetRangeSize(wxRichTextRange(range
.GetStart(), minPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
3925 if (sz
.x
> availableSpace
)
3926 breakPosition
= minPos
- 1;
3929 GetRangeSize(wxRichTextRange(range
.GetStart(), maxPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
3930 if (sz
.x
> availableSpace
)
3931 breakPosition
= maxPos
-1;
3937 long nextPos
= minPos
+ ((maxPos
- minPos
) / 2);
3940 GetRangeSize(wxRichTextRange(range
.GetStart(), nextPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
3942 if (sz
.x
> availableSpace
)
3953 // Now we know the last position on the line.
3954 // Let's try to find a word break.
3957 if (GetContiguousPlainText(plainText
, wxRichTextRange(range
.GetStart(), breakPosition
), false))
3959 int newLinePos
= plainText
.Find(wxRichTextLineBreakChar
);
3960 if (newLinePos
!= wxNOT_FOUND
)
3962 breakPosition
= wxMax(0, range
.GetStart() + newLinePos
);
3966 int spacePos
= plainText
.Find(wxT(' '), true);
3967 int tabPos
= plainText
.Find(wxT('\t'), true);
3968 int pos
= wxMax(spacePos
, tabPos
);
3969 if (pos
!= wxNOT_FOUND
)
3971 int positionsFromEndOfString
= plainText
.length() - pos
- 1;
3972 breakPosition
= breakPosition
- positionsFromEndOfString
;
3977 wrapPosition
= breakPosition
;
3982 /// Get the bullet text for this paragraph.
3983 wxString
wxRichTextParagraph::GetBulletText()
3985 if (GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE
||
3986 (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP
))
3987 return wxEmptyString
;
3989 int number
= GetAttributes().GetBulletNumber();
3992 if ((GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ARABIC
) || (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
))
3994 text
.Printf(wxT("%d"), number
);
3996 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER
)
3998 // TODO: Unicode, and also check if number > 26
3999 text
.Printf(wxT("%c"), (wxChar
) (number
+64));
4001 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER
)
4003 // TODO: Unicode, and also check if number > 26
4004 text
.Printf(wxT("%c"), (wxChar
) (number
+96));
4006 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER
)
4008 text
= wxRichTextDecimalToRoman(number
);
4010 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER
)
4012 text
= wxRichTextDecimalToRoman(number
);
4015 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL
)
4017 text
= GetAttributes().GetBulletText();
4020 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
)
4022 // The outline style relies on the text being computed statically,
4023 // since it depends on other levels points (e.g. 1.2.1.1). So normally the bullet text
4024 // should be stored in the attributes; if not, just use the number for this
4025 // level, as previously computed.
4026 if (!GetAttributes().GetBulletText().IsEmpty())
4027 text
= GetAttributes().GetBulletText();
4030 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PARENTHESES
)
4032 text
= wxT("(") + text
+ wxT(")");
4034 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS
)
4036 text
= text
+ wxT(")");
4039 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PERIOD
)
4047 /// Allocate or reuse a line object
4048 wxRichTextLine
* wxRichTextParagraph::AllocateLine(int pos
)
4050 if (pos
< (int) m_cachedLines
.GetCount())
4052 wxRichTextLine
* line
= m_cachedLines
.Item(pos
)->GetData();
4058 wxRichTextLine
* line
= new wxRichTextLine(this);
4059 m_cachedLines
.Append(line
);
4064 /// Clear remaining unused line objects, if any
4065 bool wxRichTextParagraph::ClearUnusedLines(int lineCount
)
4067 int cachedLineCount
= m_cachedLines
.GetCount();
4068 if ((int) cachedLineCount
> lineCount
)
4070 for (int i
= 0; i
< (int) (cachedLineCount
- lineCount
); i
++)
4072 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetLast();
4073 wxRichTextLine
* line
= node
->GetData();
4074 m_cachedLines
.Erase(node
);
4081 /// Get combined attributes of the base style, paragraph style and character style. We use this to dynamically
4082 /// retrieve the actual style.
4083 wxTextAttr
wxRichTextParagraph::GetCombinedAttributes(const wxTextAttr
& contentStyle
) const
4086 wxRichTextBuffer
* buf
= wxDynamicCast(GetParent(), wxRichTextBuffer
);
4089 attr
= buf
->GetBasicStyle();
4090 wxRichTextApplyStyle(attr
, GetAttributes());
4093 attr
= GetAttributes();
4095 wxRichTextApplyStyle(attr
, contentStyle
);
4099 /// Get combined attributes of the base style and paragraph style.
4100 wxTextAttr
wxRichTextParagraph::GetCombinedAttributes() const
4103 wxRichTextBuffer
* buf
= wxDynamicCast(GetParent(), wxRichTextBuffer
);
4106 attr
= buf
->GetBasicStyle();
4107 wxRichTextApplyStyle(attr
, GetAttributes());
4110 attr
= GetAttributes();
4115 /// Create default tabstop array
4116 void wxRichTextParagraph::InitDefaultTabs()
4118 // create a default tab list at 10 mm each.
4119 for (int i
= 0; i
< 20; ++i
)
4121 sm_defaultTabs
.Add(i
*100);
4125 /// Clear default tabstop array
4126 void wxRichTextParagraph::ClearDefaultTabs()
4128 sm_defaultTabs
.Clear();
4131 /// Get the first position from pos that has a line break character.
4132 long wxRichTextParagraph::GetFirstLineBreakPosition(long pos
)
4134 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
4137 wxRichTextObject
* obj
= node
->GetData();
4138 if (pos
>= obj
->GetRange().GetStart() && pos
<= obj
->GetRange().GetEnd())
4140 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
4143 long breakPos
= textObj
->GetFirstLineBreakPosition(pos
);
4148 node
= node
->GetNext();
4155 * This object represents a line in a paragraph, and stores
4156 * offsets from the start of the paragraph representing the
4157 * start and end positions of the line.
4160 wxRichTextLine::wxRichTextLine(wxRichTextParagraph
* parent
)
4166 void wxRichTextLine::Init(wxRichTextParagraph
* parent
)
4169 m_range
.SetRange(-1, -1);
4170 m_pos
= wxPoint(0, 0);
4171 m_size
= wxSize(0, 0);
4176 void wxRichTextLine::Copy(const wxRichTextLine
& obj
)
4178 m_range
= obj
.m_range
;
4181 /// Get the absolute object position
4182 wxPoint
wxRichTextLine::GetAbsolutePosition() const
4184 return m_parent
->GetPosition() + m_pos
;
4187 /// Get the absolute range
4188 wxRichTextRange
wxRichTextLine::GetAbsoluteRange() const
4190 wxRichTextRange
range(m_range
.GetStart() + m_parent
->GetRange().GetStart(), 0);
4191 range
.SetEnd(range
.GetStart() + m_range
.GetLength()-1);
4196 * wxRichTextPlainText
4197 * This object represents a single piece of text.
4200 IMPLEMENT_DYNAMIC_CLASS(wxRichTextPlainText
, wxRichTextObject
)
4202 wxRichTextPlainText::wxRichTextPlainText(const wxString
& text
, wxRichTextObject
* parent
, wxTextAttr
* style
):
4203 wxRichTextObject(parent
)
4206 SetAttributes(*style
);
4211 #define USE_KERNING_FIX 1
4213 // If insufficient tabs are defined, this is the tab width used
4214 #define WIDTH_FOR_DEFAULT_TABS 50
4217 bool wxRichTextPlainText::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int descent
, int WXUNUSED(style
))
4219 wxRichTextParagraph
* para
= wxDynamicCast(GetParent(), wxRichTextParagraph
);
4220 wxASSERT (para
!= NULL
);
4222 wxTextAttr
textAttr(para
? para
->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4224 int offset
= GetRange().GetStart();
4226 // Replace line break characters with spaces
4227 wxString str
= m_text
;
4228 wxString toRemove
= wxRichTextLineBreakChar
;
4229 str
.Replace(toRemove
, wxT(" "));
4231 long len
= range
.GetLength();
4232 wxString stringChunk
= str
.Mid(range
.GetStart() - offset
, (size_t) len
);
4233 if (textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
4234 stringChunk
.MakeUpper();
4236 int charHeight
= dc
.GetCharHeight();
4239 int y
= rect
.y
+ (rect
.height
- charHeight
- (descent
- m_descent
));
4241 // Test for the optimized situations where all is selected, or none
4244 wxFont
font(GetBuffer()->GetFontTable().FindFont(textAttr
));
4245 wxCheckSetFont(dc
, font
);
4247 // (a) All selected.
4248 if (selectionRange
.GetStart() <= range
.GetStart() && selectionRange
.GetEnd() >= range
.GetEnd())
4250 DrawTabbedString(dc
, textAttr
, rect
, stringChunk
, x
, y
, true);
4252 // (b) None selected.
4253 else if (selectionRange
.GetEnd() < range
.GetStart() || selectionRange
.GetStart() > range
.GetEnd())
4255 // Draw all unselected
4256 DrawTabbedString(dc
, textAttr
, rect
, stringChunk
, x
, y
, false);
4260 // (c) Part selected, part not
4261 // Let's draw unselected chunk, selected chunk, then unselected chunk.
4263 dc
.SetBackgroundMode(wxTRANSPARENT
);
4265 // 1. Initial unselected chunk, if any, up until start of selection.
4266 if (selectionRange
.GetStart() > range
.GetStart() && selectionRange
.GetStart() <= range
.GetEnd())
4268 int r1
= range
.GetStart();
4269 int s1
= selectionRange
.GetStart()-1;
4270 int fragmentLen
= s1
- r1
+ 1;
4271 if (fragmentLen
< 0)
4272 wxLogDebug(wxT("Mid(%d, %d"), (int)(r1
- offset
), (int)fragmentLen
);
4273 wxString stringFragment
= str
.Mid(r1
- offset
, fragmentLen
);
4275 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, false);
4278 if (stringChunk
.Find(wxT("\t")) == wxNOT_FOUND
)
4280 // Compensate for kerning difference
4281 wxString
stringFragment2(str
.Mid(r1
- offset
, fragmentLen
+1));
4282 wxString
stringFragment3(str
.Mid(r1
- offset
+ fragmentLen
, 1));
4284 wxCoord w1
, h1
, w2
, h2
, w3
, h3
;
4285 dc
.GetTextExtent(stringFragment
, & w1
, & h1
);
4286 dc
.GetTextExtent(stringFragment2
, & w2
, & h2
);
4287 dc
.GetTextExtent(stringFragment3
, & w3
, & h3
);
4289 int kerningDiff
= (w1
+ w3
) - w2
;
4290 x
= x
- kerningDiff
;
4295 // 2. Selected chunk, if any.
4296 if (selectionRange
.GetEnd() >= range
.GetStart())
4298 int s1
= wxMax(selectionRange
.GetStart(), range
.GetStart());
4299 int s2
= wxMin(selectionRange
.GetEnd(), range
.GetEnd());
4301 int fragmentLen
= s2
- s1
+ 1;
4302 if (fragmentLen
< 0)
4303 wxLogDebug(wxT("Mid(%d, %d"), (int)(s1
- offset
), (int)fragmentLen
);
4304 wxString stringFragment
= str
.Mid(s1
- offset
, fragmentLen
);
4306 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, true);
4309 if (stringChunk
.Find(wxT("\t")) == wxNOT_FOUND
)
4311 // Compensate for kerning difference
4312 wxString
stringFragment2(str
.Mid(s1
- offset
, fragmentLen
+1));
4313 wxString
stringFragment3(str
.Mid(s1
- offset
+ fragmentLen
, 1));
4315 wxCoord w1
, h1
, w2
, h2
, w3
, h3
;
4316 dc
.GetTextExtent(stringFragment
, & w1
, & h1
);
4317 dc
.GetTextExtent(stringFragment2
, & w2
, & h2
);
4318 dc
.GetTextExtent(stringFragment3
, & w3
, & h3
);
4320 int kerningDiff
= (w1
+ w3
) - w2
;
4321 x
= x
- kerningDiff
;
4326 // 3. Remaining unselected chunk, if any
4327 if (selectionRange
.GetEnd() < range
.GetEnd())
4329 int s2
= wxMin(selectionRange
.GetEnd()+1, range
.GetEnd());
4330 int r2
= range
.GetEnd();
4332 int fragmentLen
= r2
- s2
+ 1;
4333 if (fragmentLen
< 0)
4334 wxLogDebug(wxT("Mid(%d, %d"), (int)(s2
- offset
), (int)fragmentLen
);
4335 wxString stringFragment
= str
.Mid(s2
- offset
, fragmentLen
);
4337 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, false);
4344 bool wxRichTextPlainText::DrawTabbedString(wxDC
& dc
, const wxTextAttr
& attr
, const wxRect
& rect
,wxString
& str
, wxCoord
& x
, wxCoord
& y
, bool selected
)
4346 bool hasTabs
= (str
.Find(wxT('\t')) != wxNOT_FOUND
);
4348 wxArrayInt tabArray
;
4352 if (attr
.GetTabs().IsEmpty())
4353 tabArray
= wxRichTextParagraph::GetDefaultTabs();
4355 tabArray
= attr
.GetTabs();
4356 tabCount
= tabArray
.GetCount();
4358 for (int i
= 0; i
< tabCount
; ++i
)
4360 int pos
= tabArray
[i
];
4361 pos
= ConvertTenthsMMToPixels(dc
, pos
);
4368 int nextTabPos
= -1;
4374 wxColour
highlightColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT
));
4375 wxColour
highlightTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT
));
4377 wxCheckSetBrush(dc
, wxBrush(highlightColour
));
4378 wxCheckSetPen(dc
, wxPen(highlightColour
));
4379 dc
.SetTextForeground(highlightTextColour
);
4380 dc
.SetBackgroundMode(wxTRANSPARENT
);
4384 dc
.SetTextForeground(attr
.GetTextColour());
4386 if (attr
.HasFlag(wxTEXT_ATTR_BACKGROUND_COLOUR
) && attr
.GetBackgroundColour().IsOk())
4388 dc
.SetBackgroundMode(wxSOLID
);
4389 dc
.SetTextBackground(attr
.GetBackgroundColour());
4392 dc
.SetBackgroundMode(wxTRANSPARENT
);
4397 // the string has a tab
4398 // break up the string at the Tab
4399 wxString stringChunk
= str
.BeforeFirst(wxT('\t'));
4400 str
= str
.AfterFirst(wxT('\t'));
4401 dc
.GetTextExtent(stringChunk
, & w
, & h
);
4403 bool not_found
= true;
4404 for (int i
= 0; i
< tabCount
&& not_found
; ++i
)
4406 nextTabPos
= tabArray
.Item(i
);
4408 // Find the next tab position.
4409 // Even if we're at the end of the tab array, we must still draw the chunk.
4411 if (nextTabPos
> tabPos
|| (i
== (tabCount
- 1)))
4413 if (nextTabPos
<= tabPos
)
4415 int defaultTabWidth
= ConvertTenthsMMToPixels(dc
, WIDTH_FOR_DEFAULT_TABS
);
4416 nextTabPos
= tabPos
+ defaultTabWidth
;
4423 wxRect
selRect(x
, rect
.y
, w
, rect
.GetHeight());
4424 dc
.DrawRectangle(selRect
);
4426 dc
.DrawText(stringChunk
, x
, y
);
4428 if (attr
.HasTextEffects() && (attr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH
))
4430 wxPen oldPen
= dc
.GetPen();
4431 wxCheckSetPen(dc
, wxPen(attr
.GetTextColour(), 1));
4432 dc
.DrawLine(x
, (int) (y
+(h
/2)+0.5), x
+w
, (int) (y
+(h
/2)+0.5));
4433 wxCheckSetPen(dc
, oldPen
);
4439 hasTabs
= (str
.Find(wxT('\t')) != wxNOT_FOUND
);
4444 dc
.GetTextExtent(str
, & w
, & h
);
4447 wxRect
selRect(x
, rect
.y
, w
, rect
.GetHeight());
4448 dc
.DrawRectangle(selRect
);
4450 dc
.DrawText(str
, x
, y
);
4452 if (attr
.HasTextEffects() && (attr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH
))
4454 wxPen oldPen
= dc
.GetPen();
4455 wxCheckSetPen(dc
, wxPen(attr
.GetTextColour(), 1));
4456 dc
.DrawLine(x
, (int) (y
+(h
/2)+0.5), x
+w
, (int) (y
+(h
/2)+0.5));
4457 wxCheckSetPen(dc
, oldPen
);
4466 /// Lay the item out
4467 bool wxRichTextPlainText::Layout(wxDC
& dc
, const wxRect
& WXUNUSED(rect
), int WXUNUSED(style
))
4469 // Only lay out if we haven't already cached the size
4471 GetRangeSize(GetRange(), m_size
, m_descent
, dc
, 0, wxPoint(0, 0));
4477 void wxRichTextPlainText::Copy(const wxRichTextPlainText
& obj
)
4479 wxRichTextObject::Copy(obj
);
4481 m_text
= obj
.m_text
;
4484 /// Get/set the object size for the given range. Returns false if the range
4485 /// is invalid for this object.
4486 bool wxRichTextPlainText::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int WXUNUSED(flags
), wxPoint position
) const
4488 if (!range
.IsWithin(GetRange()))
4491 wxRichTextParagraph
* para
= wxDynamicCast(GetParent(), wxRichTextParagraph
);
4492 wxASSERT (para
!= NULL
);
4494 wxTextAttr
textAttr(para
? para
->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4496 // Always assume unformatted text, since at this level we have no knowledge
4497 // of line breaks - and we don't need it, since we'll calculate size within
4498 // formatted text by doing it in chunks according to the line ranges
4500 wxFont
font(GetBuffer()->GetFontTable().FindFont(textAttr
));
4501 wxCheckSetFont(dc
, font
);
4503 int startPos
= range
.GetStart() - GetRange().GetStart();
4504 long len
= range
.GetLength();
4506 wxString
str(m_text
);
4507 wxString toReplace
= wxRichTextLineBreakChar
;
4508 str
.Replace(toReplace
, wxT(" "));
4510 wxString stringChunk
= str
.Mid(startPos
, (size_t) len
);
4512 if (textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
4513 stringChunk
.MakeUpper();
4517 if (stringChunk
.Find(wxT('\t')) != wxNOT_FOUND
)
4519 // the string has a tab
4520 wxArrayInt tabArray
;
4521 if (textAttr
.GetTabs().IsEmpty())
4522 tabArray
= wxRichTextParagraph::GetDefaultTabs();
4524 tabArray
= textAttr
.GetTabs();
4526 int tabCount
= tabArray
.GetCount();
4528 for (int i
= 0; i
< tabCount
; ++i
)
4530 int pos
= tabArray
[i
];
4531 pos
= ((wxRichTextPlainText
*) this)->ConvertTenthsMMToPixels(dc
, pos
);
4535 int nextTabPos
= -1;
4537 while (stringChunk
.Find(wxT('\t')) >= 0)
4539 // the string has a tab
4540 // break up the string at the Tab
4541 wxString stringFragment
= stringChunk
.BeforeFirst(wxT('\t'));
4542 stringChunk
= stringChunk
.AfterFirst(wxT('\t'));
4543 dc
.GetTextExtent(stringFragment
, & w
, & h
);
4545 int absoluteWidth
= width
+ position
.x
;
4547 bool notFound
= true;
4548 for (int i
= 0; i
< tabCount
&& notFound
; ++i
)
4550 nextTabPos
= tabArray
.Item(i
);
4552 // Find the next tab position.
4553 // Even if we're at the end of the tab array, we must still process the chunk.
4555 if (nextTabPos
> absoluteWidth
|| (i
== (tabCount
- 1)))
4557 if (nextTabPos
<= absoluteWidth
)
4559 int defaultTabWidth
= ((wxRichTextPlainText
*) this)->ConvertTenthsMMToPixels(dc
, WIDTH_FOR_DEFAULT_TABS
);
4560 nextTabPos
= absoluteWidth
+ defaultTabWidth
;
4564 width
= nextTabPos
- position
.x
;
4569 dc
.GetTextExtent(stringChunk
, & w
, & h
, & descent
);
4571 size
= wxSize(width
, dc
.GetCharHeight());
4576 /// Do a split, returning an object containing the second part, and setting
4577 /// the first part in 'this'.
4578 wxRichTextObject
* wxRichTextPlainText::DoSplit(long pos
)
4580 long index
= pos
- GetRange().GetStart();
4582 if (index
< 0 || index
>= (int) m_text
.length())
4585 wxString firstPart
= m_text
.Mid(0, index
);
4586 wxString secondPart
= m_text
.Mid(index
);
4590 wxRichTextPlainText
* newObject
= new wxRichTextPlainText(secondPart
);
4591 newObject
->SetAttributes(GetAttributes());
4593 newObject
->SetRange(wxRichTextRange(pos
, GetRange().GetEnd()));
4594 GetRange().SetEnd(pos
-1);
4600 void wxRichTextPlainText::CalculateRange(long start
, long& end
)
4602 end
= start
+ m_text
.length() - 1;
4603 m_range
.SetRange(start
, end
);
4607 bool wxRichTextPlainText::DeleteRange(const wxRichTextRange
& range
)
4609 wxRichTextRange r
= range
;
4611 r
.LimitTo(GetRange());
4613 if (r
.GetStart() == GetRange().GetStart() && r
.GetEnd() == GetRange().GetEnd())
4619 long startIndex
= r
.GetStart() - GetRange().GetStart();
4620 long len
= r
.GetLength();
4622 m_text
= m_text
.Mid(0, startIndex
) + m_text
.Mid(startIndex
+len
);
4626 /// Get text for the given range.
4627 wxString
wxRichTextPlainText::GetTextForRange(const wxRichTextRange
& range
) const
4629 wxRichTextRange r
= range
;
4631 r
.LimitTo(GetRange());
4633 long startIndex
= r
.GetStart() - GetRange().GetStart();
4634 long len
= r
.GetLength();
4636 return m_text
.Mid(startIndex
, len
);
4639 /// Returns true if this object can merge itself with the given one.
4640 bool wxRichTextPlainText::CanMerge(wxRichTextObject
* object
) const
4642 return object
->GetClassInfo() == CLASSINFO(wxRichTextPlainText
) &&
4643 (m_text
.empty() || wxTextAttrEq(GetAttributes(), object
->GetAttributes()));
4646 /// Returns true if this object merged itself with the given one.
4647 /// The calling code will then delete the given object.
4648 bool wxRichTextPlainText::Merge(wxRichTextObject
* object
)
4650 wxRichTextPlainText
* textObject
= wxDynamicCast(object
, wxRichTextPlainText
);
4651 wxASSERT( textObject
!= NULL
);
4655 m_text
+= textObject
->GetText();
4662 /// Dump to output stream for debugging
4663 void wxRichTextPlainText::Dump(wxTextOutputStream
& stream
)
4665 wxRichTextObject::Dump(stream
);
4666 stream
<< m_text
<< wxT("\n");
4669 /// Get the first position from pos that has a line break character.
4670 long wxRichTextPlainText::GetFirstLineBreakPosition(long pos
)
4673 int len
= m_text
.length();
4674 int startPos
= pos
- m_range
.GetStart();
4675 for (i
= startPos
; i
< len
; i
++)
4677 wxChar ch
= m_text
[i
];
4678 if (ch
== wxRichTextLineBreakChar
)
4680 return i
+ m_range
.GetStart();
4688 * This is a kind of box, used to represent the whole buffer
4691 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBuffer
, wxRichTextParagraphLayoutBox
)
4693 wxList
wxRichTextBuffer::sm_handlers
;
4694 wxRichTextRenderer
* wxRichTextBuffer::sm_renderer
= NULL
;
4695 int wxRichTextBuffer::sm_bulletRightMargin
= 20;
4696 float wxRichTextBuffer::sm_bulletProportion
= (float) 0.3;
4699 void wxRichTextBuffer::Init()
4701 m_commandProcessor
= new wxCommandProcessor
;
4702 m_styleSheet
= NULL
;
4704 m_batchedCommandDepth
= 0;
4705 m_batchedCommand
= NULL
;
4712 wxRichTextBuffer::~wxRichTextBuffer()
4714 delete m_commandProcessor
;
4715 delete m_batchedCommand
;
4718 ClearEventHandlers();
4721 void wxRichTextBuffer::ResetAndClearCommands()
4725 GetCommandProcessor()->ClearCommands();
4728 Invalidate(wxRICHTEXT_ALL
);
4731 void wxRichTextBuffer::Copy(const wxRichTextBuffer
& obj
)
4733 wxRichTextParagraphLayoutBox::Copy(obj
);
4735 m_styleSheet
= obj
.m_styleSheet
;
4736 m_modified
= obj
.m_modified
;
4737 m_batchedCommandDepth
= obj
.m_batchedCommandDepth
;
4738 m_batchedCommand
= obj
.m_batchedCommand
;
4739 m_suppressUndo
= obj
.m_suppressUndo
;
4742 /// Push style sheet to top of stack
4743 bool wxRichTextBuffer::PushStyleSheet(wxRichTextStyleSheet
* styleSheet
)
4746 styleSheet
->InsertSheet(m_styleSheet
);
4748 SetStyleSheet(styleSheet
);
4753 /// Pop style sheet from top of stack
4754 wxRichTextStyleSheet
* wxRichTextBuffer::PopStyleSheet()
4758 wxRichTextStyleSheet
* oldSheet
= m_styleSheet
;
4759 m_styleSheet
= oldSheet
->GetNextSheet();
4768 /// Submit command to insert paragraphs
4769 bool wxRichTextBuffer::InsertParagraphsWithUndo(long pos
, const wxRichTextParagraphLayoutBox
& paragraphs
, wxRichTextCtrl
* ctrl
, int flags
)
4771 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4773 wxTextAttr
attr(GetDefaultStyle());
4775 wxTextAttr
* p
= NULL
;
4776 wxTextAttr paraAttr
;
4777 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4779 paraAttr
= GetStyleForNewParagraph(pos
);
4780 if (!paraAttr
.IsDefault())
4786 action
->GetNewParagraphs() = paragraphs
;
4790 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetLast();
4793 wxRichTextParagraph
* obj
= (wxRichTextParagraph
*) node
->GetData();
4794 obj
->SetAttributes(*p
);
4795 node
= node
->GetPrevious();
4799 action
->SetPosition(pos
);
4801 // Set the range we'll need to delete in Undo
4802 action
->SetRange(wxRichTextRange(pos
, pos
+ paragraphs
.GetRange().GetEnd() - 1));
4804 SubmitAction(action
);
4809 /// Submit command to insert the given text
4810 bool wxRichTextBuffer::InsertTextWithUndo(long pos
, const wxString
& text
, wxRichTextCtrl
* ctrl
, int flags
)
4812 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4814 wxTextAttr
* p
= NULL
;
4815 wxTextAttr paraAttr
;
4816 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4818 // Get appropriate paragraph style
4819 paraAttr
= GetStyleForNewParagraph(pos
, false, false);
4820 if (!paraAttr
.IsDefault())
4824 action
->GetNewParagraphs().AddParagraphs(text
, p
);
4826 int length
= action
->GetNewParagraphs().GetRange().GetLength();
4828 if (text
.length() > 0 && text
.Last() != wxT('\n'))
4830 // Don't count the newline when undoing
4832 action
->GetNewParagraphs().SetPartialParagraph(true);
4834 else if (text
.length() > 0 && text
.Last() == wxT('\n'))
4837 action
->SetPosition(pos
);
4839 // Set the range we'll need to delete in Undo
4840 action
->SetRange(wxRichTextRange(pos
, pos
+ length
- 1));
4842 SubmitAction(action
);
4847 /// Submit command to insert the given text
4848 bool wxRichTextBuffer::InsertNewlineWithUndo(long pos
, wxRichTextCtrl
* ctrl
, int flags
)
4850 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4852 wxTextAttr
* p
= NULL
;
4853 wxTextAttr paraAttr
;
4854 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4856 paraAttr
= GetStyleForNewParagraph(pos
, false, true /* look for next paragraph style */);
4857 if (!paraAttr
.IsDefault())
4861 wxTextAttr
attr(GetDefaultStyle());
4863 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(wxEmptyString
, this, & attr
);
4864 action
->GetNewParagraphs().AppendChild(newPara
);
4865 action
->GetNewParagraphs().UpdateRanges();
4866 action
->GetNewParagraphs().SetPartialParagraph(false);
4867 action
->SetPosition(pos
);
4870 newPara
->SetAttributes(*p
);
4872 // Set the range we'll need to delete in Undo
4873 action
->SetRange(wxRichTextRange(pos
, pos
));
4875 SubmitAction(action
);
4880 /// Submit command to insert the given image
4881 bool wxRichTextBuffer::InsertImageWithUndo(long pos
, const wxRichTextImageBlock
& imageBlock
, wxRichTextCtrl
* ctrl
, int flags
)
4883 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Image"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4885 wxTextAttr
* p
= NULL
;
4886 wxTextAttr paraAttr
;
4887 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4889 paraAttr
= GetStyleForNewParagraph(pos
);
4890 if (!paraAttr
.IsDefault())
4894 wxTextAttr
attr(GetDefaultStyle());
4896 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(this, & attr
);
4898 newPara
->SetAttributes(*p
);
4900 wxRichTextImage
* imageObject
= new wxRichTextImage(imageBlock
, newPara
);
4901 newPara
->AppendChild(imageObject
);
4902 action
->GetNewParagraphs().AppendChild(newPara
);
4903 action
->GetNewParagraphs().UpdateRanges();
4905 action
->GetNewParagraphs().SetPartialParagraph(true);
4907 action
->SetPosition(pos
);
4909 // Set the range we'll need to delete in Undo
4910 action
->SetRange(wxRichTextRange(pos
, pos
));
4912 SubmitAction(action
);
4917 /// Get the style that is appropriate for a new paragraph at this position.
4918 /// If the previous paragraph has a paragraph style name, look up the next-paragraph
4920 wxTextAttr
wxRichTextBuffer::GetStyleForNewParagraph(long pos
, bool caretPosition
, bool lookUpNewParaStyle
) const
4922 wxRichTextParagraph
* para
= GetParagraphAtPosition(pos
, caretPosition
);
4926 bool foundAttributes
= false;
4928 // Look for a matching paragraph style
4929 if (lookUpNewParaStyle
&& !para
->GetAttributes().GetParagraphStyleName().IsEmpty() && GetStyleSheet())
4931 wxRichTextParagraphStyleDefinition
* paraDef
= GetStyleSheet()->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
4934 // If we're not at the end of the paragraph, then we apply THIS style, and not the designated next style.
4935 if (para
->GetRange().GetEnd() == pos
&& !paraDef
->GetNextStyle().IsEmpty())
4937 wxRichTextParagraphStyleDefinition
* nextParaDef
= GetStyleSheet()->FindParagraphStyle(paraDef
->GetNextStyle());
4940 foundAttributes
= true;
4941 attr
= nextParaDef
->GetStyleMergedWithBase(GetStyleSheet());
4945 // If we didn't find the 'next style', use this style instead.
4946 if (!foundAttributes
)
4948 foundAttributes
= true;
4949 attr
= paraDef
->GetStyleMergedWithBase(GetStyleSheet());
4953 if (!foundAttributes
)
4955 attr
= para
->GetAttributes();
4956 int flags
= attr
.GetFlags();
4958 // Eliminate character styles
4959 flags
&= ( (~ wxTEXT_ATTR_FONT
) |
4960 (~ wxTEXT_ATTR_TEXT_COLOUR
) |
4961 (~ wxTEXT_ATTR_BACKGROUND_COLOUR
) );
4962 attr
.SetFlags(flags
);
4965 // Now see if we need to number the paragraph.
4966 if (attr
.HasBulletStyle())
4968 wxTextAttr numberingAttr
;
4969 if (FindNextParagraphNumber(para
, numberingAttr
))
4970 wxRichTextApplyStyle(attr
, (const wxTextAttr
&) numberingAttr
);
4976 return wxTextAttr();
4979 /// Submit command to delete this range
4980 bool wxRichTextBuffer::DeleteRangeWithUndo(const wxRichTextRange
& range
, wxRichTextCtrl
* ctrl
)
4982 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Delete"), wxRICHTEXT_DELETE
, this, ctrl
);
4984 action
->SetPosition(ctrl
->GetCaretPosition());
4986 // Set the range to delete
4987 action
->SetRange(range
);
4989 // Copy the fragment that we'll need to restore in Undo
4990 CopyFragment(range
, action
->GetOldParagraphs());
4992 // Special case: if there is only one (non-partial) paragraph,
4993 // we must save the *next* paragraph's style, because that
4994 // is the style we must apply when inserting the content back
4995 // when undoing the delete. (This is because we're merging the
4996 // paragraph with the previous paragraph and throwing away
4997 // the style, and we need to restore it.)
4998 if (!action
->GetOldParagraphs().GetPartialParagraph() && action
->GetOldParagraphs().GetChildCount() == 1)
5000 wxRichTextParagraph
* lastPara
= GetParagraphAtPosition(range
.GetStart());
5003 wxRichTextParagraph
* nextPara
= GetParagraphAtPosition(range
.GetEnd()+1);
5006 wxRichTextParagraph
* para
= (wxRichTextParagraph
*) action
->GetOldParagraphs().GetChild(0);
5007 para
->SetAttributes(nextPara
->GetAttributes());
5012 SubmitAction(action
);
5017 /// Collapse undo/redo commands
5018 bool wxRichTextBuffer::BeginBatchUndo(const wxString
& cmdName
)
5020 if (m_batchedCommandDepth
== 0)
5022 wxASSERT(m_batchedCommand
== NULL
);
5023 if (m_batchedCommand
)
5025 GetCommandProcessor()->Submit(m_batchedCommand
);
5027 m_batchedCommand
= new wxRichTextCommand(cmdName
);
5030 m_batchedCommandDepth
++;
5035 /// Collapse undo/redo commands
5036 bool wxRichTextBuffer::EndBatchUndo()
5038 m_batchedCommandDepth
--;
5040 wxASSERT(m_batchedCommandDepth
>= 0);
5041 wxASSERT(m_batchedCommand
!= NULL
);
5043 if (m_batchedCommandDepth
== 0)
5045 GetCommandProcessor()->Submit(m_batchedCommand
);
5046 m_batchedCommand
= NULL
;
5052 /// Submit immediately, or delay according to whether collapsing is on
5053 bool wxRichTextBuffer::SubmitAction(wxRichTextAction
* action
)
5055 if (BatchingUndo() && m_batchedCommand
&& !SuppressingUndo())
5056 m_batchedCommand
->AddAction(action
);
5059 wxRichTextCommand
* cmd
= new wxRichTextCommand(action
->GetName());
5060 cmd
->AddAction(action
);
5062 // Only store it if we're not suppressing undo.
5063 return GetCommandProcessor()->Submit(cmd
, !SuppressingUndo());
5069 /// Begin suppressing undo/redo commands.
5070 bool wxRichTextBuffer::BeginSuppressUndo()
5077 /// End suppressing undo/redo commands.
5078 bool wxRichTextBuffer::EndSuppressUndo()
5085 /// Begin using a style
5086 bool wxRichTextBuffer::BeginStyle(const wxTextAttr
& style
)
5088 wxTextAttr
newStyle(GetDefaultStyle());
5090 // Save the old default style
5091 m_attributeStack
.Append((wxObject
*) new wxTextAttr(GetDefaultStyle()));
5093 wxRichTextApplyStyle(newStyle
, style
);
5094 newStyle
.SetFlags(style
.GetFlags()|newStyle
.GetFlags());
5096 SetDefaultStyle(newStyle
);
5098 // wxLogDebug("Default style size = %d", GetDefaultStyle().GetFont().GetPointSize());
5104 bool wxRichTextBuffer::EndStyle()
5106 if (!m_attributeStack
.GetFirst())
5108 wxLogDebug(_("Too many EndStyle calls!"));
5112 wxList::compatibility_iterator node
= m_attributeStack
.GetLast();
5113 wxTextAttr
* attr
= (wxTextAttr
*)node
->GetData();
5114 m_attributeStack
.Erase(node
);
5116 SetDefaultStyle(*attr
);
5123 bool wxRichTextBuffer::EndAllStyles()
5125 while (m_attributeStack
.GetCount() != 0)
5130 /// Clear the style stack
5131 void wxRichTextBuffer::ClearStyleStack()
5133 for (wxList::compatibility_iterator node
= m_attributeStack
.GetFirst(); node
; node
= node
->GetNext())
5134 delete (wxTextAttr
*) node
->GetData();
5135 m_attributeStack
.Clear();
5138 /// Begin using bold
5139 bool wxRichTextBuffer::BeginBold()
5142 attr
.SetFontWeight(wxBOLD
);
5144 return BeginStyle(attr
);
5147 /// Begin using italic
5148 bool wxRichTextBuffer::BeginItalic()
5151 attr
.SetFontStyle(wxITALIC
);
5153 return BeginStyle(attr
);
5156 /// Begin using underline
5157 bool wxRichTextBuffer::BeginUnderline()
5160 attr
.SetFontUnderlined(true);
5162 return BeginStyle(attr
);
5165 /// Begin using point size
5166 bool wxRichTextBuffer::BeginFontSize(int pointSize
)
5169 attr
.SetFontSize(pointSize
);
5171 return BeginStyle(attr
);
5174 /// Begin using this font
5175 bool wxRichTextBuffer::BeginFont(const wxFont
& font
)
5180 return BeginStyle(attr
);
5183 /// Begin using this colour
5184 bool wxRichTextBuffer::BeginTextColour(const wxColour
& colour
)
5187 attr
.SetFlags(wxTEXT_ATTR_TEXT_COLOUR
);
5188 attr
.SetTextColour(colour
);
5190 return BeginStyle(attr
);
5193 /// Begin using alignment
5194 bool wxRichTextBuffer::BeginAlignment(wxTextAttrAlignment alignment
)
5197 attr
.SetFlags(wxTEXT_ATTR_ALIGNMENT
);
5198 attr
.SetAlignment(alignment
);
5200 return BeginStyle(attr
);
5203 /// Begin left indent
5204 bool wxRichTextBuffer::BeginLeftIndent(int leftIndent
, int leftSubIndent
)
5207 attr
.SetFlags(wxTEXT_ATTR_LEFT_INDENT
);
5208 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5210 return BeginStyle(attr
);
5213 /// Begin right indent
5214 bool wxRichTextBuffer::BeginRightIndent(int rightIndent
)
5217 attr
.SetFlags(wxTEXT_ATTR_RIGHT_INDENT
);
5218 attr
.SetRightIndent(rightIndent
);
5220 return BeginStyle(attr
);
5223 /// Begin paragraph spacing
5224 bool wxRichTextBuffer::BeginParagraphSpacing(int before
, int after
)
5228 flags
|= wxTEXT_ATTR_PARA_SPACING_BEFORE
;
5230 flags
|= wxTEXT_ATTR_PARA_SPACING_AFTER
;
5233 attr
.SetFlags(flags
);
5234 attr
.SetParagraphSpacingBefore(before
);
5235 attr
.SetParagraphSpacingAfter(after
);
5237 return BeginStyle(attr
);
5240 /// Begin line spacing
5241 bool wxRichTextBuffer::BeginLineSpacing(int lineSpacing
)
5244 attr
.SetFlags(wxTEXT_ATTR_LINE_SPACING
);
5245 attr
.SetLineSpacing(lineSpacing
);
5247 return BeginStyle(attr
);
5250 /// Begin numbered bullet
5251 bool wxRichTextBuffer::BeginNumberedBullet(int bulletNumber
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5254 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5255 attr
.SetBulletStyle(bulletStyle
);
5256 attr
.SetBulletNumber(bulletNumber
);
5257 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5259 return BeginStyle(attr
);
5262 /// Begin symbol bullet
5263 bool wxRichTextBuffer::BeginSymbolBullet(const wxString
& symbol
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5266 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5267 attr
.SetBulletStyle(bulletStyle
);
5268 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5269 attr
.SetBulletText(symbol
);
5271 return BeginStyle(attr
);
5274 /// Begin standard bullet
5275 bool wxRichTextBuffer::BeginStandardBullet(const wxString
& bulletName
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5278 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5279 attr
.SetBulletStyle(bulletStyle
);
5280 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5281 attr
.SetBulletName(bulletName
);
5283 return BeginStyle(attr
);
5286 /// Begin named character style
5287 bool wxRichTextBuffer::BeginCharacterStyle(const wxString
& characterStyle
)
5289 if (GetStyleSheet())
5291 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterStyle
);
5294 wxTextAttr attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5295 return BeginStyle(attr
);
5301 /// Begin named paragraph style
5302 bool wxRichTextBuffer::BeginParagraphStyle(const wxString
& paragraphStyle
)
5304 if (GetStyleSheet())
5306 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(paragraphStyle
);
5309 wxTextAttr attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5310 return BeginStyle(attr
);
5316 /// Begin named list style
5317 bool wxRichTextBuffer::BeginListStyle(const wxString
& listStyle
, int level
, int number
)
5319 if (GetStyleSheet())
5321 wxRichTextListStyleDefinition
* def
= GetStyleSheet()->FindListStyle(listStyle
);
5324 wxTextAttr
attr(def
->GetCombinedStyleForLevel(level
));
5326 attr
.SetBulletNumber(number
);
5328 return BeginStyle(attr
);
5335 bool wxRichTextBuffer::BeginURL(const wxString
& url
, const wxString
& characterStyle
)
5339 if (!characterStyle
.IsEmpty() && GetStyleSheet())
5341 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterStyle
);
5344 attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5349 return BeginStyle(attr
);
5352 /// Adds a handler to the end
5353 void wxRichTextBuffer::AddHandler(wxRichTextFileHandler
*handler
)
5355 sm_handlers
.Append(handler
);
5358 /// Inserts a handler at the front
5359 void wxRichTextBuffer::InsertHandler(wxRichTextFileHandler
*handler
)
5361 sm_handlers
.Insert( handler
);
5364 /// Removes a handler
5365 bool wxRichTextBuffer::RemoveHandler(const wxString
& name
)
5367 wxRichTextFileHandler
*handler
= FindHandler(name
);
5370 sm_handlers
.DeleteObject(handler
);
5378 /// Finds a handler by filename or, if supplied, type
5379 wxRichTextFileHandler
*wxRichTextBuffer::FindHandlerFilenameOrType(const wxString
& filename
, int imageType
)
5381 if (imageType
!= wxRICHTEXT_TYPE_ANY
)
5382 return FindHandler(imageType
);
5383 else if (!filename
.IsEmpty())
5385 wxString path
, file
, ext
;
5386 wxSplitPath(filename
, & path
, & file
, & ext
);
5387 return FindHandler(ext
, imageType
);
5394 /// Finds a handler by name
5395 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(const wxString
& name
)
5397 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5400 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5401 if (handler
->GetName().Lower() == name
.Lower()) return handler
;
5403 node
= node
->GetNext();
5408 /// Finds a handler by extension and type
5409 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(const wxString
& extension
, int type
)
5411 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5414 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5415 if ( handler
->GetExtension().Lower() == extension
.Lower() &&
5416 (type
== wxRICHTEXT_TYPE_ANY
|| handler
->GetType() == type
) )
5418 node
= node
->GetNext();
5423 /// Finds a handler by type
5424 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(int type
)
5426 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5429 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5430 if (handler
->GetType() == type
) return handler
;
5431 node
= node
->GetNext();
5436 void wxRichTextBuffer::InitStandardHandlers()
5438 if (!FindHandler(wxRICHTEXT_TYPE_TEXT
))
5439 AddHandler(new wxRichTextPlainTextHandler
);
5442 void wxRichTextBuffer::CleanUpHandlers()
5444 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5447 wxRichTextFileHandler
* handler
= (wxRichTextFileHandler
*)node
->GetData();
5448 wxList::compatibility_iterator next
= node
->GetNext();
5453 sm_handlers
.Clear();
5456 wxString
wxRichTextBuffer::GetExtWildcard(bool combine
, bool save
, wxArrayInt
* types
)
5463 wxList::compatibility_iterator node
= GetHandlers().GetFirst();
5467 wxRichTextFileHandler
* handler
= (wxRichTextFileHandler
*) node
->GetData();
5468 if (handler
->IsVisible() && ((save
&& handler
->CanSave()) || !save
&& handler
->CanLoad()))
5473 wildcard
+= wxT(";");
5474 wildcard
+= wxT("*.") + handler
->GetExtension();
5479 wildcard
+= wxT("|");
5480 wildcard
+= handler
->GetName();
5481 wildcard
+= wxT(" ");
5482 wildcard
+= _("files");
5483 wildcard
+= wxT(" (*.");
5484 wildcard
+= handler
->GetExtension();
5485 wildcard
+= wxT(")|*.");
5486 wildcard
+= handler
->GetExtension();
5488 types
->Add(handler
->GetType());
5493 node
= node
->GetNext();
5497 wildcard
= wxT("(") + wildcard
+ wxT(")|") + wildcard
;
5502 bool wxRichTextBuffer::LoadFile(const wxString
& filename
, int type
)
5504 wxRichTextFileHandler
* handler
= FindHandlerFilenameOrType(filename
, type
);
5507 SetDefaultStyle(wxTextAttr());
5508 handler
->SetFlags(GetHandlerFlags());
5509 bool success
= handler
->LoadFile(this, filename
);
5510 Invalidate(wxRICHTEXT_ALL
);
5518 bool wxRichTextBuffer::SaveFile(const wxString
& filename
, int type
)
5520 wxRichTextFileHandler
* handler
= FindHandlerFilenameOrType(filename
, type
);
5523 handler
->SetFlags(GetHandlerFlags());
5524 return handler
->SaveFile(this, filename
);
5530 /// Load from a stream
5531 bool wxRichTextBuffer::LoadFile(wxInputStream
& stream
, int type
)
5533 wxRichTextFileHandler
* handler
= FindHandler(type
);
5536 SetDefaultStyle(wxTextAttr());
5537 handler
->SetFlags(GetHandlerFlags());
5538 bool success
= handler
->LoadFile(this, stream
);
5539 Invalidate(wxRICHTEXT_ALL
);
5546 /// Save to a stream
5547 bool wxRichTextBuffer::SaveFile(wxOutputStream
& stream
, int type
)
5549 wxRichTextFileHandler
* handler
= FindHandler(type
);
5552 handler
->SetFlags(GetHandlerFlags());
5553 return handler
->SaveFile(this, stream
);
5559 /// Copy the range to the clipboard
5560 bool wxRichTextBuffer::CopyToClipboard(const wxRichTextRange
& range
)
5562 bool success
= false;
5563 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5565 if (!wxTheClipboard
->IsOpened() && wxTheClipboard
->Open())
5567 wxTheClipboard
->Clear();
5569 // Add composite object
5571 wxDataObjectComposite
* compositeObject
= new wxDataObjectComposite();
5574 wxString text
= GetTextForRange(range
);
5577 text
= wxTextFile::Translate(text
, wxTextFileType_Dos
);
5580 compositeObject
->Add(new wxTextDataObject(text
), false /* not preferred */);
5583 // Add rich text buffer data object. This needs the XML handler to be present.
5585 if (FindHandler(wxRICHTEXT_TYPE_XML
))
5587 wxRichTextBuffer
* richTextBuf
= new wxRichTextBuffer
;
5588 CopyFragment(range
, *richTextBuf
);
5590 compositeObject
->Add(new wxRichTextBufferDataObject(richTextBuf
), true /* preferred */);
5593 if (wxTheClipboard
->SetData(compositeObject
))
5596 wxTheClipboard
->Close();
5605 /// Paste the clipboard content to the buffer
5606 bool wxRichTextBuffer::PasteFromClipboard(long position
)
5608 bool success
= false;
5609 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5610 if (CanPasteFromClipboard())
5612 if (wxTheClipboard
->Open())
5614 if (wxTheClipboard
->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())))
5616 wxRichTextBufferDataObject data
;
5617 wxTheClipboard
->GetData(data
);
5618 wxRichTextBuffer
* richTextBuffer
= data
.GetRichTextBuffer();
5621 InsertParagraphsWithUndo(position
+1, *richTextBuffer
, GetRichTextCtrl(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
);
5622 delete richTextBuffer
;
5625 else if (wxTheClipboard
->IsSupported(wxDF_TEXT
) || wxTheClipboard
->IsSupported(wxDF_UNICODETEXT
))
5627 wxTextDataObject data
;
5628 wxTheClipboard
->GetData(data
);
5629 wxString
text(data
.GetText());
5632 text2
.Alloc(text
.Length()+1);
5634 for (i
= 0; i
< text
.Length(); i
++)
5636 wxChar ch
= text
[i
];
5637 if (ch
!= wxT('\r'))
5641 wxString text2
= text
;
5643 InsertTextWithUndo(position
+1, text2
, GetRichTextCtrl());
5647 else if (wxTheClipboard
->IsSupported(wxDF_BITMAP
))
5649 wxBitmapDataObject data
;
5650 wxTheClipboard
->GetData(data
);
5651 wxBitmap
bitmap(data
.GetBitmap());
5652 wxImage
image(bitmap
.ConvertToImage());
5654 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Image"), wxRICHTEXT_INSERT
, this, GetRichTextCtrl(), false);
5656 action
->GetNewParagraphs().AddImage(image
);
5658 if (action
->GetNewParagraphs().GetChildCount() == 1)
5659 action
->GetNewParagraphs().SetPartialParagraph(true);
5661 action
->SetPosition(position
);
5663 // Set the range we'll need to delete in Undo
5664 action
->SetRange(wxRichTextRange(position
, position
));
5666 SubmitAction(action
);
5670 wxTheClipboard
->Close();
5674 wxUnusedVar(position
);
5679 /// Can we paste from the clipboard?
5680 bool wxRichTextBuffer::CanPasteFromClipboard() const
5682 bool canPaste
= false;
5683 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5684 if (!wxTheClipboard
->IsOpened() && wxTheClipboard
->Open())
5686 if (wxTheClipboard
->IsSupported(wxDF_TEXT
) || wxTheClipboard
->IsSupported(wxDF_UNICODETEXT
) ||
5687 wxTheClipboard
->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())) ||
5688 wxTheClipboard
->IsSupported(wxDF_BITMAP
))
5692 wxTheClipboard
->Close();
5698 /// Dumps contents of buffer for debugging purposes
5699 void wxRichTextBuffer::Dump()
5703 wxStringOutputStream
stream(& text
);
5704 wxTextOutputStream
textStream(stream
);
5711 /// Add an event handler
5712 bool wxRichTextBuffer::AddEventHandler(wxEvtHandler
* handler
)
5714 m_eventHandlers
.Append(handler
);
5718 /// Remove an event handler
5719 bool wxRichTextBuffer::RemoveEventHandler(wxEvtHandler
* handler
, bool deleteHandler
)
5721 wxList::compatibility_iterator node
= m_eventHandlers
.Find(handler
);
5724 m_eventHandlers
.Erase(node
);
5734 /// Clear event handlers
5735 void wxRichTextBuffer::ClearEventHandlers()
5737 m_eventHandlers
.Clear();
5740 /// Send event to event handlers. If sendToAll is true, will send to all event handlers,
5741 /// otherwise will stop at the first successful one.
5742 bool wxRichTextBuffer::SendEvent(wxEvent
& event
, bool sendToAll
)
5744 bool success
= false;
5745 for (wxList::compatibility_iterator node
= m_eventHandlers
.GetFirst(); node
; node
= node
->GetNext())
5747 wxEvtHandler
* handler
= (wxEvtHandler
*) node
->GetData();
5748 if (handler
->ProcessEvent(event
))
5758 /// Set style sheet and notify of the change
5759 bool wxRichTextBuffer::SetStyleSheetAndNotify(wxRichTextStyleSheet
* sheet
)
5761 wxRichTextStyleSheet
* oldSheet
= GetStyleSheet();
5763 wxWindowID id
= wxID_ANY
;
5764 if (GetRichTextCtrl())
5765 id
= GetRichTextCtrl()->GetId();
5767 wxRichTextEvent
event(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING
, id
);
5768 event
.SetEventObject(GetRichTextCtrl());
5769 event
.SetOldStyleSheet(oldSheet
);
5770 event
.SetNewStyleSheet(sheet
);
5773 if (SendEvent(event
) && !event
.IsAllowed())
5775 if (sheet
!= oldSheet
)
5781 if (oldSheet
&& oldSheet
!= sheet
)
5784 SetStyleSheet(sheet
);
5786 event
.SetEventType(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED
);
5787 event
.SetOldStyleSheet(NULL
);
5790 return SendEvent(event
);
5793 /// Set renderer, deleting old one
5794 void wxRichTextBuffer::SetRenderer(wxRichTextRenderer
* renderer
)
5798 sm_renderer
= renderer
;
5801 bool wxRichTextStdRenderer::DrawStandardBullet(wxRichTextParagraph
* paragraph
, wxDC
& dc
, const wxTextAttr
& bulletAttr
, const wxRect
& rect
)
5803 if (bulletAttr
.GetTextColour().Ok())
5805 wxCheckSetPen(dc
, wxPen(bulletAttr
.GetTextColour()));
5806 wxCheckSetBrush(dc
, wxBrush(bulletAttr
.GetTextColour()));
5810 wxCheckSetPen(dc
, *wxBLACK_PEN
);
5811 wxCheckSetBrush(dc
, *wxBLACK_BRUSH
);
5815 if (bulletAttr
.HasFont())
5817 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(bulletAttr
);
5820 font
= (*wxNORMAL_FONT
);
5822 wxCheckSetFont(dc
, font
);
5824 int charHeight
= dc
.GetCharHeight();
5826 int bulletWidth
= (int) (((float) charHeight
) * wxRichTextBuffer::GetBulletProportion());
5827 int bulletHeight
= bulletWidth
;
5831 // Calculate the top position of the character (as opposed to the whole line height)
5832 int y
= rect
.y
+ (rect
.height
- charHeight
);
5834 // Calculate where the bullet should be positioned
5835 y
= y
+ (charHeight
+1)/2 - (bulletHeight
+1)/2;
5837 // The margin between a bullet and text.
5838 int margin
= paragraph
->ConvertTenthsMMToPixels(dc
, wxRichTextBuffer::GetBulletRightMargin());
5840 if (bulletAttr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT
)
5841 x
= rect
.x
+ rect
.width
- bulletWidth
- margin
;
5842 else if (bulletAttr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE
)
5843 x
= x
+ (rect
.width
)/2 - bulletWidth
/2;
5845 if (bulletAttr
.GetBulletName() == wxT("standard/square"))
5847 dc
.DrawRectangle(x
, y
, bulletWidth
, bulletHeight
);
5849 else if (bulletAttr
.GetBulletName() == wxT("standard/diamond"))
5852 pts
[0].x
= x
; pts
[0].y
= y
+ bulletHeight
/2;
5853 pts
[1].x
= x
+ bulletWidth
/2; pts
[1].y
= y
;
5854 pts
[2].x
= x
+ bulletWidth
; pts
[2].y
= y
+ bulletHeight
/2;
5855 pts
[3].x
= x
+ bulletWidth
/2; pts
[3].y
= y
+ bulletHeight
;
5857 dc
.DrawPolygon(4, pts
);
5859 else if (bulletAttr
.GetBulletName() == wxT("standard/triangle"))
5862 pts
[0].x
= x
; pts
[0].y
= y
;
5863 pts
[1].x
= x
+ bulletWidth
; pts
[1].y
= y
+ bulletHeight
/2;
5864 pts
[2].x
= x
; pts
[2].y
= y
+ bulletHeight
;
5866 dc
.DrawPolygon(3, pts
);
5868 else // "standard/circle", and catch-all
5870 dc
.DrawEllipse(x
, y
, bulletWidth
, bulletHeight
);
5876 bool wxRichTextStdRenderer::DrawTextBullet(wxRichTextParagraph
* paragraph
, wxDC
& dc
, const wxTextAttr
& attr
, const wxRect
& rect
, const wxString
& text
)
5881 if ((attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL
) && !attr
.GetBulletFont().IsEmpty() && attr
.HasFont())
5883 wxTextAttr fontAttr
;
5884 fontAttr
.SetFontSize(attr
.GetFontSize());
5885 fontAttr
.SetFontStyle(attr
.GetFontStyle());
5886 fontAttr
.SetFontWeight(attr
.GetFontWeight());
5887 fontAttr
.SetFontUnderlined(attr
.GetFontUnderlined());
5888 fontAttr
.SetFontFaceName(attr
.GetBulletFont());
5889 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(fontAttr
);
5891 else if (attr
.HasFont())
5892 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(attr
);
5894 font
= (*wxNORMAL_FONT
);
5896 wxCheckSetFont(dc
, font
);
5898 if (attr
.GetTextColour().Ok())
5899 dc
.SetTextForeground(attr
.GetTextColour());
5901 dc
.SetBackgroundMode(wxTRANSPARENT
);
5903 int charHeight
= dc
.GetCharHeight();
5905 dc
.GetTextExtent(text
, & tw
, & th
);
5909 // Calculate the top position of the character (as opposed to the whole line height)
5910 int y
= rect
.y
+ (rect
.height
- charHeight
);
5912 // The margin between a bullet and text.
5913 int margin
= paragraph
->ConvertTenthsMMToPixels(dc
, wxRichTextBuffer::GetBulletRightMargin());
5915 if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT
)
5916 x
= (rect
.x
+ rect
.width
) - tw
- margin
;
5917 else if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE
)
5918 x
= x
+ (rect
.width
)/2 - tw
/2;
5920 dc
.DrawText(text
, x
, y
);
5928 bool wxRichTextStdRenderer::DrawBitmapBullet(wxRichTextParagraph
* WXUNUSED(paragraph
), wxDC
& WXUNUSED(dc
), const wxTextAttr
& WXUNUSED(attr
), const wxRect
& WXUNUSED(rect
))
5930 // Currently unimplemented. The intention is to store bitmaps by name in a media store associated
5931 // with the buffer. The store will allow retrieval from memory, disk or other means.
5935 /// Enumerate the standard bullet names currently supported
5936 bool wxRichTextStdRenderer::EnumerateStandardBulletNames(wxArrayString
& bulletNames
)
5938 bulletNames
.Add(wxT("standard/circle"));
5939 bulletNames
.Add(wxT("standard/square"));
5940 bulletNames
.Add(wxT("standard/diamond"));
5941 bulletNames
.Add(wxT("standard/triangle"));
5947 * Module to initialise and clean up handlers
5950 class wxRichTextModule
: public wxModule
5952 DECLARE_DYNAMIC_CLASS(wxRichTextModule
)
5954 wxRichTextModule() {}
5957 wxRichTextBuffer::SetRenderer(new wxRichTextStdRenderer
);
5958 wxRichTextBuffer::InitStandardHandlers();
5959 wxRichTextParagraph::InitDefaultTabs();
5964 wxRichTextBuffer::CleanUpHandlers();
5965 wxRichTextDecimalToRoman(-1);
5966 wxRichTextParagraph::ClearDefaultTabs();
5967 wxRichTextCtrl::ClearAvailableFontNames();
5968 wxRichTextBuffer::SetRenderer(NULL
);
5972 IMPLEMENT_DYNAMIC_CLASS(wxRichTextModule
, wxModule
)
5975 // If the richtext lib is dynamically loaded after the app has already started
5976 // (such as from wxPython) then the built-in module system will not init this
5977 // module. Provide this function to do it manually.
5978 void wxRichTextModuleInit()
5980 wxModule
* module = new wxRichTextModule
;
5982 wxModule::RegisterModule(module);
5987 * Commands for undo/redo
5991 wxRichTextCommand::wxRichTextCommand(const wxString
& name
, wxRichTextCommandId id
, wxRichTextBuffer
* buffer
,
5992 wxRichTextCtrl
* ctrl
, bool ignoreFirstTime
): wxCommand(true, name
)
5994 /* wxRichTextAction* action = */ new wxRichTextAction(this, name
, id
, buffer
, ctrl
, ignoreFirstTime
);
5997 wxRichTextCommand::wxRichTextCommand(const wxString
& name
): wxCommand(true, name
)
6001 wxRichTextCommand::~wxRichTextCommand()
6006 void wxRichTextCommand::AddAction(wxRichTextAction
* action
)
6008 if (!m_actions
.Member(action
))
6009 m_actions
.Append(action
);
6012 bool wxRichTextCommand::Do()
6014 for (wxList::compatibility_iterator node
= m_actions
.GetFirst(); node
; node
= node
->GetNext())
6016 wxRichTextAction
* action
= (wxRichTextAction
*) node
->GetData();
6023 bool wxRichTextCommand::Undo()
6025 for (wxList::compatibility_iterator node
= m_actions
.GetLast(); node
; node
= node
->GetPrevious())
6027 wxRichTextAction
* action
= (wxRichTextAction
*) node
->GetData();
6034 void wxRichTextCommand::ClearActions()
6036 WX_CLEAR_LIST(wxList
, m_actions
);
6044 wxRichTextAction::wxRichTextAction(wxRichTextCommand
* cmd
, const wxString
& name
, wxRichTextCommandId id
, wxRichTextBuffer
* buffer
,
6045 wxRichTextCtrl
* ctrl
, bool ignoreFirstTime
)
6048 m_ignoreThis
= ignoreFirstTime
;
6053 m_newParagraphs
.SetDefaultStyle(buffer
->GetDefaultStyle());
6054 m_newParagraphs
.SetBasicStyle(buffer
->GetBasicStyle());
6056 cmd
->AddAction(this);
6059 wxRichTextAction::~wxRichTextAction()
6063 bool wxRichTextAction::Do()
6065 m_buffer
->Modify(true);
6069 case wxRICHTEXT_INSERT
:
6071 // Store a list of line start character and y positions so we can figure out which area
6072 // we need to refresh
6073 wxArrayInt optimizationLineCharPositions
;
6074 wxArrayInt optimizationLineYPositions
;
6076 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6077 // NOTE: we're assuming that the buffer is laid out correctly at this point.
6078 // If we had several actions, which only invalidate and leave layout until the
6079 // paint handler is called, then this might not be true. So we may need to switch
6080 // optimisation on only when we're simply adding text and not simultaneously
6081 // deleting a selection, for example. Or, we make sure the buffer is laid out correctly
6082 // first, but of course this means we'll be doing it twice.
6083 if (!m_buffer
->GetDirty() && m_ctrl
) // can only do optimisation if the buffer is already laid out correctly
6085 wxSize clientSize
= m_ctrl
->GetClientSize();
6086 wxPoint firstVisiblePt
= m_ctrl
->GetFirstVisiblePoint();
6087 int lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6089 wxRichTextParagraph
* para
= m_buffer
->GetParagraphAtPosition(GetPosition());
6090 wxRichTextObjectList::compatibility_iterator node
= m_buffer
->GetChildren().Find(para
);
6093 wxRichTextParagraph
* child
= (wxRichTextParagraph
*) node
->GetData();
6094 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
6097 wxRichTextLine
* line
= node2
->GetData();
6098 wxPoint pt
= line
->GetAbsolutePosition();
6099 wxRichTextRange range
= line
->GetAbsoluteRange();
6103 node2
= wxRichTextLineList::compatibility_iterator();
6104 node
= wxRichTextObjectList::compatibility_iterator();
6106 else if (range
.GetStart() > GetPosition() && pt
.y
>= firstVisiblePt
.y
)
6108 optimizationLineCharPositions
.Add(range
.GetStart());
6109 optimizationLineYPositions
.Add(pt
.y
);
6113 node2
= node2
->GetNext();
6117 node
= node
->GetNext();
6122 m_buffer
->InsertFragment(GetPosition(), m_newParagraphs
);
6123 m_buffer
->UpdateRanges();
6124 m_buffer
->Invalidate(GetRange());
6126 long newCaretPosition
= GetPosition() + m_newParagraphs
.GetRange().GetLength();
6128 // Character position to caret position
6129 newCaretPosition
--;
6131 // Don't take into account the last newline
6132 if (m_newParagraphs
.GetPartialParagraph())
6133 newCaretPosition
--;
6135 if (m_newParagraphs
.GetChildren().GetCount() > 1)
6137 wxRichTextObject
* p
= (wxRichTextObject
*) m_newParagraphs
.GetChildren().GetLast()->GetData();
6138 if (p
->GetRange().GetLength() == 1)
6139 newCaretPosition
--;
6142 newCaretPosition
= wxMin(newCaretPosition
, (m_buffer
->GetRange().GetEnd()-1));
6144 if (optimizationLineCharPositions
.GetCount() > 0)
6145 UpdateAppearance(newCaretPosition
, true /* send update event */, & optimizationLineCharPositions
, & optimizationLineYPositions
);
6147 UpdateAppearance(newCaretPosition
, true /* send update event */);
6149 wxRichTextEvent
cmdEvent(
6150 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED
,
6151 m_ctrl
? m_ctrl
->GetId() : -1);
6152 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6153 cmdEvent
.SetRange(GetRange());
6154 cmdEvent
.SetPosition(GetRange().GetStart());
6156 m_buffer
->SendEvent(cmdEvent
);
6160 case wxRICHTEXT_DELETE
:
6162 m_buffer
->DeleteRange(GetRange());
6163 m_buffer
->UpdateRanges();
6164 m_buffer
->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6166 UpdateAppearance(GetRange().GetStart()-1, true /* send update event */);
6168 wxRichTextEvent
cmdEvent(
6169 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED
,
6170 m_ctrl
? m_ctrl
->GetId() : -1);
6171 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6172 cmdEvent
.SetRange(GetRange());
6173 cmdEvent
.SetPosition(GetRange().GetStart());
6175 m_buffer
->SendEvent(cmdEvent
);
6179 case wxRICHTEXT_CHANGE_STYLE
:
6181 ApplyParagraphs(GetNewParagraphs());
6182 m_buffer
->Invalidate(GetRange());
6184 UpdateAppearance(GetPosition());
6186 wxRichTextEvent
cmdEvent(
6187 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED
,
6188 m_ctrl
? m_ctrl
->GetId() : -1);
6189 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6190 cmdEvent
.SetRange(GetRange());
6191 cmdEvent
.SetPosition(GetRange().GetStart());
6193 m_buffer
->SendEvent(cmdEvent
);
6204 bool wxRichTextAction::Undo()
6206 m_buffer
->Modify(true);
6210 case wxRICHTEXT_INSERT
:
6212 m_buffer
->DeleteRange(GetRange());
6213 m_buffer
->UpdateRanges();
6214 m_buffer
->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6216 long newCaretPosition
= GetPosition() - 1;
6218 UpdateAppearance(newCaretPosition
, true /* send update event */);
6220 wxRichTextEvent
cmdEvent(
6221 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED
,
6222 m_ctrl
? m_ctrl
->GetId() : -1);
6223 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6224 cmdEvent
.SetRange(GetRange());
6225 cmdEvent
.SetPosition(GetRange().GetStart());
6227 m_buffer
->SendEvent(cmdEvent
);
6231 case wxRICHTEXT_DELETE
:
6233 m_buffer
->InsertFragment(GetRange().GetStart(), m_oldParagraphs
);
6234 m_buffer
->UpdateRanges();
6235 m_buffer
->Invalidate(GetRange());
6237 UpdateAppearance(GetPosition(), true /* send update event */);
6239 wxRichTextEvent
cmdEvent(
6240 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED
,
6241 m_ctrl
? m_ctrl
->GetId() : -1);
6242 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6243 cmdEvent
.SetRange(GetRange());
6244 cmdEvent
.SetPosition(GetRange().GetStart());
6246 m_buffer
->SendEvent(cmdEvent
);
6250 case wxRICHTEXT_CHANGE_STYLE
:
6252 ApplyParagraphs(GetOldParagraphs());
6253 m_buffer
->Invalidate(GetRange());
6255 UpdateAppearance(GetPosition());
6257 wxRichTextEvent
cmdEvent(
6258 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED
,
6259 m_ctrl
? m_ctrl
->GetId() : -1);
6260 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6261 cmdEvent
.SetRange(GetRange());
6262 cmdEvent
.SetPosition(GetRange().GetStart());
6264 m_buffer
->SendEvent(cmdEvent
);
6275 /// Update the control appearance
6276 void wxRichTextAction::UpdateAppearance(long caretPosition
, bool sendUpdateEvent
, wxArrayInt
* optimizationLineCharPositions
, wxArrayInt
* optimizationLineYPositions
)
6280 m_ctrl
->SetCaretPosition(caretPosition
);
6281 if (!m_ctrl
->IsFrozen())
6283 m_ctrl
->LayoutContent();
6284 m_ctrl
->PositionCaret();
6286 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6287 // Find refresh rectangle if we are in a position to optimise refresh
6288 if (m_cmdId
== wxRICHTEXT_INSERT
&& optimizationLineCharPositions
&& optimizationLineCharPositions
->GetCount() > 0)
6292 wxSize clientSize
= m_ctrl
->GetClientSize();
6293 wxPoint firstVisiblePt
= m_ctrl
->GetFirstVisiblePoint();
6295 // Start/end positions
6297 int lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6299 bool foundStart
= false;
6300 bool foundEnd
= false;
6302 // position offset - how many characters were inserted
6303 int positionOffset
= GetRange().GetLength();
6305 // find the first line which is being drawn at the same position as it was
6306 // before. Since we're talking about a simple insertion, we can assume
6307 // that the rest of the window does not need to be redrawn.
6309 wxRichTextParagraph
* para
= m_buffer
->GetParagraphAtPosition(GetPosition());
6310 wxRichTextObjectList::compatibility_iterator node
= m_buffer
->GetChildren().Find(para
);
6313 wxRichTextParagraph
* child
= (wxRichTextParagraph
*) node
->GetData();
6314 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
6317 wxRichTextLine
* line
= node2
->GetData();
6318 wxPoint pt
= line
->GetAbsolutePosition();
6319 wxRichTextRange range
= line
->GetAbsoluteRange();
6321 // we want to find the first line that is in the same position
6322 // as before. This will mean we're at the end of the changed text.
6324 if (pt
.y
> lastY
) // going past the end of the window, no more info
6326 node2
= wxRichTextLineList::compatibility_iterator();
6327 node
= wxRichTextObjectList::compatibility_iterator();
6333 firstY
= pt
.y
- firstVisiblePt
.y
;
6337 // search for this line being at the same position as before
6338 for (i
= 0; i
< optimizationLineCharPositions
->GetCount(); i
++)
6340 if (((*optimizationLineCharPositions
)[i
] + positionOffset
== range
.GetStart()) &&
6341 ((*optimizationLineYPositions
)[i
] == pt
.y
))
6343 // Stop, we're now the same as we were
6345 lastY
= pt
.y
- firstVisiblePt
.y
;
6347 node2
= wxRichTextLineList::compatibility_iterator();
6348 node
= wxRichTextObjectList::compatibility_iterator();
6356 node2
= node2
->GetNext();
6360 node
= node
->GetNext();
6364 firstY
= firstVisiblePt
.y
;
6366 lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6368 wxRect
rect(firstVisiblePt
.x
, firstY
, firstVisiblePt
.x
+ clientSize
.x
, lastY
- firstY
);
6369 m_ctrl
->RefreshRect(rect
);
6371 // TODO: we need to make sure that lines are only drawn if in the update region. The rect
6372 // passed to Draw is currently used in different ways (to pass the position the content should
6373 // be drawn at as well as the relevant region).
6377 m_ctrl
->Refresh(false);
6379 if (sendUpdateEvent
)
6380 wxTextCtrl::SendTextUpdatedEvent(m_ctrl
);
6385 /// Replace the buffer paragraphs with the new ones.
6386 void wxRichTextAction::ApplyParagraphs(const wxRichTextParagraphLayoutBox
& fragment
)
6388 wxRichTextObjectList::compatibility_iterator node
= fragment
.GetChildren().GetFirst();
6391 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
6392 wxASSERT (para
!= NULL
);
6394 // We'll replace the existing paragraph by finding the paragraph at this position,
6395 // delete its node data, and setting a copy as the new node data.
6396 // TODO: make more efficient by simply swapping old and new paragraph objects.
6398 wxRichTextParagraph
* existingPara
= m_buffer
->GetParagraphAtPosition(para
->GetRange().GetStart());
6401 wxRichTextObjectList::compatibility_iterator bufferParaNode
= m_buffer
->GetChildren().Find(existingPara
);
6404 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(*para
);
6405 newPara
->SetParent(m_buffer
);
6407 bufferParaNode
->SetData(newPara
);
6409 delete existingPara
;
6413 node
= node
->GetNext();
6420 * This stores beginning and end positions for a range of data.
6423 /// Limit this range to be within 'range'
6424 bool wxRichTextRange::LimitTo(const wxRichTextRange
& range
)
6426 if (m_start
< range
.m_start
)
6427 m_start
= range
.m_start
;
6429 if (m_end
> range
.m_end
)
6430 m_end
= range
.m_end
;
6436 * wxRichTextImage implementation
6437 * This object represents an image.
6440 IMPLEMENT_DYNAMIC_CLASS(wxRichTextImage
, wxRichTextObject
)
6442 wxRichTextImage::wxRichTextImage(const wxImage
& image
, wxRichTextObject
* parent
, wxTextAttr
* charStyle
):
6443 wxRichTextObject(parent
)
6447 SetAttributes(*charStyle
);
6450 wxRichTextImage::wxRichTextImage(const wxRichTextImageBlock
& imageBlock
, wxRichTextObject
* parent
, wxTextAttr
* charStyle
):
6451 wxRichTextObject(parent
)
6453 m_imageBlock
= imageBlock
;
6454 m_imageBlock
.Load(m_image
);
6456 SetAttributes(*charStyle
);
6459 /// Load wxImage from the block
6460 bool wxRichTextImage::LoadFromBlock()
6462 m_imageBlock
.Load(m_image
);
6463 return m_imageBlock
.Ok();
6466 /// Make block from the wxImage
6467 bool wxRichTextImage::MakeBlock()
6469 if (m_imageBlock
.GetImageType() == wxBITMAP_TYPE_ANY
|| m_imageBlock
.GetImageType() == -1)
6470 m_imageBlock
.SetImageType(wxBITMAP_TYPE_PNG
);
6472 m_imageBlock
.MakeImageBlock(m_image
, m_imageBlock
.GetImageType());
6473 return m_imageBlock
.Ok();
6478 bool wxRichTextImage::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int WXUNUSED(descent
), int WXUNUSED(style
))
6480 if (!m_image
.Ok() && m_imageBlock
.Ok())
6486 if (m_image
.Ok() && !m_bitmap
.Ok())
6487 m_bitmap
= wxBitmap(m_image
);
6489 int y
= rect
.y
+ (rect
.height
- m_image
.GetHeight());
6492 dc
.DrawBitmap(m_bitmap
, rect
.x
, y
, true);
6494 if (selectionRange
.Contains(range
.GetStart()))
6496 wxCheckSetBrush(dc
, *wxBLACK_BRUSH
);
6497 wxCheckSetPen(dc
, *wxBLACK_PEN
);
6498 dc
.SetLogicalFunction(wxINVERT
);
6499 dc
.DrawRectangle(rect
);
6500 dc
.SetLogicalFunction(wxCOPY
);
6506 /// Lay the item out
6507 bool wxRichTextImage::Layout(wxDC
& WXUNUSED(dc
), const wxRect
& rect
, int WXUNUSED(style
))
6514 SetCachedSize(wxSize(m_image
.GetWidth(), m_image
.GetHeight()));
6515 SetPosition(rect
.GetPosition());
6521 /// Get/set the object size for the given range. Returns false if the range
6522 /// is invalid for this object.
6523 bool wxRichTextImage::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& WXUNUSED(descent
), wxDC
& WXUNUSED(dc
), int WXUNUSED(flags
), wxPoint
WXUNUSED(position
)) const
6525 if (!range
.IsWithin(GetRange()))
6531 size
.x
= m_image
.GetWidth();
6532 size
.y
= m_image
.GetHeight();
6538 void wxRichTextImage::Copy(const wxRichTextImage
& obj
)
6540 wxRichTextObject::Copy(obj
);
6542 m_image
= obj
.m_image
;
6543 m_imageBlock
= obj
.m_imageBlock
;
6551 /// Compare two attribute objects
6552 bool wxTextAttrEq(const wxTextAttr
& attr1
, const wxTextAttr
& attr2
)
6554 return (attr1
== attr2
);
6557 // Partial equality test taking flags into account
6558 bool wxTextAttrEqPartial(const wxTextAttr
& attr1
, const wxTextAttr
& attr2
, int flags
)
6560 return attr1
.EqPartial(attr2
, flags
);
6564 bool wxRichTextTabsEq(const wxArrayInt
& tabs1
, const wxArrayInt
& tabs2
)
6566 if (tabs1
.GetCount() != tabs2
.GetCount())
6570 for (i
= 0; i
< tabs1
.GetCount(); i
++)
6572 if (tabs1
[i
] != tabs2
[i
])
6578 bool wxRichTextApplyStyle(wxTextAttr
& destStyle
, const wxTextAttr
& style
, wxTextAttr
* compareWith
)
6580 return destStyle
.Apply(style
, compareWith
);
6583 // Remove attributes
6584 bool wxRichTextRemoveStyle(wxTextAttr
& destStyle
, const wxTextAttr
& style
)
6586 return wxTextAttr::RemoveStyle(destStyle
, style
);
6589 /// Combine two bitlists, specifying the bits of interest with separate flags.
6590 bool wxRichTextCombineBitlists(int& valueA
, int valueB
, int& flagsA
, int flagsB
)
6592 return wxTextAttr::CombineBitlists(valueA
, valueB
, flagsA
, flagsB
);
6595 /// Compare two bitlists
6596 bool wxRichTextBitlistsEqPartial(int valueA
, int valueB
, int flags
)
6598 return wxTextAttr::BitlistsEqPartial(valueA
, valueB
, flags
);
6601 /// Split into paragraph and character styles
6602 bool wxRichTextSplitParaCharStyles(const wxTextAttr
& style
, wxTextAttr
& parStyle
, wxTextAttr
& charStyle
)
6604 return wxTextAttr::SplitParaCharStyles(style
, parStyle
, charStyle
);
6607 /// Convert a decimal to Roman numerals
6608 wxString
wxRichTextDecimalToRoman(long n
)
6610 static wxArrayInt decimalNumbers
;
6611 static wxArrayString romanNumbers
;
6616 decimalNumbers
.Clear();
6617 romanNumbers
.Clear();
6618 return wxEmptyString
;
6621 if (decimalNumbers
.GetCount() == 0)
6623 #define wxRichTextAddDecRom(n, r) decimalNumbers.Add(n); romanNumbers.Add(r);
6625 wxRichTextAddDecRom(1000, wxT("M"));
6626 wxRichTextAddDecRom(900, wxT("CM"));
6627 wxRichTextAddDecRom(500, wxT("D"));
6628 wxRichTextAddDecRom(400, wxT("CD"));
6629 wxRichTextAddDecRom(100, wxT("C"));
6630 wxRichTextAddDecRom(90, wxT("XC"));
6631 wxRichTextAddDecRom(50, wxT("L"));
6632 wxRichTextAddDecRom(40, wxT("XL"));
6633 wxRichTextAddDecRom(10, wxT("X"));
6634 wxRichTextAddDecRom(9, wxT("IX"));
6635 wxRichTextAddDecRom(5, wxT("V"));
6636 wxRichTextAddDecRom(4, wxT("IV"));
6637 wxRichTextAddDecRom(1, wxT("I"));
6643 while (n
> 0 && i
< 13)
6645 if (n
>= decimalNumbers
[i
])
6647 n
-= decimalNumbers
[i
];
6648 roman
+= romanNumbers
[i
];
6655 if (roman
.IsEmpty())
6661 * wxRichTextFileHandler
6662 * Base class for file handlers
6665 IMPLEMENT_CLASS(wxRichTextFileHandler
, wxObject
)
6667 #if wxUSE_FFILE && wxUSE_STREAMS
6668 bool wxRichTextFileHandler::LoadFile(wxRichTextBuffer
*buffer
, const wxString
& filename
)
6670 wxFFileInputStream
stream(filename
);
6672 return LoadFile(buffer
, stream
);
6677 bool wxRichTextFileHandler::SaveFile(wxRichTextBuffer
*buffer
, const wxString
& filename
)
6679 wxFFileOutputStream
stream(filename
);
6681 return SaveFile(buffer
, stream
);
6685 #endif // wxUSE_FFILE && wxUSE_STREAMS
6687 /// Can we handle this filename (if using files)? By default, checks the extension.
6688 bool wxRichTextFileHandler::CanHandle(const wxString
& filename
) const
6690 wxString path
, file
, ext
;
6691 wxSplitPath(filename
, & path
, & file
, & ext
);
6693 return (ext
.Lower() == GetExtension());
6697 * wxRichTextTextHandler
6698 * Plain text handler
6701 IMPLEMENT_CLASS(wxRichTextPlainTextHandler
, wxRichTextFileHandler
)
6704 bool wxRichTextPlainTextHandler::DoLoadFile(wxRichTextBuffer
*buffer
, wxInputStream
& stream
)
6712 while (!stream
.Eof())
6714 int ch
= stream
.GetC();
6718 if (ch
== 10 && lastCh
!= 13)
6721 if (ch
> 0 && ch
!= 10)
6728 buffer
->ResetAndClearCommands();
6730 buffer
->AddParagraphs(str
);
6731 buffer
->UpdateRanges();
6736 bool wxRichTextPlainTextHandler::DoSaveFile(wxRichTextBuffer
*buffer
, wxOutputStream
& stream
)
6741 wxString text
= buffer
->GetText();
6743 wxString newLine
= wxRichTextLineBreakChar
;
6744 text
.Replace(newLine
, wxT("\n"));
6746 wxCharBuffer buf
= text
.ToAscii();
6748 stream
.Write((const char*) buf
, text
.length());
6751 #endif // wxUSE_STREAMS
6754 * Stores information about an image, in binary in-memory form
6757 wxRichTextImageBlock::wxRichTextImageBlock()
6762 wxRichTextImageBlock::wxRichTextImageBlock(const wxRichTextImageBlock
& block
):wxObject()
6768 wxRichTextImageBlock::~wxRichTextImageBlock()
6777 void wxRichTextImageBlock::Init()
6784 void wxRichTextImageBlock::Clear()
6793 // Load the original image into a memory block.
6794 // If the image is not a JPEG, we must convert it into a JPEG
6795 // to conserve space.
6796 // If it's not a JPEG we can make use of 'image', already scaled, so we don't have to
6797 // load the image a 2nd time.
6799 bool wxRichTextImageBlock::MakeImageBlock(const wxString
& filename
, int imageType
, wxImage
& image
, bool convertToJPEG
)
6801 m_imageType
= imageType
;
6803 wxString
filenameToRead(filename
);
6804 bool removeFile
= false;
6806 if (imageType
== -1)
6807 return false; // Could not determine image type
6809 if ((imageType
!= wxBITMAP_TYPE_JPEG
) && convertToJPEG
)
6812 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
6816 wxUnusedVar(success
);
6818 image
.SaveFile(tempFile
, wxBITMAP_TYPE_JPEG
);
6819 filenameToRead
= tempFile
;
6822 m_imageType
= wxBITMAP_TYPE_JPEG
;
6825 if (!file
.Open(filenameToRead
))
6828 m_dataSize
= (size_t) file
.Length();
6833 m_data
= ReadBlock(filenameToRead
, m_dataSize
);
6836 wxRemoveFile(filenameToRead
);
6838 return (m_data
!= NULL
);
6841 // Make an image block from the wxImage in the given
6843 bool wxRichTextImageBlock::MakeImageBlock(wxImage
& image
, int imageType
, int quality
)
6845 m_imageType
= imageType
;
6846 image
.SetOption(wxT("quality"), quality
);
6848 if (imageType
== -1)
6849 return false; // Could not determine image type
6852 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
6855 wxUnusedVar(success
);
6857 if (!image
.SaveFile(tempFile
, m_imageType
))
6859 if (wxFileExists(tempFile
))
6860 wxRemoveFile(tempFile
);
6865 if (!file
.Open(tempFile
))
6868 m_dataSize
= (size_t) file
.Length();
6873 m_data
= ReadBlock(tempFile
, m_dataSize
);
6875 wxRemoveFile(tempFile
);
6877 return (m_data
!= NULL
);
6882 bool wxRichTextImageBlock::Write(const wxString
& filename
)
6884 return WriteBlock(filename
, m_data
, m_dataSize
);
6887 void wxRichTextImageBlock::Copy(const wxRichTextImageBlock
& block
)
6889 m_imageType
= block
.m_imageType
;
6895 m_dataSize
= block
.m_dataSize
;
6896 if (m_dataSize
== 0)
6899 m_data
= new unsigned char[m_dataSize
];
6901 for (i
= 0; i
< m_dataSize
; i
++)
6902 m_data
[i
] = block
.m_data
[i
];
6906 void wxRichTextImageBlock::operator=(const wxRichTextImageBlock
& block
)
6911 // Load a wxImage from the block
6912 bool wxRichTextImageBlock::Load(wxImage
& image
)
6917 // Read in the image.
6919 wxMemoryInputStream
mstream(m_data
, m_dataSize
);
6920 bool success
= image
.LoadFile(mstream
, GetImageType());
6923 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
6926 if (!WriteBlock(tempFile
, m_data
, m_dataSize
))
6930 success
= image
.LoadFile(tempFile
, GetImageType());
6931 wxRemoveFile(tempFile
);
6937 // Write data in hex to a stream
6938 bool wxRichTextImageBlock::WriteHex(wxOutputStream
& stream
)
6940 const int bufSize
= 512;
6941 char buf
[bufSize
+1];
6943 int left
= m_dataSize
;
6948 if (left
*2 > bufSize
)
6950 n
= bufSize
; left
-= (bufSize
/2);
6954 n
= left
*2; left
= 0;
6958 for (i
= 0; i
< (n
/2); i
++)
6960 wxDecToHex(m_data
[j
], b
, b
+1);
6965 stream
.Write((const char*) buf
, n
);
6970 // Read data in hex from a stream
6971 bool wxRichTextImageBlock::ReadHex(wxInputStream
& stream
, int length
, int imageType
)
6973 int dataSize
= length
/2;
6979 m_data
= new unsigned char[dataSize
];
6981 for (i
= 0; i
< dataSize
; i
++)
6983 str
[0] = (char)stream
.GetC();
6984 str
[1] = (char)stream
.GetC();
6986 m_data
[i
] = (unsigned char)wxHexToDec(str
);
6989 m_dataSize
= dataSize
;
6990 m_imageType
= imageType
;
6995 // Allocate and read from stream as a block of memory
6996 unsigned char* wxRichTextImageBlock::ReadBlock(wxInputStream
& stream
, size_t size
)
6998 unsigned char* block
= new unsigned char[size
];
7002 stream
.Read(block
, size
);
7007 unsigned char* wxRichTextImageBlock::ReadBlock(const wxString
& filename
, size_t size
)
7009 wxFileInputStream
stream(filename
);
7013 return ReadBlock(stream
, size
);
7016 // Write memory block to stream
7017 bool wxRichTextImageBlock::WriteBlock(wxOutputStream
& stream
, unsigned char* block
, size_t size
)
7019 stream
.Write((void*) block
, size
);
7020 return stream
.IsOk();
7024 // Write memory block to file
7025 bool wxRichTextImageBlock::WriteBlock(const wxString
& filename
, unsigned char* block
, size_t size
)
7027 wxFileOutputStream
outStream(filename
);
7028 if (!outStream
.Ok())
7031 return WriteBlock(outStream
, block
, size
);
7034 // Gets the extension for the block's type
7035 wxString
wxRichTextImageBlock::GetExtension() const
7037 wxImageHandler
* handler
= wxImage::FindHandler(GetImageType());
7039 return handler
->GetExtension();
7041 return wxEmptyString
;
7047 * The data object for a wxRichTextBuffer
7050 const wxChar
*wxRichTextBufferDataObject::ms_richTextBufferFormatId
= wxT("wxShape");
7052 wxRichTextBufferDataObject::wxRichTextBufferDataObject(wxRichTextBuffer
* richTextBuffer
)
7054 m_richTextBuffer
= richTextBuffer
;
7056 // this string should uniquely identify our format, but is otherwise
7058 m_formatRichTextBuffer
.SetId(GetRichTextBufferFormatId());
7060 SetFormat(m_formatRichTextBuffer
);
7063 wxRichTextBufferDataObject::~wxRichTextBufferDataObject()
7065 delete m_richTextBuffer
;
7068 // after a call to this function, the richTextBuffer is owned by the caller and it
7069 // is responsible for deleting it!
7070 wxRichTextBuffer
* wxRichTextBufferDataObject::GetRichTextBuffer()
7072 wxRichTextBuffer
* richTextBuffer
= m_richTextBuffer
;
7073 m_richTextBuffer
= NULL
;
7075 return richTextBuffer
;
7078 wxDataFormat
wxRichTextBufferDataObject::GetPreferredFormat(Direction
WXUNUSED(dir
)) const
7080 return m_formatRichTextBuffer
;
7083 size_t wxRichTextBufferDataObject::GetDataSize() const
7085 if (!m_richTextBuffer
)
7091 wxStringOutputStream
stream(& bufXML
);
7092 if (!m_richTextBuffer
->SaveFile(stream
, wxRICHTEXT_TYPE_XML
))
7094 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
7100 wxCharBuffer buffer
= bufXML
.mb_str(wxConvUTF8
);
7101 return strlen(buffer
) + 1;
7103 return bufXML
.Length()+1;
7107 bool wxRichTextBufferDataObject::GetDataHere(void *pBuf
) const
7109 if (!pBuf
|| !m_richTextBuffer
)
7115 wxStringOutputStream
stream(& bufXML
);
7116 if (!m_richTextBuffer
->SaveFile(stream
, wxRICHTEXT_TYPE_XML
))
7118 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
7124 wxCharBuffer buffer
= bufXML
.mb_str(wxConvUTF8
);
7125 size_t len
= strlen(buffer
);
7126 memcpy((char*) pBuf
, (const char*) buffer
, len
);
7127 ((char*) pBuf
)[len
] = 0;
7129 size_t len
= bufXML
.Length();
7130 memcpy((char*) pBuf
, (const char*) bufXML
.c_str(), len
);
7131 ((char*) pBuf
)[len
] = 0;
7137 bool wxRichTextBufferDataObject::SetData(size_t WXUNUSED(len
), const void *buf
)
7139 delete m_richTextBuffer
;
7140 m_richTextBuffer
= NULL
;
7142 wxString
bufXML((const char*) buf
, wxConvUTF8
);
7144 m_richTextBuffer
= new wxRichTextBuffer
;
7146 wxStringInputStream
stream(bufXML
);
7147 if (!m_richTextBuffer
->LoadFile(stream
, wxRICHTEXT_TYPE_XML
))
7149 wxLogError(wxT("Could not read the buffer from an XML stream.\nYou may have forgotten to add the XML file handler."));
7151 delete m_richTextBuffer
;
7152 m_richTextBuffer
= NULL
;
7164 * wxRichTextFontTable
7165 * Manages quick access to a pool of fonts for rendering rich text
7168 WX_DECLARE_STRING_HASH_MAP_WITH_DECL(wxFont
, wxRichTextFontTableHashMap
, class WXDLLIMPEXP_RICHTEXT
);
7170 class wxRichTextFontTableData
: public wxObjectRefData
7173 wxRichTextFontTableData() {}
7175 wxFont
FindFont(const wxTextAttr
& fontSpec
);
7177 wxRichTextFontTableHashMap m_hashMap
;
7180 wxFont
wxRichTextFontTableData::FindFont(const wxTextAttr
& fontSpec
)
7182 wxString
facename(fontSpec
.GetFontFaceName());
7183 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()));
7184 wxRichTextFontTableHashMap::iterator entry
= m_hashMap
.find(spec
);
7186 if ( entry
== m_hashMap
.end() )
7188 wxFont
font(fontSpec
.GetFontSize(), wxDEFAULT
, fontSpec
.GetFontStyle(), fontSpec
.GetFontWeight(), fontSpec
.GetFontUnderlined(), facename
.c_str());
7189 m_hashMap
[spec
] = font
;
7194 return entry
->second
;
7198 IMPLEMENT_DYNAMIC_CLASS(wxRichTextFontTable
, wxObject
)
7200 wxRichTextFontTable::wxRichTextFontTable()
7202 m_refData
= new wxRichTextFontTableData
;
7203 m_refData
->IncRef();
7206 wxRichTextFontTable::wxRichTextFontTable(const wxRichTextFontTable
& table
)
7211 wxRichTextFontTable::~wxRichTextFontTable()
7216 bool wxRichTextFontTable::operator == (const wxRichTextFontTable
& table
) const
7218 return (m_refData
== table
.m_refData
);
7221 void wxRichTextFontTable::operator= (const wxRichTextFontTable
& table
)
7226 wxFont
wxRichTextFontTable::FindFont(const wxTextAttr
& fontSpec
)
7228 wxRichTextFontTableData
* data
= (wxRichTextFontTableData
*) m_refData
;
7230 return data
->FindFont(fontSpec
);
7235 void wxRichTextFontTable::Clear()
7237 wxRichTextFontTableData
* data
= (wxRichTextFontTableData
*) m_refData
;
7239 data
->m_hashMap
.clear();