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;
55 * This is the base for drawable objects.
58 IMPLEMENT_CLASS(wxRichTextObject
, wxObject
)
60 wxRichTextObject::wxRichTextObject(wxRichTextObject
* parent
)
72 wxRichTextObject::~wxRichTextObject()
76 void wxRichTextObject::Dereference()
84 void wxRichTextObject::Copy(const wxRichTextObject
& obj
)
88 m_dirty
= obj
.m_dirty
;
89 m_range
= obj
.m_range
;
90 m_attributes
= obj
.m_attributes
;
91 m_descent
= obj
.m_descent
;
94 void wxRichTextObject::SetMargins(int margin
)
96 m_leftMargin
= m_rightMargin
= m_topMargin
= m_bottomMargin
= margin
;
99 void wxRichTextObject::SetMargins(int leftMargin
, int rightMargin
, int topMargin
, int bottomMargin
)
101 m_leftMargin
= leftMargin
;
102 m_rightMargin
= rightMargin
;
103 m_topMargin
= topMargin
;
104 m_bottomMargin
= bottomMargin
;
107 // Convert units in tenths of a millimetre to device units
108 int wxRichTextObject::ConvertTenthsMMToPixels(wxDC
& dc
, int units
)
110 int p
= ConvertTenthsMMToPixels(dc
.GetPPI().x
, units
);
113 wxRichTextBuffer
* buffer
= GetBuffer();
115 p
= (int) ((double)p
/ buffer
->GetScale());
119 // Convert units in tenths of a millimetre to device units
120 int wxRichTextObject::ConvertTenthsMMToPixels(int ppi
, int units
)
122 // There are ppi pixels in 254.1 "1/10 mm"
124 double pixels
= ((double) units
* (double)ppi
) / 254.1;
129 /// Dump to output stream for debugging
130 void wxRichTextObject::Dump(wxTextOutputStream
& stream
)
132 stream
<< GetClassInfo()->GetClassName() << wxT("\n");
133 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");
134 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");
137 /// Gets the containing buffer
138 wxRichTextBuffer
* wxRichTextObject::GetBuffer() const
140 const wxRichTextObject
* obj
= this;
141 while (obj
&& !obj
->IsKindOf(CLASSINFO(wxRichTextBuffer
)))
142 obj
= obj
->GetParent();
143 return wxDynamicCast(obj
, wxRichTextBuffer
);
147 * wxRichTextCompositeObject
148 * This is the base for drawable objects.
151 IMPLEMENT_CLASS(wxRichTextCompositeObject
, wxRichTextObject
)
153 wxRichTextCompositeObject::wxRichTextCompositeObject(wxRichTextObject
* parent
):
154 wxRichTextObject(parent
)
158 wxRichTextCompositeObject::~wxRichTextCompositeObject()
163 /// Get the nth child
164 wxRichTextObject
* wxRichTextCompositeObject::GetChild(size_t n
) const
166 wxASSERT ( n
< m_children
.GetCount() );
168 return m_children
.Item(n
)->GetData();
171 /// Append a child, returning the position
172 size_t wxRichTextCompositeObject::AppendChild(wxRichTextObject
* child
)
174 m_children
.Append(child
);
175 child
->SetParent(this);
176 return m_children
.GetCount() - 1;
179 /// Insert the child in front of the given object, or at the beginning
180 bool wxRichTextCompositeObject::InsertChild(wxRichTextObject
* child
, wxRichTextObject
* inFrontOf
)
184 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(inFrontOf
);
185 m_children
.Insert(node
, child
);
188 m_children
.Insert(child
);
189 child
->SetParent(this);
195 bool wxRichTextCompositeObject::RemoveChild(wxRichTextObject
* child
, bool deleteChild
)
197 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(child
);
200 wxRichTextObject
* obj
= node
->GetData();
201 m_children
.Erase(node
);
210 /// Delete all children
211 bool wxRichTextCompositeObject::DeleteChildren()
213 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
216 wxRichTextObjectList::compatibility_iterator oldNode
= node
;
218 wxRichTextObject
* child
= node
->GetData();
219 child
->Dereference(); // Only delete if reference count is zero
221 node
= node
->GetNext();
222 m_children
.Erase(oldNode
);
228 /// Get the child count
229 size_t wxRichTextCompositeObject::GetChildCount() const
231 return m_children
.GetCount();
235 void wxRichTextCompositeObject::Copy(const wxRichTextCompositeObject
& obj
)
237 wxRichTextObject::Copy(obj
);
241 wxRichTextObjectList::compatibility_iterator node
= obj
.m_children
.GetFirst();
244 wxRichTextObject
* child
= node
->GetData();
245 wxRichTextObject
* newChild
= child
->Clone();
246 newChild
->SetParent(this);
247 m_children
.Append(newChild
);
249 node
= node
->GetNext();
253 /// Hit-testing: returns a flag indicating hit test details, plus
254 /// information about position
255 int wxRichTextCompositeObject::HitTest(wxDC
& dc
, const wxPoint
& pt
, long& textPosition
)
257 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
260 wxRichTextObject
* child
= node
->GetData();
262 int ret
= child
->HitTest(dc
, pt
, textPosition
);
263 if (ret
!= wxRICHTEXT_HITTEST_NONE
)
266 node
= node
->GetNext();
269 return wxRICHTEXT_HITTEST_NONE
;
272 /// Finds the absolute position and row height for the given character position
273 bool wxRichTextCompositeObject::FindPosition(wxDC
& dc
, long index
, wxPoint
& pt
, int* height
, bool forceLineStart
)
275 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
278 wxRichTextObject
* child
= node
->GetData();
280 if (child
->FindPosition(dc
, index
, pt
, height
, forceLineStart
))
283 node
= node
->GetNext();
290 void wxRichTextCompositeObject::CalculateRange(long start
, long& end
)
292 long current
= start
;
293 long lastEnd
= current
;
295 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
298 wxRichTextObject
* child
= node
->GetData();
301 child
->CalculateRange(current
, childEnd
);
304 current
= childEnd
+ 1;
306 node
= node
->GetNext();
311 // An object with no children has zero length
312 if (m_children
.GetCount() == 0)
315 m_range
.SetRange(start
, end
);
318 /// Delete range from layout.
319 bool wxRichTextCompositeObject::DeleteRange(const wxRichTextRange
& range
)
321 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
325 wxRichTextObject
* obj
= (wxRichTextObject
*) node
->GetData();
326 wxRichTextObjectList::compatibility_iterator next
= node
->GetNext();
328 // Delete the range in each paragraph
330 // When a chunk has been deleted, internally the content does not
331 // now match the ranges.
332 // However, so long as deletion is not done on the same object twice this is OK.
333 // If you may delete content from the same object twice, recalculate
334 // the ranges inbetween DeleteRange calls by calling CalculateRanges, and
335 // adjust the range you're deleting accordingly.
337 if (!obj
->GetRange().IsOutside(range
))
339 obj
->DeleteRange(range
);
341 // Delete an empty object, or paragraph within this range.
342 if (obj
->IsEmpty() ||
343 (range
.GetStart() <= obj
->GetRange().GetStart() && range
.GetEnd() >= obj
->GetRange().GetEnd()))
345 // An empty paragraph has length 1, so won't be deleted unless the
346 // whole range is deleted.
347 RemoveChild(obj
, true);
357 /// Get any text in this object for the given range
358 wxString
wxRichTextCompositeObject::GetTextForRange(const wxRichTextRange
& range
) const
361 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
364 wxRichTextObject
* child
= node
->GetData();
365 wxRichTextRange childRange
= range
;
366 if (!child
->GetRange().IsOutside(range
))
368 childRange
.LimitTo(child
->GetRange());
370 wxString childText
= child
->GetTextForRange(childRange
);
374 node
= node
->GetNext();
380 /// Recursively merge all pieces that can be merged.
381 bool wxRichTextCompositeObject::Defragment()
383 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
386 wxRichTextObject
* child
= node
->GetData();
387 wxRichTextCompositeObject
* composite
= wxDynamicCast(child
, wxRichTextCompositeObject
);
389 composite
->Defragment();
393 wxRichTextObject
* nextChild
= node
->GetNext()->GetData();
394 if (child
->CanMerge(nextChild
) && child
->Merge(nextChild
))
396 nextChild
->Dereference();
397 m_children
.Erase(node
->GetNext());
399 // Don't set node -- we'll see if we can merge again with the next
403 node
= node
->GetNext();
406 node
= node
->GetNext();
412 /// Dump to output stream for debugging
413 void wxRichTextCompositeObject::Dump(wxTextOutputStream
& stream
)
415 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
418 wxRichTextObject
* child
= node
->GetData();
420 node
= node
->GetNext();
427 * This defines a 2D space to lay out objects
430 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBox
, wxRichTextCompositeObject
)
432 wxRichTextBox::wxRichTextBox(wxRichTextObject
* parent
):
433 wxRichTextCompositeObject(parent
)
438 bool wxRichTextBox::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& WXUNUSED(rect
), int descent
, int style
)
440 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
443 wxRichTextObject
* child
= node
->GetData();
445 wxRect childRect
= wxRect(child
->GetPosition(), child
->GetCachedSize());
446 child
->Draw(dc
, range
, selectionRange
, childRect
, descent
, style
);
448 node
= node
->GetNext();
454 bool wxRichTextBox::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
456 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
459 wxRichTextObject
* child
= node
->GetData();
460 child
->Layout(dc
, rect
, style
);
462 node
= node
->GetNext();
468 /// Get/set the size for the given range. Assume only has one child.
469 bool wxRichTextBox::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
) const
471 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
474 wxRichTextObject
* child
= node
->GetData();
475 return child
->GetRangeSize(range
, size
, descent
, dc
, flags
, position
);
482 void wxRichTextBox::Copy(const wxRichTextBox
& obj
)
484 wxRichTextCompositeObject::Copy(obj
);
489 * wxRichTextParagraphLayoutBox
490 * This box knows how to lay out paragraphs.
493 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraphLayoutBox
, wxRichTextBox
)
495 wxRichTextParagraphLayoutBox::wxRichTextParagraphLayoutBox(wxRichTextObject
* parent
):
496 wxRichTextBox(parent
)
501 /// Initialize the object.
502 void wxRichTextParagraphLayoutBox::Init()
506 // For now, assume is the only box and has no initial size.
507 m_range
= wxRichTextRange(0, -1);
509 m_invalidRange
.SetRange(-1, -1);
514 m_partialParagraph
= false;
518 bool wxRichTextParagraphLayoutBox::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int descent
, int style
)
520 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
523 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
524 wxASSERT (child
!= NULL
);
526 if (child
&& !child
->GetRange().IsOutside(range
))
528 wxRect
childRect(child
->GetPosition(), child
->GetCachedSize());
530 if (((style
& wxRICHTEXT_DRAW_IGNORE_CACHE
) == 0) && childRect
.GetTop() > rect
.GetBottom())
535 else if (((style
& wxRICHTEXT_DRAW_IGNORE_CACHE
) == 0) && childRect
.GetBottom() < rect
.GetTop())
540 child
->Draw(dc
, range
, selectionRange
, childRect
, descent
, style
);
543 node
= node
->GetNext();
549 bool wxRichTextParagraphLayoutBox::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
551 wxRect availableSpace
;
552 bool formatRect
= (style
& wxRICHTEXT_LAYOUT_SPECIFIED_RECT
) == wxRICHTEXT_LAYOUT_SPECIFIED_RECT
;
554 // If only laying out a specific area, the passed rect has a different meaning:
555 // the visible part of the buffer. This is used in wxRichTextCtrl::OnSize,
556 // so that during a size, only the visible part will be relaid out, or
557 // it would take too long causing flicker. As an approximation, we assume that
558 // everything up to the start of the visible area is laid out correctly.
561 availableSpace
= wxRect(0 + m_leftMargin
,
563 rect
.width
- m_leftMargin
- m_rightMargin
,
566 // Invalidate the part of the buffer from the first visible line
567 // to the end. If other parts of the buffer are currently invalid,
568 // then they too will be taken into account if they are above
569 // the visible point.
571 wxRichTextLine
* line
= GetLineAtYPosition(rect
.y
);
573 startPos
= line
->GetAbsoluteRange().GetStart();
575 Invalidate(wxRichTextRange(startPos
, GetRange().GetEnd()));
578 availableSpace
= wxRect(rect
.x
+ m_leftMargin
,
579 rect
.y
+ m_topMargin
,
580 rect
.width
- m_leftMargin
- m_rightMargin
,
581 rect
.height
- m_topMargin
- m_bottomMargin
);
585 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
587 bool layoutAll
= true;
589 // Get invalid range, rounding to paragraph start/end.
590 wxRichTextRange invalidRange
= GetInvalidRange(true);
592 if (invalidRange
== wxRICHTEXT_NONE
&& !formatRect
)
595 if (invalidRange
== wxRICHTEXT_ALL
)
597 else // If we know what range is affected, start laying out from that point on.
598 if (invalidRange
.GetStart() > GetRange().GetStart())
600 wxRichTextParagraph
* firstParagraph
= GetParagraphAtPosition(invalidRange
.GetStart());
603 wxRichTextObjectList::compatibility_iterator firstNode
= m_children
.Find(firstParagraph
);
604 wxRichTextObjectList::compatibility_iterator previousNode
;
606 previousNode
= firstNode
->GetPrevious();
607 if (firstNode
&& previousNode
)
609 wxRichTextParagraph
* previousParagraph
= wxDynamicCast(previousNode
->GetData(), wxRichTextParagraph
);
610 availableSpace
.y
= previousParagraph
->GetPosition().y
+ previousParagraph
->GetCachedSize().y
;
612 // Now we're going to start iterating from the first affected paragraph.
620 // A way to force speedy rest-of-buffer layout (the 'else' below)
621 bool forceQuickLayout
= false;
625 // Assume this box only contains paragraphs
627 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
628 wxCHECK_MSG( child
, false, _T("Unknown object in layout") );
630 // TODO: what if the child hasn't been laid out (e.g. involved in Undo) but still has 'old' lines
631 if ( !forceQuickLayout
&&
633 child
->GetLines().IsEmpty() ||
634 !child
->GetRange().IsOutside(invalidRange
)) )
636 child
->Layout(dc
, availableSpace
, style
);
638 // Layout must set the cached size
639 availableSpace
.y
+= child
->GetCachedSize().y
;
640 maxWidth
= wxMax(maxWidth
, child
->GetCachedSize().x
);
642 // If we're just formatting the visible part of the buffer,
643 // and we're now past the bottom of the window, start quick
645 if (formatRect
&& child
->GetPosition().y
> rect
.GetBottom())
646 forceQuickLayout
= true;
650 // We're outside the immediately affected range, so now let's just
651 // move everything up or down. This assumes that all the children have previously
652 // been laid out and have wrapped line lists associated with them.
653 // TODO: check all paragraphs before the affected range.
655 int inc
= availableSpace
.y
- child
->GetPosition().y
;
659 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
662 if (child
->GetLines().GetCount() == 0)
663 child
->Layout(dc
, availableSpace
, style
);
665 child
->SetPosition(wxPoint(child
->GetPosition().x
, child
->GetPosition().y
+ inc
));
667 availableSpace
.y
+= child
->GetCachedSize().y
;
668 maxWidth
= wxMax(maxWidth
, child
->GetCachedSize().x
);
671 node
= node
->GetNext();
676 node
= node
->GetNext();
679 SetCachedSize(wxSize(maxWidth
, availableSpace
.y
));
682 m_invalidRange
= wxRICHTEXT_NONE
;
688 void wxRichTextParagraphLayoutBox::Copy(const wxRichTextParagraphLayoutBox
& obj
)
690 wxRichTextBox::Copy(obj
);
692 m_partialParagraph
= obj
.m_partialParagraph
;
693 m_defaultAttributes
= obj
.m_defaultAttributes
;
696 /// Get/set the size for the given range.
697 bool wxRichTextParagraphLayoutBox::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
) const
701 wxRichTextObjectList::compatibility_iterator startPara
= wxRichTextObjectList::compatibility_iterator();
702 wxRichTextObjectList::compatibility_iterator endPara
= wxRichTextObjectList::compatibility_iterator();
704 // First find the first paragraph whose starting position is within the range.
705 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
708 // child is a paragraph
709 wxRichTextObject
* child
= node
->GetData();
710 const wxRichTextRange
& r
= child
->GetRange();
712 if (r
.GetStart() <= range
.GetStart() && r
.GetEnd() >= range
.GetStart())
718 node
= node
->GetNext();
721 // Next find the last paragraph containing part of the range
722 node
= m_children
.GetFirst();
725 // child is a paragraph
726 wxRichTextObject
* child
= node
->GetData();
727 const wxRichTextRange
& r
= child
->GetRange();
729 if (r
.GetStart() <= range
.GetEnd() && r
.GetEnd() >= range
.GetEnd())
735 node
= node
->GetNext();
738 if (!startPara
|| !endPara
)
741 // Now we can add up the sizes
742 for (node
= startPara
; node
; node
= node
->GetNext())
744 // child is a paragraph
745 wxRichTextObject
* child
= node
->GetData();
746 const wxRichTextRange
& childRange
= child
->GetRange();
747 wxRichTextRange rangeToFind
= range
;
748 rangeToFind
.LimitTo(childRange
);
752 int childDescent
= 0;
753 child
->GetRangeSize(rangeToFind
, childSize
, childDescent
, dc
, flags
, position
);
755 descent
= wxMax(childDescent
, descent
);
757 sz
.x
= wxMax(sz
.x
, childSize
.x
);
769 /// Get the paragraph at the given position
770 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphAtPosition(long pos
, bool caretPosition
) const
775 // First find the first paragraph whose starting position is within the range.
776 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
779 // child is a paragraph
780 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
781 wxASSERT (child
!= NULL
);
783 // Return first child in buffer if position is -1
787 if (child
->GetRange().Contains(pos
))
790 node
= node
->GetNext();
795 /// Get the line at the given position
796 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineAtPosition(long pos
, bool caretPosition
) const
801 // First find the first paragraph whose starting position is within the range.
802 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
805 // child is a paragraph
806 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
807 wxASSERT (child
!= NULL
);
809 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
812 wxRichTextLine
* line
= node2
->GetData();
814 wxRichTextRange range
= line
->GetAbsoluteRange();
816 if (range
.Contains(pos
) ||
818 // If the position is end-of-paragraph, then return the last line of
820 (range
.GetEnd() == child
->GetRange().GetEnd()-1) && (pos
== child
->GetRange().GetEnd()))
823 node2
= node2
->GetNext();
826 node
= node
->GetNext();
829 int lineCount
= GetLineCount();
831 return GetLineForVisibleLineNumber(lineCount
-1);
836 /// Get the line at the given y pixel position, or the last line.
837 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineAtYPosition(int y
) const
839 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
842 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
843 wxASSERT (child
!= NULL
);
845 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
848 wxRichTextLine
* line
= node2
->GetData();
850 wxRect
rect(line
->GetRect());
852 if (y
<= rect
.GetBottom())
855 node2
= node2
->GetNext();
858 node
= node
->GetNext();
862 int lineCount
= GetLineCount();
864 return GetLineForVisibleLineNumber(lineCount
-1);
869 /// Get the number of visible lines
870 int wxRichTextParagraphLayoutBox::GetLineCount() const
874 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
877 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
878 wxASSERT (child
!= NULL
);
880 count
+= child
->GetLines().GetCount();
881 node
= node
->GetNext();
887 /// Get the paragraph for a given line
888 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphForLine(wxRichTextLine
* line
) const
890 return GetParagraphAtPosition(line
->GetAbsoluteRange().GetStart());
893 /// Get the line size at the given position
894 wxSize
wxRichTextParagraphLayoutBox::GetLineSizeAtPosition(long pos
, bool caretPosition
) const
896 wxRichTextLine
* line
= GetLineAtPosition(pos
, caretPosition
);
899 return line
->GetSize();
906 /// Convenience function to add a paragraph of text
907 wxRichTextRange
wxRichTextParagraphLayoutBox::AddParagraph(const wxString
& text
, wxTextAttr
* paraStyle
)
909 // Don't use the base style, just the default style, and the base style will
910 // be combined at display time.
911 // Divide into paragraph and character styles.
913 wxTextAttr defaultCharStyle
;
914 wxTextAttr defaultParaStyle
;
916 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
917 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
918 wxTextAttr
* cStyle
= & defaultCharStyle
;
920 wxRichTextParagraph
* para
= new wxRichTextParagraph(text
, this, pStyle
, cStyle
);
927 return para
->GetRange();
930 /// Adds multiple paragraphs, based on newlines.
931 wxRichTextRange
wxRichTextParagraphLayoutBox::AddParagraphs(const wxString
& text
, wxTextAttr
* paraStyle
)
933 // Don't use the base style, just the default style, and the base style will
934 // be combined at display time.
935 // Divide into paragraph and character styles.
937 wxTextAttr defaultCharStyle
;
938 wxTextAttr defaultParaStyle
;
939 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
941 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
942 wxTextAttr
* cStyle
= & defaultCharStyle
;
944 wxRichTextParagraph
* firstPara
= NULL
;
945 wxRichTextParagraph
* lastPara
= NULL
;
947 wxRichTextRange
range(-1, -1);
950 size_t len
= text
.length();
952 wxRichTextParagraph
* para
= new wxRichTextParagraph(wxEmptyString
, this, pStyle
, cStyle
);
962 if (ch
== wxT('\n') || ch
== wxT('\r'))
964 wxRichTextPlainText
* plainText
= (wxRichTextPlainText
*) para
->GetChildren().GetFirst()->GetData();
965 plainText
->SetText(line
);
967 para
= new wxRichTextParagraph(wxEmptyString
, this, pStyle
, cStyle
);
972 line
= wxEmptyString
;
982 wxRichTextPlainText
* plainText
= (wxRichTextPlainText
*) para
->GetChildren().GetFirst()->GetData();
983 plainText
->SetText(line
);
990 return wxRichTextRange(firstPara
->GetRange().GetStart(), lastPara
->GetRange().GetEnd());
993 /// Convenience function to add an image
994 wxRichTextRange
wxRichTextParagraphLayoutBox::AddImage(const wxImage
& image
, wxTextAttr
* paraStyle
)
996 // Don't use the base style, just the default style, and the base style will
997 // be combined at display time.
998 // Divide into paragraph and character styles.
1000 wxTextAttr defaultCharStyle
;
1001 wxTextAttr defaultParaStyle
;
1002 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
1004 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
1005 wxTextAttr
* cStyle
= & defaultCharStyle
;
1007 wxRichTextParagraph
* para
= new wxRichTextParagraph(this, pStyle
);
1009 para
->AppendChild(new wxRichTextImage(image
, this, cStyle
));
1014 return para
->GetRange();
1018 /// Insert fragment into this box at the given position. If partialParagraph is true,
1019 /// it is assumed that the last (or only) paragraph is just a piece of data with no paragraph
1022 bool wxRichTextParagraphLayoutBox::InsertFragment(long position
, wxRichTextParagraphLayoutBox
& fragment
)
1026 // First, find the first paragraph whose starting position is within the range.
1027 wxRichTextParagraph
* para
= GetParagraphAtPosition(position
);
1030 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(para
);
1032 // Now split at this position, returning the object to insert the new
1033 // ones in front of.
1034 wxRichTextObject
* nextObject
= para
->SplitAt(position
);
1036 // Special case: partial paragraph, just one paragraph. Might be a small amount of
1037 // text, for example, so let's optimize.
1039 if (fragment
.GetPartialParagraph() && fragment
.GetChildren().GetCount() == 1)
1041 // Add the first para to this para...
1042 wxRichTextObjectList::compatibility_iterator firstParaNode
= fragment
.GetChildren().GetFirst();
1046 // Iterate through the fragment paragraph inserting the content into this paragraph.
1047 wxRichTextParagraph
* firstPara
= wxDynamicCast(firstParaNode
->GetData(), wxRichTextParagraph
);
1048 wxASSERT (firstPara
!= NULL
);
1050 // Apply the new paragraph attributes to the existing paragraph
1051 wxTextAttr
attr(para
->GetAttributes());
1052 wxRichTextApplyStyle(attr
, firstPara
->GetAttributes());
1053 para
->SetAttributes(attr
);
1055 wxRichTextObjectList::compatibility_iterator objectNode
= firstPara
->GetChildren().GetFirst();
1058 wxRichTextObject
* newObj
= objectNode
->GetData()->Clone();
1063 para
->AppendChild(newObj
);
1067 // Insert before nextObject
1068 para
->InsertChild(newObj
, nextObject
);
1071 objectNode
= objectNode
->GetNext();
1078 // Procedure for inserting a fragment consisting of a number of
1081 // 1. Remove and save the content that's after the insertion point, for adding
1082 // back once we've added the fragment.
1083 // 2. Add the content from the first fragment paragraph to the current
1085 // 3. Add remaining fragment paragraphs after the current paragraph.
1086 // 4. Add back the saved content from the first paragraph. If partialParagraph
1087 // is true, add it to the last paragraph added and not a new one.
1089 // 1. Remove and save objects after split point.
1090 wxList savedObjects
;
1092 para
->MoveToList(nextObject
, savedObjects
);
1094 // 2. Add the content from the 1st fragment paragraph.
1095 wxRichTextObjectList::compatibility_iterator firstParaNode
= fragment
.GetChildren().GetFirst();
1099 wxRichTextParagraph
* firstPara
= wxDynamicCast(firstParaNode
->GetData(), wxRichTextParagraph
);
1100 wxASSERT(firstPara
!= NULL
);
1102 wxRichTextObjectList::compatibility_iterator objectNode
= firstPara
->GetChildren().GetFirst();
1105 wxRichTextObject
* newObj
= objectNode
->GetData()->Clone();
1108 para
->AppendChild(newObj
);
1110 objectNode
= objectNode
->GetNext();
1113 // 3. Add remaining fragment paragraphs after the current paragraph.
1114 wxRichTextObjectList::compatibility_iterator nextParagraphNode
= node
->GetNext();
1115 wxRichTextObject
* nextParagraph
= NULL
;
1116 if (nextParagraphNode
)
1117 nextParagraph
= nextParagraphNode
->GetData();
1119 wxRichTextObjectList::compatibility_iterator i
= fragment
.GetChildren().GetFirst()->GetNext();
1120 wxRichTextParagraph
* finalPara
= para
;
1122 // If there was only one paragraph, we need to insert a new one.
1125 finalPara
= new wxRichTextParagraph
;
1127 // TODO: These attributes should come from the subsequent paragraph
1128 // when originally deleted, since the subsequent para takes on
1129 // the previous para's attributes.
1130 finalPara
->SetAttributes(firstPara
->GetAttributes());
1133 InsertChild(finalPara
, nextParagraph
);
1135 AppendChild(finalPara
);
1139 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1140 wxASSERT( para
!= NULL
);
1142 finalPara
= (wxRichTextParagraph
*) para
->Clone();
1145 InsertChild(finalPara
, nextParagraph
);
1147 AppendChild(finalPara
);
1152 // 4. Add back the remaining content.
1155 finalPara
->MoveFromList(savedObjects
);
1157 // Ensure there's at least one object
1158 if (finalPara
->GetChildCount() == 0)
1160 wxRichTextPlainText
* text
= new wxRichTextPlainText(wxEmptyString
);
1162 finalPara
->AppendChild(text
);
1172 wxRichTextObjectList::compatibility_iterator i
= fragment
.GetChildren().GetFirst();
1175 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1176 wxASSERT( para
!= NULL
);
1178 AppendChild(para
->Clone());
1187 /// Make a copy of the fragment corresponding to the given range, putting it in 'fragment'.
1188 /// If there was an incomplete paragraph at the end, partialParagraph is set to true.
1189 bool wxRichTextParagraphLayoutBox::CopyFragment(const wxRichTextRange
& range
, wxRichTextParagraphLayoutBox
& fragment
)
1191 wxRichTextObjectList::compatibility_iterator i
= GetChildren().GetFirst();
1194 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1195 wxASSERT( para
!= NULL
);
1197 if (!para
->GetRange().IsOutside(range
))
1199 fragment
.AppendChild(para
->Clone());
1204 // Now top and tail the first and last paragraphs in our new fragment (which might be the same).
1205 if (!fragment
.IsEmpty())
1207 wxRichTextRange
topTailRange(range
);
1209 wxRichTextParagraph
* firstPara
= wxDynamicCast(fragment
.GetChildren().GetFirst()->GetData(), wxRichTextParagraph
);
1210 wxASSERT( firstPara
!= NULL
);
1212 // Chop off the start of the paragraph
1213 if (topTailRange
.GetStart() > firstPara
->GetRange().GetStart())
1215 wxRichTextRange
r(firstPara
->GetRange().GetStart(), topTailRange
.GetStart()-1);
1216 firstPara
->DeleteRange(r
);
1218 // Make sure the numbering is correct
1220 fragment
.CalculateRange(firstPara
->GetRange().GetStart(), end
);
1222 // Now, we've deleted some positions, so adjust the range
1224 topTailRange
.SetEnd(topTailRange
.GetEnd() - r
.GetLength());
1227 wxRichTextParagraph
* lastPara
= wxDynamicCast(fragment
.GetChildren().GetLast()->GetData(), wxRichTextParagraph
);
1228 wxASSERT( lastPara
!= NULL
);
1230 if (topTailRange
.GetEnd() < (lastPara
->GetRange().GetEnd()-1))
1232 wxRichTextRange
r(topTailRange
.GetEnd()+1, lastPara
->GetRange().GetEnd()-1); /* -1 since actual text ends 1 position before end of para marker */
1233 lastPara
->DeleteRange(r
);
1235 // Make sure the numbering is correct
1237 fragment
.CalculateRange(firstPara
->GetRange().GetStart(), end
);
1239 // We only have part of a paragraph at the end
1240 fragment
.SetPartialParagraph(true);
1244 if (topTailRange
.GetEnd() == (lastPara
->GetRange().GetEnd() - 1))
1245 // We have a partial paragraph (don't save last new paragraph marker)
1246 fragment
.SetPartialParagraph(true);
1248 // We have a complete paragraph
1249 fragment
.SetPartialParagraph(false);
1256 /// Given a position, get the number of the visible line (potentially many to a paragraph),
1257 /// starting from zero at the start of the buffer.
1258 long wxRichTextParagraphLayoutBox::GetVisibleLineNumber(long pos
, bool caretPosition
, bool startOfLine
) const
1265 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1268 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1269 wxASSERT( child
!= NULL
);
1271 if (child
->GetRange().Contains(pos
))
1273 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
1276 wxRichTextLine
* line
= node2
->GetData();
1277 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
1279 if (lineRange
.Contains(pos
))
1281 // If the caret is displayed at the end of the previous wrapped line,
1282 // we want to return the line it's _displayed_ at (not the actual line
1283 // containing the position).
1284 if (lineRange
.GetStart() == pos
&& !startOfLine
&& child
->GetRange().GetStart() != pos
)
1285 return lineCount
- 1;
1292 node2
= node2
->GetNext();
1294 // If we didn't find it in the lines, it must be
1295 // the last position of the paragraph. So return the last line.
1299 lineCount
+= child
->GetLines().GetCount();
1301 node
= node
->GetNext();
1308 /// Given a line number, get the corresponding wxRichTextLine object.
1309 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineForVisibleLineNumber(long lineNumber
) const
1313 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1316 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1317 wxASSERT(child
!= NULL
);
1319 if (lineNumber
< (int) (child
->GetLines().GetCount() + lineCount
))
1321 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
1324 wxRichTextLine
* line
= node2
->GetData();
1326 if (lineCount
== lineNumber
)
1331 node2
= node2
->GetNext();
1335 lineCount
+= child
->GetLines().GetCount();
1337 node
= node
->GetNext();
1344 /// Delete range from layout.
1345 bool wxRichTextParagraphLayoutBox::DeleteRange(const wxRichTextRange
& range
)
1347 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1351 wxRichTextParagraph
* obj
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1352 wxASSERT (obj
!= NULL
);
1354 wxRichTextObjectList::compatibility_iterator next
= node
->GetNext();
1356 // Delete the range in each paragraph
1358 if (!obj
->GetRange().IsOutside(range
))
1360 // Deletes the content of this object within the given range
1361 obj
->DeleteRange(range
);
1363 // If the whole paragraph is within the range to delete,
1364 // delete the whole thing.
1365 if (range
.GetStart() <= obj
->GetRange().GetStart() && range
.GetEnd() >= obj
->GetRange().GetEnd())
1367 // Delete the whole object
1368 RemoveChild(obj
, true);
1370 // If the range includes the paragraph end, we need to join this
1371 // and the next paragraph.
1372 else if (range
.Contains(obj
->GetRange().GetEnd()))
1374 // We need to move the objects from the next paragraph
1375 // to this paragraph
1379 wxRichTextParagraph
* nextParagraph
= wxDynamicCast(next
->GetData(), wxRichTextParagraph
);
1380 next
= next
->GetNext();
1383 // Delete the stuff we need to delete
1384 nextParagraph
->DeleteRange(range
);
1386 // Move the objects to the previous para
1387 wxRichTextObjectList::compatibility_iterator node1
= nextParagraph
->GetChildren().GetFirst();
1391 wxRichTextObject
* obj1
= node1
->GetData();
1393 // If the object is empty, optimise it out
1394 if (obj1
->IsEmpty())
1400 obj
->AppendChild(obj1
);
1403 wxRichTextObjectList::compatibility_iterator next1
= node1
->GetNext();
1404 nextParagraph
->GetChildren().Erase(node1
);
1409 // Delete the paragraph
1410 RemoveChild(nextParagraph
, true);
1424 /// Get any text in this object for the given range
1425 wxString
wxRichTextParagraphLayoutBox::GetTextForRange(const wxRichTextRange
& range
) const
1429 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1432 wxRichTextObject
* child
= node
->GetData();
1433 if (!child
->GetRange().IsOutside(range
))
1435 wxRichTextRange childRange
= range
;
1436 childRange
.LimitTo(child
->GetRange());
1438 wxString childText
= child
->GetTextForRange(childRange
);
1442 if ((childRange
.GetEnd() == child
->GetRange().GetEnd()) && node
->GetNext())
1447 node
= node
->GetNext();
1453 /// Get all the text
1454 wxString
wxRichTextParagraphLayoutBox::GetText() const
1456 return GetTextForRange(GetRange());
1459 /// Get the paragraph by number
1460 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphAtLine(long paragraphNumber
) const
1462 if ((size_t) paragraphNumber
>= GetChildCount())
1465 return (wxRichTextParagraph
*) GetChild((size_t) paragraphNumber
);
1468 /// Get the length of the paragraph
1469 int wxRichTextParagraphLayoutBox::GetParagraphLength(long paragraphNumber
) const
1471 wxRichTextParagraph
* para
= GetParagraphAtLine(paragraphNumber
);
1473 return para
->GetRange().GetLength() - 1; // don't include newline
1478 /// Get the text of the paragraph
1479 wxString
wxRichTextParagraphLayoutBox::GetParagraphText(long paragraphNumber
) const
1481 wxRichTextParagraph
* para
= GetParagraphAtLine(paragraphNumber
);
1483 return para
->GetTextForRange(para
->GetRange());
1485 return wxEmptyString
;
1488 /// Convert zero-based line column and paragraph number to a position.
1489 long wxRichTextParagraphLayoutBox::XYToPosition(long x
, long y
) const
1491 wxRichTextParagraph
* para
= GetParagraphAtLine(y
);
1494 return para
->GetRange().GetStart() + x
;
1500 /// Convert zero-based position to line column and paragraph number
1501 bool wxRichTextParagraphLayoutBox::PositionToXY(long pos
, long* x
, long* y
) const
1503 wxRichTextParagraph
* para
= GetParagraphAtPosition(pos
);
1507 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1510 wxRichTextObject
* child
= node
->GetData();
1514 node
= node
->GetNext();
1518 *x
= pos
- para
->GetRange().GetStart();
1526 /// Get the leaf object in a paragraph at this position.
1527 /// Given a line number, get the corresponding wxRichTextLine object.
1528 wxRichTextObject
* wxRichTextParagraphLayoutBox::GetLeafObjectAtPosition(long position
) const
1530 wxRichTextParagraph
* para
= GetParagraphAtPosition(position
);
1533 wxRichTextObjectList::compatibility_iterator node
= para
->GetChildren().GetFirst();
1537 wxRichTextObject
* child
= node
->GetData();
1538 if (child
->GetRange().Contains(position
))
1541 node
= node
->GetNext();
1543 if (position
== para
->GetRange().GetEnd() && para
->GetChildCount() > 0)
1544 return para
->GetChildren().GetLast()->GetData();
1549 /// Set character or paragraph text attributes: apply character styles only to immediate text nodes
1550 bool wxRichTextParagraphLayoutBox::SetStyle(const wxRichTextRange
& range
, const wxTextAttr
& style
, int flags
)
1552 bool characterStyle
= false;
1553 bool paragraphStyle
= false;
1555 if (style
.IsCharacterStyle())
1556 characterStyle
= true;
1557 if (style
.IsParagraphStyle())
1558 paragraphStyle
= true;
1560 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
1561 bool applyMinimal
= ((flags
& wxRICHTEXT_SETSTYLE_OPTIMIZE
) != 0);
1562 bool parasOnly
= ((flags
& wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY
) != 0);
1563 bool charactersOnly
= ((flags
& wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY
) != 0);
1564 bool resetExistingStyle
= ((flags
& wxRICHTEXT_SETSTYLE_RESET
) != 0);
1565 bool removeStyle
= ((flags
& wxRICHTEXT_SETSTYLE_REMOVE
) != 0);
1567 // Apply paragraph style first, if any
1568 wxTextAttr
wholeStyle(style
);
1570 if (!removeStyle
&& wholeStyle
.HasParagraphStyleName() && GetStyleSheet())
1572 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(wholeStyle
.GetParagraphStyleName());
1574 wxRichTextApplyStyle(wholeStyle
, def
->GetStyleMergedWithBase(GetStyleSheet()));
1577 // Limit the attributes to be set to the content to only character attributes.
1578 wxTextAttr
characterAttributes(wholeStyle
);
1579 characterAttributes
.SetFlags(characterAttributes
.GetFlags() & (wxTEXT_ATTR_CHARACTER
));
1581 if (!removeStyle
&& characterAttributes
.HasCharacterStyleName() && GetStyleSheet())
1583 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterAttributes
.GetCharacterStyleName());
1585 wxRichTextApplyStyle(characterAttributes
, def
->GetStyleMergedWithBase(GetStyleSheet()));
1588 // If we are associated with a control, make undoable; otherwise, apply immediately
1591 bool haveControl
= (GetRichTextCtrl() != NULL
);
1593 wxRichTextAction
* action
= NULL
;
1595 if (haveControl
&& withUndo
)
1597 action
= new wxRichTextAction(NULL
, _("Change Style"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
1598 action
->SetRange(range
);
1599 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
1602 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1605 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1606 wxASSERT (para
!= NULL
);
1608 if (para
&& para
->GetChildCount() > 0)
1610 // Stop searching if we're beyond the range of interest
1611 if (para
->GetRange().GetStart() > range
.GetEnd())
1614 if (!para
->GetRange().IsOutside(range
))
1616 // We'll be using a copy of the paragraph to make style changes,
1617 // not updating the buffer directly.
1618 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
1620 if (haveControl
&& withUndo
)
1622 newPara
= new wxRichTextParagraph(*para
);
1623 action
->GetNewParagraphs().AppendChild(newPara
);
1625 // Also store the old ones for Undo
1626 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
1631 // If we're specifying paragraphs only, then we really mean character formatting
1632 // to be included in the paragraph style
1633 if ((paragraphStyle
|| parasOnly
) && !charactersOnly
)
1637 // Removes the given style from the paragraph
1638 wxRichTextRemoveStyle(newPara
->GetAttributes(), style
);
1640 else if (resetExistingStyle
)
1641 newPara
->GetAttributes() = wholeStyle
;
1646 // Only apply attributes that will make a difference to the combined
1647 // style as seen on the display
1648 wxTextAttr
combinedAttr(para
->GetCombinedAttributes());
1649 wxRichTextApplyStyle(newPara
->GetAttributes(), wholeStyle
, & combinedAttr
);
1652 wxRichTextApplyStyle(newPara
->GetAttributes(), wholeStyle
);
1656 // When applying paragraph styles dynamically, don't change the text objects' attributes
1657 // since they will computed as needed. Only apply the character styling if it's _only_
1658 // character styling. This policy is subject to change and might be put under user control.
1660 // Hm. we might well be applying a mix of paragraph and character styles, in which
1661 // case we _do_ want to apply character styles regardless of what para styles are set.
1662 // But if we're applying a paragraph style, which has some character attributes, but
1663 // we only want the paragraphs to hold this character style, then we _don't_ want to
1664 // apply the character style. So we need to be able to choose.
1666 // if (!paragraphStyle && characterStyle && range.GetStart() != newPara->GetRange().GetEnd())
1667 if (!parasOnly
&& characterStyle
&& range
.GetStart() != newPara
->GetRange().GetEnd())
1669 wxRichTextRange
childRange(range
);
1670 childRange
.LimitTo(newPara
->GetRange());
1672 // Find the starting position and if necessary split it so
1673 // we can start applying a different style.
1674 // TODO: check that the style actually changes or is different
1675 // from style outside of range
1676 wxRichTextObject
* firstObject
wxDUMMY_INITIALIZE(NULL
);
1677 wxRichTextObject
* lastObject
wxDUMMY_INITIALIZE(NULL
);
1679 if (childRange
.GetStart() == newPara
->GetRange().GetStart())
1680 firstObject
= newPara
->GetChildren().GetFirst()->GetData();
1682 firstObject
= newPara
->SplitAt(range
.GetStart());
1684 // Increment by 1 because we're apply the style one _after_ the split point
1685 long splitPoint
= childRange
.GetEnd();
1686 if (splitPoint
!= newPara
->GetRange().GetEnd())
1690 if (splitPoint
== newPara
->GetRange().GetEnd() || splitPoint
== (newPara
->GetRange().GetEnd() - 1))
1691 lastObject
= newPara
->GetChildren().GetLast()->GetData();
1693 // lastObject is set as a side-effect of splitting. It's
1694 // returned as the object before the new object.
1695 (void) newPara
->SplitAt(splitPoint
, & lastObject
);
1697 wxASSERT(firstObject
!= NULL
);
1698 wxASSERT(lastObject
!= NULL
);
1700 if (!firstObject
|| !lastObject
)
1703 wxRichTextObjectList::compatibility_iterator firstNode
= newPara
->GetChildren().Find(firstObject
);
1704 wxRichTextObjectList::compatibility_iterator lastNode
= newPara
->GetChildren().Find(lastObject
);
1706 wxASSERT(firstNode
);
1709 wxRichTextObjectList::compatibility_iterator node2
= firstNode
;
1713 wxRichTextObject
* child
= node2
->GetData();
1717 // Removes the given style from the paragraph
1718 wxRichTextRemoveStyle(child
->GetAttributes(), style
);
1720 else if (resetExistingStyle
)
1721 child
->GetAttributes() = characterAttributes
;
1726 // Only apply attributes that will make a difference to the combined
1727 // style as seen on the display
1728 wxTextAttr
combinedAttr(newPara
->GetCombinedAttributes(child
->GetAttributes()));
1729 wxRichTextApplyStyle(child
->GetAttributes(), characterAttributes
, & combinedAttr
);
1732 wxRichTextApplyStyle(child
->GetAttributes(), characterAttributes
);
1735 if (node2
== lastNode
)
1738 node2
= node2
->GetNext();
1744 node
= node
->GetNext();
1747 // Do action, or delay it until end of batch.
1748 if (haveControl
&& withUndo
)
1749 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
1754 /// Get the text attributes for this position.
1755 bool wxRichTextParagraphLayoutBox::GetStyle(long position
, wxTextAttr
& style
)
1757 return DoGetStyle(position
, style
, true);
1760 bool wxRichTextParagraphLayoutBox::GetUncombinedStyle(long position
, wxTextAttr
& style
)
1762 return DoGetStyle(position
, style
, false);
1765 /// Implementation helper for GetStyle. If combineStyles is true, combine base, paragraph and
1766 /// context attributes.
1767 bool wxRichTextParagraphLayoutBox::DoGetStyle(long position
, wxTextAttr
& style
, bool combineStyles
)
1769 wxRichTextObject
* obj
wxDUMMY_INITIALIZE(NULL
);
1771 if (style
.IsParagraphStyle())
1773 obj
= GetParagraphAtPosition(position
);
1778 // Start with the base style
1779 style
= GetAttributes();
1781 // Apply the paragraph style
1782 wxRichTextApplyStyle(style
, obj
->GetAttributes());
1785 style
= obj
->GetAttributes();
1792 obj
= GetLeafObjectAtPosition(position
);
1797 wxRichTextParagraph
* para
= wxDynamicCast(obj
->GetParent(), wxRichTextParagraph
);
1798 style
= para
? para
->GetCombinedAttributes(obj
->GetAttributes()) : obj
->GetAttributes();
1801 style
= obj
->GetAttributes();
1809 static bool wxHasStyle(long flags
, long style
)
1811 return (flags
& style
) != 0;
1814 /// Combines 'style' with 'currentStyle' for the purpose of summarising the attributes of a range of
1816 bool wxRichTextParagraphLayoutBox::CollectStyle(wxTextAttr
& currentStyle
, const wxTextAttr
& style
, long& multipleStyleAttributes
, int& multipleTextEffectAttributes
)
1818 if (style
.HasFont())
1820 if (style
.HasFontSize() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_SIZE
))
1822 if (currentStyle
.HasFontSize())
1824 if (currentStyle
.GetFontSize() != style
.GetFontSize())
1826 // Clash of style - mark as such
1827 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_SIZE
;
1828 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_SIZE
);
1833 currentStyle
.SetFontSize(style
.GetFontSize());
1837 if (style
.HasFontItalic() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_ITALIC
))
1839 if (currentStyle
.HasFontItalic())
1841 if (currentStyle
.GetFontStyle() != style
.GetFontStyle())
1843 // Clash of style - mark as such
1844 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_ITALIC
;
1845 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_ITALIC
);
1850 currentStyle
.SetFontStyle(style
.GetFontStyle());
1854 if (style
.HasFontWeight() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_WEIGHT
))
1856 if (currentStyle
.HasFontWeight())
1858 if (currentStyle
.GetFontWeight() != style
.GetFontWeight())
1860 // Clash of style - mark as such
1861 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_WEIGHT
;
1862 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_WEIGHT
);
1867 currentStyle
.SetFontWeight(style
.GetFontWeight());
1871 if (style
.HasFontFaceName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_FACE
))
1873 if (currentStyle
.HasFontFaceName())
1875 wxString
faceName1(currentStyle
.GetFontFaceName());
1876 wxString
faceName2(style
.GetFontFaceName());
1878 if (faceName1
!= faceName2
)
1880 // Clash of style - mark as such
1881 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_FACE
;
1882 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_FACE
);
1887 currentStyle
.SetFontFaceName(style
.GetFontFaceName());
1891 if (style
.HasFontUnderlined() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_UNDERLINE
))
1893 if (currentStyle
.HasFontUnderlined())
1895 if (currentStyle
.GetFontUnderlined() != style
.GetFontUnderlined())
1897 // Clash of style - mark as such
1898 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_UNDERLINE
;
1899 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_UNDERLINE
);
1904 currentStyle
.SetFontUnderlined(style
.GetFontUnderlined());
1909 if (style
.HasTextColour() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_TEXT_COLOUR
))
1911 if (currentStyle
.HasTextColour())
1913 if (currentStyle
.GetTextColour() != style
.GetTextColour())
1915 // Clash of style - mark as such
1916 multipleStyleAttributes
|= wxTEXT_ATTR_TEXT_COLOUR
;
1917 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_TEXT_COLOUR
);
1921 currentStyle
.SetTextColour(style
.GetTextColour());
1924 if (style
.HasBackgroundColour() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BACKGROUND_COLOUR
))
1926 if (currentStyle
.HasBackgroundColour())
1928 if (currentStyle
.GetBackgroundColour() != style
.GetBackgroundColour())
1930 // Clash of style - mark as such
1931 multipleStyleAttributes
|= wxTEXT_ATTR_BACKGROUND_COLOUR
;
1932 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BACKGROUND_COLOUR
);
1936 currentStyle
.SetBackgroundColour(style
.GetBackgroundColour());
1939 if (style
.HasAlignment() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_ALIGNMENT
))
1941 if (currentStyle
.HasAlignment())
1943 if (currentStyle
.GetAlignment() != style
.GetAlignment())
1945 // Clash of style - mark as such
1946 multipleStyleAttributes
|= wxTEXT_ATTR_ALIGNMENT
;
1947 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_ALIGNMENT
);
1951 currentStyle
.SetAlignment(style
.GetAlignment());
1954 if (style
.HasTabs() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_TABS
))
1956 if (currentStyle
.HasTabs())
1958 if (!wxRichTextTabsEq(currentStyle
.GetTabs(), style
.GetTabs()))
1960 // Clash of style - mark as such
1961 multipleStyleAttributes
|= wxTEXT_ATTR_TABS
;
1962 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_TABS
);
1966 currentStyle
.SetTabs(style
.GetTabs());
1969 if (style
.HasLeftIndent() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_LEFT_INDENT
))
1971 if (currentStyle
.HasLeftIndent())
1973 if (currentStyle
.GetLeftIndent() != style
.GetLeftIndent() || currentStyle
.GetLeftSubIndent() != style
.GetLeftSubIndent())
1975 // Clash of style - mark as such
1976 multipleStyleAttributes
|= wxTEXT_ATTR_LEFT_INDENT
;
1977 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LEFT_INDENT
);
1981 currentStyle
.SetLeftIndent(style
.GetLeftIndent(), style
.GetLeftSubIndent());
1984 if (style
.HasRightIndent() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_RIGHT_INDENT
))
1986 if (currentStyle
.HasRightIndent())
1988 if (currentStyle
.GetRightIndent() != style
.GetRightIndent())
1990 // Clash of style - mark as such
1991 multipleStyleAttributes
|= wxTEXT_ATTR_RIGHT_INDENT
;
1992 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_RIGHT_INDENT
);
1996 currentStyle
.SetRightIndent(style
.GetRightIndent());
1999 if (style
.HasParagraphSpacingAfter() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_PARA_SPACING_AFTER
))
2001 if (currentStyle
.HasParagraphSpacingAfter())
2003 if (currentStyle
.GetParagraphSpacingAfter() != style
.GetParagraphSpacingAfter())
2005 // Clash of style - mark as such
2006 multipleStyleAttributes
|= wxTEXT_ATTR_PARA_SPACING_AFTER
;
2007 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARA_SPACING_AFTER
);
2011 currentStyle
.SetParagraphSpacingAfter(style
.GetParagraphSpacingAfter());
2014 if (style
.HasParagraphSpacingBefore() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_PARA_SPACING_BEFORE
))
2016 if (currentStyle
.HasParagraphSpacingBefore())
2018 if (currentStyle
.GetParagraphSpacingBefore() != style
.GetParagraphSpacingBefore())
2020 // Clash of style - mark as such
2021 multipleStyleAttributes
|= wxTEXT_ATTR_PARA_SPACING_BEFORE
;
2022 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARA_SPACING_BEFORE
);
2026 currentStyle
.SetParagraphSpacingBefore(style
.GetParagraphSpacingBefore());
2029 if (style
.HasLineSpacing() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_LINE_SPACING
))
2031 if (currentStyle
.HasLineSpacing())
2033 if (currentStyle
.GetLineSpacing() != style
.GetLineSpacing())
2035 // Clash of style - mark as such
2036 multipleStyleAttributes
|= wxTEXT_ATTR_LINE_SPACING
;
2037 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LINE_SPACING
);
2041 currentStyle
.SetLineSpacing(style
.GetLineSpacing());
2044 if (style
.HasCharacterStyleName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_CHARACTER_STYLE_NAME
))
2046 if (currentStyle
.HasCharacterStyleName())
2048 if (currentStyle
.GetCharacterStyleName() != style
.GetCharacterStyleName())
2050 // Clash of style - mark as such
2051 multipleStyleAttributes
|= wxTEXT_ATTR_CHARACTER_STYLE_NAME
;
2052 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_CHARACTER_STYLE_NAME
);
2056 currentStyle
.SetCharacterStyleName(style
.GetCharacterStyleName());
2059 if (style
.HasParagraphStyleName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
))
2061 if (currentStyle
.HasParagraphStyleName())
2063 if (currentStyle
.GetParagraphStyleName() != style
.GetParagraphStyleName())
2065 // Clash of style - mark as such
2066 multipleStyleAttributes
|= wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
;
2067 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
);
2071 currentStyle
.SetParagraphStyleName(style
.GetParagraphStyleName());
2074 if (style
.HasListStyleName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_LIST_STYLE_NAME
))
2076 if (currentStyle
.HasListStyleName())
2078 if (currentStyle
.GetListStyleName() != style
.GetListStyleName())
2080 // Clash of style - mark as such
2081 multipleStyleAttributes
|= wxTEXT_ATTR_LIST_STYLE_NAME
;
2082 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LIST_STYLE_NAME
);
2086 currentStyle
.SetListStyleName(style
.GetListStyleName());
2089 if (style
.HasBulletStyle() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_STYLE
))
2091 if (currentStyle
.HasBulletStyle())
2093 if (currentStyle
.GetBulletStyle() != style
.GetBulletStyle())
2095 // Clash of style - mark as such
2096 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_STYLE
;
2097 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_STYLE
);
2101 currentStyle
.SetBulletStyle(style
.GetBulletStyle());
2104 if (style
.HasBulletNumber() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_NUMBER
))
2106 if (currentStyle
.HasBulletNumber())
2108 if (currentStyle
.GetBulletNumber() != style
.GetBulletNumber())
2110 // Clash of style - mark as such
2111 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_NUMBER
;
2112 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_NUMBER
);
2116 currentStyle
.SetBulletNumber(style
.GetBulletNumber());
2119 if (style
.HasBulletText() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_TEXT
))
2121 if (currentStyle
.HasBulletText())
2123 if (currentStyle
.GetBulletText() != style
.GetBulletText())
2125 // Clash of style - mark as such
2126 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_TEXT
;
2127 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_TEXT
);
2132 currentStyle
.SetBulletText(style
.GetBulletText());
2133 currentStyle
.SetBulletFont(style
.GetBulletFont());
2137 if (style
.HasBulletName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_NAME
))
2139 if (currentStyle
.HasBulletName())
2141 if (currentStyle
.GetBulletName() != style
.GetBulletName())
2143 // Clash of style - mark as such
2144 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_NAME
;
2145 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_NAME
);
2150 currentStyle
.SetBulletName(style
.GetBulletName());
2154 if (style
.HasURL() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_URL
))
2156 if (currentStyle
.HasURL())
2158 if (currentStyle
.GetURL() != style
.GetURL())
2160 // Clash of style - mark as such
2161 multipleStyleAttributes
|= wxTEXT_ATTR_URL
;
2162 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_URL
);
2167 currentStyle
.SetURL(style
.GetURL());
2171 if (style
.HasTextEffects() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_EFFECTS
))
2173 if (currentStyle
.HasTextEffects())
2175 // We need to find the bits in the new style that are different:
2176 // just look at those bits that are specified by the new style.
2178 int currentRelevantTextEffects
= currentStyle
.GetTextEffects() & style
.GetTextEffectFlags();
2179 int newRelevantTextEffects
= style
.GetTextEffects() & style
.GetTextEffectFlags();
2181 if (currentRelevantTextEffects
!= newRelevantTextEffects
)
2183 // Find the text effects that were different, using XOR
2184 int differentEffects
= currentRelevantTextEffects
^ newRelevantTextEffects
;
2186 // Clash of style - mark as such
2187 multipleTextEffectAttributes
|= differentEffects
;
2188 currentStyle
.SetTextEffectFlags(currentStyle
.GetTextEffectFlags() & ~differentEffects
);
2193 currentStyle
.SetTextEffects(style
.GetTextEffects());
2194 currentStyle
.SetTextEffectFlags(style
.GetTextEffectFlags());
2198 if (style
.HasOutlineLevel() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_OUTLINE_LEVEL
))
2200 if (currentStyle
.HasOutlineLevel())
2202 if (currentStyle
.GetOutlineLevel() != style
.GetOutlineLevel())
2204 // Clash of style - mark as such
2205 multipleStyleAttributes
|= wxTEXT_ATTR_OUTLINE_LEVEL
;
2206 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_OUTLINE_LEVEL
);
2210 currentStyle
.SetOutlineLevel(style
.GetOutlineLevel());
2216 /// Get the combined style for a range - if any attribute is different within the range,
2217 /// that attribute is not present within the flags.
2218 /// *** Note that this is not recursive, and so assumes that content inside a paragraph is not itself
2220 bool wxRichTextParagraphLayoutBox::GetStyleForRange(const wxRichTextRange
& range
, wxTextAttr
& style
)
2222 style
= wxTextAttr();
2224 // The attributes that aren't valid because of multiple styles within the range
2225 long multipleStyleAttributes
= 0;
2226 int multipleTextEffectAttributes
= 0;
2228 wxRichTextObjectList::compatibility_iterator node
= GetChildren().GetFirst();
2231 wxRichTextParagraph
* para
= (wxRichTextParagraph
*) node
->GetData();
2232 if (!(para
->GetRange().GetStart() > range
.GetEnd() || para
->GetRange().GetEnd() < range
.GetStart()))
2234 if (para
->GetChildren().GetCount() == 0)
2236 wxTextAttr paraStyle
= para
->GetCombinedAttributes();
2238 CollectStyle(style
, paraStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
);
2242 wxRichTextRange
paraRange(para
->GetRange());
2243 paraRange
.LimitTo(range
);
2245 // First collect paragraph attributes only
2246 wxTextAttr paraStyle
= para
->GetCombinedAttributes();
2247 paraStyle
.SetFlags(paraStyle
.GetFlags() & wxTEXT_ATTR_PARAGRAPH
);
2248 CollectStyle(style
, paraStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
);
2250 wxRichTextObjectList::compatibility_iterator childNode
= para
->GetChildren().GetFirst();
2254 wxRichTextObject
* child
= childNode
->GetData();
2255 if (!(child
->GetRange().GetStart() > range
.GetEnd() || child
->GetRange().GetEnd() < range
.GetStart()))
2257 wxTextAttr childStyle
= para
->GetCombinedAttributes(child
->GetAttributes());
2259 // Now collect character attributes only
2260 childStyle
.SetFlags(childStyle
.GetFlags() & wxTEXT_ATTR_CHARACTER
);
2262 CollectStyle(style
, childStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
);
2265 childNode
= childNode
->GetNext();
2269 node
= node
->GetNext();
2274 /// Set default style
2275 bool wxRichTextParagraphLayoutBox::SetDefaultStyle(const wxTextAttr
& style
)
2277 m_defaultAttributes
= style
;
2281 /// Test if this whole range has character attributes of the specified kind. If any
2282 /// of the attributes are different within the range, the test fails. You
2283 /// can use this to implement, for example, bold button updating. style must have
2284 /// flags indicating which attributes are of interest.
2285 bool wxRichTextParagraphLayoutBox::HasCharacterAttributes(const wxRichTextRange
& range
, const wxTextAttr
& style
) const
2288 int matchingCount
= 0;
2290 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2293 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2294 wxASSERT (para
!= NULL
);
2298 // Stop searching if we're beyond the range of interest
2299 if (para
->GetRange().GetStart() > range
.GetEnd())
2300 return foundCount
== matchingCount
;
2302 if (!para
->GetRange().IsOutside(range
))
2304 wxRichTextObjectList::compatibility_iterator node2
= para
->GetChildren().GetFirst();
2308 wxRichTextObject
* child
= node2
->GetData();
2309 if (!child
->GetRange().IsOutside(range
) && child
->IsKindOf(CLASSINFO(wxRichTextPlainText
)))
2312 wxTextAttr textAttr
= para
->GetCombinedAttributes(child
->GetAttributes());
2314 if (wxTextAttrEqPartial(textAttr
, style
, style
.GetFlags()))
2318 node2
= node2
->GetNext();
2323 node
= node
->GetNext();
2326 return foundCount
== matchingCount
;
2329 /// Test if this whole range has paragraph attributes of the specified kind. If any
2330 /// of the attributes are different within the range, the test fails. You
2331 /// can use this to implement, for example, centering button updating. style must have
2332 /// flags indicating which attributes are of interest.
2333 bool wxRichTextParagraphLayoutBox::HasParagraphAttributes(const wxRichTextRange
& range
, const wxTextAttr
& style
) const
2336 int matchingCount
= 0;
2338 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2341 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2342 wxASSERT (para
!= NULL
);
2346 // Stop searching if we're beyond the range of interest
2347 if (para
->GetRange().GetStart() > range
.GetEnd())
2348 return foundCount
== matchingCount
;
2350 if (!para
->GetRange().IsOutside(range
))
2352 wxTextAttr textAttr
= GetAttributes();
2353 // Apply the paragraph style
2354 wxRichTextApplyStyle(textAttr
, para
->GetAttributes());
2357 if (wxTextAttrEqPartial(textAttr
, style
, style
.GetFlags()))
2362 node
= node
->GetNext();
2364 return foundCount
== matchingCount
;
2367 void wxRichTextParagraphLayoutBox::Clear()
2372 void wxRichTextParagraphLayoutBox::Reset()
2376 AddParagraph(wxEmptyString
);
2378 Invalidate(wxRICHTEXT_ALL
);
2381 /// Invalidate the buffer. With no argument, invalidates whole buffer.
2382 void wxRichTextParagraphLayoutBox::Invalidate(const wxRichTextRange
& invalidRange
)
2386 if (invalidRange
== wxRICHTEXT_ALL
)
2388 m_invalidRange
= wxRICHTEXT_ALL
;
2392 // Already invalidating everything
2393 if (m_invalidRange
== wxRICHTEXT_ALL
)
2396 if ((invalidRange
.GetStart() < m_invalidRange
.GetStart()) || m_invalidRange
.GetStart() == -1)
2397 m_invalidRange
.SetStart(invalidRange
.GetStart());
2398 if (invalidRange
.GetEnd() > m_invalidRange
.GetEnd())
2399 m_invalidRange
.SetEnd(invalidRange
.GetEnd());
2402 /// Get invalid range, rounding to entire paragraphs if argument is true.
2403 wxRichTextRange
wxRichTextParagraphLayoutBox::GetInvalidRange(bool wholeParagraphs
) const
2405 if (m_invalidRange
== wxRICHTEXT_ALL
|| m_invalidRange
== wxRICHTEXT_NONE
)
2406 return m_invalidRange
;
2408 wxRichTextRange range
= m_invalidRange
;
2410 if (wholeParagraphs
)
2412 wxRichTextParagraph
* para1
= GetParagraphAtPosition(range
.GetStart());
2413 wxRichTextParagraph
* para2
= GetParagraphAtPosition(range
.GetEnd());
2415 range
.SetStart(para1
->GetRange().GetStart());
2417 range
.SetEnd(para2
->GetRange().GetEnd());
2422 /// Apply the style sheet to the buffer, for example if the styles have changed.
2423 bool wxRichTextParagraphLayoutBox::ApplyStyleSheet(wxRichTextStyleSheet
* styleSheet
)
2425 wxASSERT(styleSheet
!= NULL
);
2431 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2434 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2435 wxASSERT (para
!= NULL
);
2439 // Combine paragraph and list styles. If there is a list style in the original attributes,
2440 // the current indentation overrides anything else and is used to find the item indentation.
2441 // Also, for applying paragraph styles, consider having 2 modes: (1) we merge with what we have,
2442 // thereby taking into account all user changes, (2) reset the style completely (except for indentation/list
2443 // exception as above).
2444 // Problem: when changing from one list style to another, there's a danger that the level info will get lost.
2445 // So when changing a list style interactively, could retrieve level based on current style, then
2446 // set appropriate indent and apply new style.
2448 if (!para
->GetAttributes().GetParagraphStyleName().IsEmpty() && !para
->GetAttributes().GetListStyleName().IsEmpty())
2450 int currentIndent
= para
->GetAttributes().GetLeftIndent();
2452 wxRichTextParagraphStyleDefinition
* paraDef
= styleSheet
->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
2453 wxRichTextListStyleDefinition
* listDef
= styleSheet
->FindListStyle(para
->GetAttributes().GetListStyleName());
2454 if (paraDef
&& !listDef
)
2456 para
->GetAttributes() = paraDef
->GetStyleMergedWithBase(styleSheet
);
2459 else if (listDef
&& !paraDef
)
2461 // Set overall style defined for the list style definition
2462 para
->GetAttributes() = listDef
->GetStyleMergedWithBase(styleSheet
);
2464 // Apply the style for this level
2465 wxRichTextApplyStyle(para
->GetAttributes(), * listDef
->GetLevelAttributes(listDef
->FindLevelForIndent(currentIndent
)));
2468 else if (listDef
&& paraDef
)
2470 // Combines overall list style, style for level, and paragraph style
2471 para
->GetAttributes() = listDef
->CombineWithParagraphStyle(currentIndent
, paraDef
->GetStyleMergedWithBase(styleSheet
));
2475 else if (para
->GetAttributes().GetParagraphStyleName().IsEmpty() && !para
->GetAttributes().GetListStyleName().IsEmpty())
2477 int currentIndent
= para
->GetAttributes().GetLeftIndent();
2479 wxRichTextListStyleDefinition
* listDef
= styleSheet
->FindListStyle(para
->GetAttributes().GetListStyleName());
2481 // Overall list definition style
2482 para
->GetAttributes() = listDef
->GetStyleMergedWithBase(styleSheet
);
2484 // Style for this level
2485 wxRichTextApplyStyle(para
->GetAttributes(), * listDef
->GetLevelAttributes(listDef
->FindLevelForIndent(currentIndent
)));
2489 else if (!para
->GetAttributes().GetParagraphStyleName().IsEmpty() && para
->GetAttributes().GetListStyleName().IsEmpty())
2491 wxRichTextParagraphStyleDefinition
* def
= styleSheet
->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
2494 para
->GetAttributes() = def
->GetStyleMergedWithBase(styleSheet
);
2500 node
= node
->GetNext();
2502 return foundCount
!= 0;
2506 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2508 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2510 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
2511 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2512 bool specifyLevel
= ((flags
& wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL
) != 0);
2513 bool renumber
= ((flags
& wxRICHTEXT_SETSTYLE_RENUMBER
) != 0);
2515 // Current number, if numbering
2518 wxASSERT (!specifyLevel
|| (specifyLevel
&& (specifiedLevel
>= 0)));
2520 // If we are associated with a control, make undoable; otherwise, apply immediately
2523 bool haveControl
= (GetRichTextCtrl() != NULL
);
2525 wxRichTextAction
* action
= NULL
;
2527 if (haveControl
&& withUndo
)
2529 action
= new wxRichTextAction(NULL
, _("Change List Style"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2530 action
->SetRange(range
);
2531 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2534 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2537 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2538 wxASSERT (para
!= NULL
);
2540 if (para
&& para
->GetChildCount() > 0)
2542 // Stop searching if we're beyond the range of interest
2543 if (para
->GetRange().GetStart() > range
.GetEnd())
2546 if (!para
->GetRange().IsOutside(range
))
2548 // We'll be using a copy of the paragraph to make style changes,
2549 // not updating the buffer directly.
2550 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
2552 if (haveControl
&& withUndo
)
2554 newPara
= new wxRichTextParagraph(*para
);
2555 action
->GetNewParagraphs().AppendChild(newPara
);
2557 // Also store the old ones for Undo
2558 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
2565 int thisIndent
= newPara
->GetAttributes().GetLeftIndent();
2566 int thisLevel
= specifyLevel
? specifiedLevel
: def
->FindLevelForIndent(thisIndent
);
2568 // How is numbering going to work?
2569 // If we are renumbering, or numbering for the first time, we need to keep
2570 // track of the number for each level. But we might be simply applying a different
2572 // In Word, applying a style to several paragraphs, even if at different levels,
2573 // reverts the level back to the same one. So we could do the same here.
2574 // Renumbering will need to be done when we promote/demote a paragraph.
2576 // Apply the overall list style, and item style for this level
2577 wxTextAttr
listStyle(def
->GetCombinedStyleForLevel(thisLevel
, styleSheet
));
2578 wxRichTextApplyStyle(newPara
->GetAttributes(), listStyle
);
2580 // Now we need to do numbering
2583 newPara
->GetAttributes().SetBulletNumber(n
);
2588 else if (!newPara
->GetAttributes().GetListStyleName().IsEmpty())
2590 // if def is NULL, remove list style, applying any associated paragraph style
2591 // to restore the attributes
2593 newPara
->GetAttributes().SetListStyleName(wxEmptyString
);
2594 newPara
->GetAttributes().SetLeftIndent(0, 0);
2595 newPara
->GetAttributes().SetBulletText(wxEmptyString
);
2597 // Eliminate the main list-related attributes
2598 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
);
2600 if (styleSheet
&& !newPara
->GetAttributes().GetParagraphStyleName().IsEmpty())
2602 wxRichTextParagraphStyleDefinition
* def
= styleSheet
->FindParagraphStyle(newPara
->GetAttributes().GetParagraphStyleName());
2605 newPara
->GetAttributes() = def
->GetStyleMergedWithBase(styleSheet
);
2612 node
= node
->GetNext();
2615 // Do action, or delay it until end of batch.
2616 if (haveControl
&& withUndo
)
2617 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
2622 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int startFrom
, int specifiedLevel
)
2624 if (GetStyleSheet())
2626 wxRichTextListStyleDefinition
* def
= GetStyleSheet()->FindListStyle(defName
);
2628 return SetListStyle(range
, def
, flags
, startFrom
, specifiedLevel
);
2633 /// Clear list for given range
2634 bool wxRichTextParagraphLayoutBox::ClearListStyle(const wxRichTextRange
& range
, int flags
)
2636 return SetListStyle(range
, NULL
, flags
);
2639 /// Number/renumber any list elements in the given range
2640 bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2642 return DoNumberList(range
, range
, 0, def
, flags
, startFrom
, specifiedLevel
);
2645 /// Number/renumber any list elements in the given range. Also do promotion or demotion of items, if specified
2646 bool wxRichTextParagraphLayoutBox::DoNumberList(const wxRichTextRange
& range
, const wxRichTextRange
& promotionRange
, int promoteBy
,
2647 wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2649 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2651 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
2652 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2654 bool specifyLevel
= ((flags
& wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL
) != 0);
2657 bool renumber
= ((flags
& wxRICHTEXT_SETSTYLE_RENUMBER
) != 0);
2659 // Max number of levels
2660 const int maxLevels
= 10;
2662 // The level we're looking at now
2663 int currentLevel
= -1;
2665 // The item number for each level
2666 int levels
[maxLevels
];
2669 // Reset all numbering
2670 for (i
= 0; i
< maxLevels
; i
++)
2672 if (startFrom
!= -1)
2673 levels
[i
] = startFrom
-1;
2674 else if (renumber
) // start again
2677 levels
[i
] = -1; // start from the number we found, if any
2680 wxASSERT(!specifyLevel
|| (specifyLevel
&& (specifiedLevel
>= 0)));
2682 // If we are associated with a control, make undoable; otherwise, apply immediately
2685 bool haveControl
= (GetRichTextCtrl() != NULL
);
2687 wxRichTextAction
* action
= NULL
;
2689 if (haveControl
&& withUndo
)
2691 action
= new wxRichTextAction(NULL
, _("Renumber List"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2692 action
->SetRange(range
);
2693 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2696 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2699 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2700 wxASSERT (para
!= NULL
);
2702 if (para
&& para
->GetChildCount() > 0)
2704 // Stop searching if we're beyond the range of interest
2705 if (para
->GetRange().GetStart() > range
.GetEnd())
2708 if (!para
->GetRange().IsOutside(range
))
2710 // We'll be using a copy of the paragraph to make style changes,
2711 // not updating the buffer directly.
2712 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
2714 if (haveControl
&& withUndo
)
2716 newPara
= new wxRichTextParagraph(*para
);
2717 action
->GetNewParagraphs().AppendChild(newPara
);
2719 // Also store the old ones for Undo
2720 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
2725 wxRichTextListStyleDefinition
* defToUse
= def
;
2728 if (styleSheet
&& !newPara
->GetAttributes().GetListStyleName().IsEmpty())
2729 defToUse
= styleSheet
->FindListStyle(newPara
->GetAttributes().GetListStyleName());
2734 int thisIndent
= newPara
->GetAttributes().GetLeftIndent();
2735 int thisLevel
= defToUse
->FindLevelForIndent(thisIndent
);
2737 // If we've specified a level to apply to all, change the level.
2738 if (specifiedLevel
!= -1)
2739 thisLevel
= specifiedLevel
;
2741 // Do promotion if specified
2742 if ((promoteBy
!= 0) && !para
->GetRange().IsOutside(promotionRange
))
2744 thisLevel
= thisLevel
- promoteBy
;
2751 // Apply the overall list style, and item style for this level
2752 wxTextAttr
listStyle(defToUse
->GetCombinedStyleForLevel(thisLevel
, styleSheet
));
2753 wxRichTextApplyStyle(newPara
->GetAttributes(), listStyle
);
2755 // OK, we've (re)applied the style, now let's get the numbering right.
2757 if (currentLevel
== -1)
2758 currentLevel
= thisLevel
;
2760 // Same level as before, do nothing except increment level's number afterwards
2761 if (currentLevel
== thisLevel
)
2764 // A deeper level: start renumbering all levels after current level
2765 else if (thisLevel
> currentLevel
)
2767 for (i
= currentLevel
+1; i
<= thisLevel
; i
++)
2771 currentLevel
= thisLevel
;
2773 else if (thisLevel
< currentLevel
)
2775 currentLevel
= thisLevel
;
2778 // Use the current numbering if -1 and we have a bullet number already
2779 if (levels
[currentLevel
] == -1)
2781 if (newPara
->GetAttributes().HasBulletNumber())
2782 levels
[currentLevel
] = newPara
->GetAttributes().GetBulletNumber();
2784 levels
[currentLevel
] = 1;
2788 levels
[currentLevel
] ++;
2791 newPara
->GetAttributes().SetBulletNumber(levels
[currentLevel
]);
2793 // Create the bullet text if an outline list
2794 if (listStyle
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
)
2797 for (i
= 0; i
<= currentLevel
; i
++)
2799 if (!text
.IsEmpty())
2801 text
+= wxString::Format(wxT("%d"), levels
[i
]);
2803 newPara
->GetAttributes().SetBulletText(text
);
2809 node
= node
->GetNext();
2812 // Do action, or delay it until end of batch.
2813 if (haveControl
&& withUndo
)
2814 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
2819 bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int startFrom
, int specifiedLevel
)
2821 if (GetStyleSheet())
2823 wxRichTextListStyleDefinition
* def
= NULL
;
2824 if (!defName
.IsEmpty())
2825 def
= GetStyleSheet()->FindListStyle(defName
);
2826 return NumberList(range
, def
, flags
, startFrom
, specifiedLevel
);
2831 /// Promote the list items within the given range. promoteBy can be a positive or negative number, e.g. 1 or -1
2832 bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy
, const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int specifiedLevel
)
2835 // One strategy is to first work out the range within which renumbering must occur. Then could pass these two ranges
2836 // to NumberList with a flag indicating promotion is required within one of the ranges.
2837 // Find first and last paragraphs in range. Then for first, calculate new indentation and look back until we find
2838 // a paragraph that either has no list style, or has one that is different or whose indentation is less.
2839 // We start renumbering from the para after that different para we found. We specify that the numbering of that
2840 // list position will start from 1.
2841 // Similarly, we look after the last para in the promote range for an indentation that is less (or no list style).
2842 // We can end the renumbering at this point.
2844 // For now, only renumber within the promotion range.
2846 return DoNumberList(range
, range
, promoteBy
, def
, flags
, 1, specifiedLevel
);
2849 bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy
, const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int specifiedLevel
)
2851 if (GetStyleSheet())
2853 wxRichTextListStyleDefinition
* def
= NULL
;
2854 if (!defName
.IsEmpty())
2855 def
= GetStyleSheet()->FindListStyle(defName
);
2856 return PromoteList(promoteBy
, range
, def
, flags
, specifiedLevel
);
2861 /// Fills in the attributes for numbering a paragraph after previousParagraph. It also finds the
2862 /// position of the paragraph that it had to start looking from.
2863 bool wxRichTextParagraphLayoutBox::FindNextParagraphNumber(wxRichTextParagraph
* previousParagraph
, wxTextAttr
& attr
) const
2865 if (!previousParagraph
->GetAttributes().HasFlag(wxTEXT_ATTR_BULLET_STYLE
) || previousParagraph
->GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE
)
2868 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2869 if (styleSheet
&& !previousParagraph
->GetAttributes().GetListStyleName().IsEmpty())
2871 wxRichTextListStyleDefinition
* def
= styleSheet
->FindListStyle(previousParagraph
->GetAttributes().GetListStyleName());
2874 // int thisIndent = previousParagraph->GetAttributes().GetLeftIndent();
2875 // int thisLevel = def->FindLevelForIndent(thisIndent);
2877 bool isOutline
= (previousParagraph
->GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
) != 0;
2879 attr
.SetFlags(previousParagraph
->GetAttributes().GetFlags() & (wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_BULLET_NUMBER
|wxTEXT_ATTR_BULLET_TEXT
|wxTEXT_ATTR_BULLET_NAME
));
2880 if (previousParagraph
->GetAttributes().HasBulletName())
2881 attr
.SetBulletName(previousParagraph
->GetAttributes().GetBulletName());
2882 attr
.SetBulletStyle(previousParagraph
->GetAttributes().GetBulletStyle());
2883 attr
.SetListStyleName(previousParagraph
->GetAttributes().GetListStyleName());
2885 int nextNumber
= previousParagraph
->GetAttributes().GetBulletNumber() + 1;
2886 attr
.SetBulletNumber(nextNumber
);
2890 wxString text
= previousParagraph
->GetAttributes().GetBulletText();
2891 if (!text
.IsEmpty())
2893 int pos
= text
.Find(wxT('.'), true);
2894 if (pos
!= wxNOT_FOUND
)
2896 text
= text
.Mid(0, text
.Length() - pos
- 1);
2899 text
= wxEmptyString
;
2900 if (!text
.IsEmpty())
2902 text
+= wxString::Format(wxT("%d"), nextNumber
);
2903 attr
.SetBulletText(text
);
2917 * wxRichTextParagraph
2918 * This object represents a single paragraph (or in a straight text editor, a line).
2921 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraph
, wxRichTextBox
)
2923 wxArrayInt
wxRichTextParagraph::sm_defaultTabs
;
2925 wxRichTextParagraph::wxRichTextParagraph(wxRichTextObject
* parent
, wxTextAttr
* style
):
2926 wxRichTextBox(parent
)
2929 SetAttributes(*style
);
2932 wxRichTextParagraph::wxRichTextParagraph(const wxString
& text
, wxRichTextObject
* parent
, wxTextAttr
* paraStyle
, wxTextAttr
* charStyle
):
2933 wxRichTextBox(parent
)
2936 SetAttributes(*paraStyle
);
2938 AppendChild(new wxRichTextPlainText(text
, this, charStyle
));
2941 wxRichTextParagraph::~wxRichTextParagraph()
2947 bool wxRichTextParagraph::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& WXUNUSED(rect
), int WXUNUSED(descent
), int style
)
2949 wxTextAttr attr
= GetCombinedAttributes();
2951 // Draw the bullet, if any
2952 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
2954 if (attr
.GetLeftSubIndent() != 0)
2956 int spaceBeforePara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingBefore());
2957 int leftIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftIndent());
2959 wxTextAttr
bulletAttr(GetCombinedAttributes());
2961 // Combine with the font of the first piece of content, if one is specified
2962 if (GetChildren().GetCount() > 0)
2964 wxRichTextObject
* firstObj
= (wxRichTextObject
*) GetChildren().GetFirst()->GetData();
2965 if (firstObj
->GetAttributes().HasFont())
2967 wxRichTextApplyStyle(bulletAttr
, firstObj
->GetAttributes());
2971 // Get line height from first line, if any
2972 wxRichTextLine
* line
= m_cachedLines
.GetFirst() ? (wxRichTextLine
* ) m_cachedLines
.GetFirst()->GetData() : (wxRichTextLine
*) NULL
;
2975 int lineHeight
wxDUMMY_INITIALIZE(0);
2978 lineHeight
= line
->GetSize().y
;
2979 linePos
= line
->GetPosition() + GetPosition();
2984 if (bulletAttr
.HasFont() && GetBuffer())
2985 font
= GetBuffer()->GetFontTable().FindFont(bulletAttr
);
2987 font
= (*wxNORMAL_FONT
);
2991 lineHeight
= dc
.GetCharHeight();
2992 linePos
= GetPosition();
2993 linePos
.y
+= spaceBeforePara
;
2996 wxRect
bulletRect(GetPosition().x
+ leftIndent
, linePos
.y
, linePos
.x
- (GetPosition().x
+ leftIndent
), lineHeight
);
2998 if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP
)
3000 if (wxRichTextBuffer::GetRenderer())
3001 wxRichTextBuffer::GetRenderer()->DrawBitmapBullet(this, dc
, bulletAttr
, bulletRect
);
3003 else if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_STANDARD
)
3005 if (wxRichTextBuffer::GetRenderer())
3006 wxRichTextBuffer::GetRenderer()->DrawStandardBullet(this, dc
, bulletAttr
, bulletRect
);
3010 wxString bulletText
= GetBulletText();
3012 if (!bulletText
.empty() && wxRichTextBuffer::GetRenderer())
3013 wxRichTextBuffer::GetRenderer()->DrawTextBullet(this, dc
, bulletAttr
, bulletRect
, bulletText
);
3018 // Draw the range for each line, one object at a time.
3020 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3023 wxRichTextLine
* line
= node
->GetData();
3024 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3026 int maxDescent
= line
->GetDescent();
3028 // Lines are specified relative to the paragraph
3030 wxPoint linePosition
= line
->GetPosition() + GetPosition();
3031 wxPoint objectPosition
= linePosition
;
3033 // Loop through objects until we get to the one within range
3034 wxRichTextObjectList::compatibility_iterator node2
= m_children
.GetFirst();
3037 wxRichTextObject
* child
= node2
->GetData();
3039 if (!child
->GetRange().IsOutside(lineRange
) && !lineRange
.IsOutside(range
))
3041 // Draw this part of the line at the correct position
3042 wxRichTextRange
objectRange(child
->GetRange());
3043 objectRange
.LimitTo(lineRange
);
3047 child
->GetRangeSize(objectRange
, objectSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, objectPosition
);
3049 // Use the child object's width, but the whole line's height
3050 wxRect
childRect(objectPosition
, wxSize(objectSize
.x
, line
->GetSize().y
));
3051 child
->Draw(dc
, objectRange
, selectionRange
, childRect
, maxDescent
, style
);
3053 objectPosition
.x
+= objectSize
.x
;
3055 else if (child
->GetRange().GetStart() > lineRange
.GetEnd())
3056 // Can break out of inner loop now since we've passed this line's range
3059 node2
= node2
->GetNext();
3062 node
= node
->GetNext();
3068 /// Lay the item out
3069 bool wxRichTextParagraph::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
3071 wxTextAttr attr
= GetCombinedAttributes();
3075 // Increase the size of the paragraph due to spacing
3076 int spaceBeforePara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingBefore());
3077 int spaceAfterPara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingAfter());
3078 int leftIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftIndent());
3079 int leftSubIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftSubIndent());
3080 int rightIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetRightIndent());
3082 int lineSpacing
= 0;
3084 // Let's assume line spacing of 10 is normal, 15 is 1.5, 20 is 2, etc.
3085 if (attr
.GetLineSpacing() != 10 && GetBuffer())
3087 wxFont
font(GetBuffer()->GetFontTable().FindFont(attr
));
3089 lineSpacing
= (ConvertTenthsMMToPixels(dc
, dc
.GetCharHeight()) * attr
.GetLineSpacing())/10;
3092 // Available space for text on each line differs.
3093 int availableTextSpaceFirstLine
= rect
.GetWidth() - leftIndent
- rightIndent
;
3095 // Bullets start the text at the same position as subsequent lines
3096 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3097 availableTextSpaceFirstLine
-= leftSubIndent
;
3099 int availableTextSpaceSubsequentLines
= rect
.GetWidth() - leftIndent
- rightIndent
- leftSubIndent
;
3101 // Start position for each line relative to the paragraph
3102 int startPositionFirstLine
= leftIndent
;
3103 int startPositionSubsequentLines
= leftIndent
+ leftSubIndent
;
3105 // If we have a bullet in this paragraph, the start position for the first line's text
3106 // is actually leftIndent + leftSubIndent.
3107 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3108 startPositionFirstLine
= startPositionSubsequentLines
;
3110 long lastEndPos
= GetRange().GetStart()-1;
3111 long lastCompletedEndPos
= lastEndPos
;
3113 int currentWidth
= 0;
3114 SetPosition(rect
.GetPosition());
3116 wxPoint
currentPosition(0, spaceBeforePara
); // We will calculate lines relative to paragraph
3125 // We may need to go back to a previous child, in which case create the new line,
3126 // find the child corresponding to the start position of the string, and
3129 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3132 wxRichTextObject
* child
= node
->GetData();
3134 // If this is e.g. a composite text box, it will need to be laid out itself.
3135 // But if just a text fragment or image, for example, this will
3136 // do nothing. NB: won't we need to set the position after layout?
3137 // since for example if position is dependent on vertical line size, we
3138 // can't tell the position until the size is determined. So possibly introduce
3139 // another layout phase.
3141 // TODO: can't this be called only once per child?
3142 child
->Layout(dc
, rect
, style
);
3144 // Available width depends on whether we're on the first or subsequent lines
3145 int availableSpaceForText
= (lineCount
== 0 ? availableTextSpaceFirstLine
: availableTextSpaceSubsequentLines
);
3147 currentPosition
.x
= (lineCount
== 0 ? startPositionFirstLine
: startPositionSubsequentLines
);
3149 // We may only be looking at part of a child, if we searched back for wrapping
3150 // and found a suitable point some way into the child. So get the size for the fragment
3153 long nextBreakPos
= GetFirstLineBreakPosition(lastEndPos
+1);
3154 long lastPosToUse
= child
->GetRange().GetEnd();
3155 bool lineBreakInThisObject
= (nextBreakPos
> -1 && nextBreakPos
<= child
->GetRange().GetEnd());
3157 if (lineBreakInThisObject
)
3158 lastPosToUse
= nextBreakPos
;
3161 int childDescent
= 0;
3163 if ((nextBreakPos
== -1) && (lastEndPos
== child
->GetRange().GetStart() - 1)) // i.e. we want to get the whole thing
3165 childSize
= child
->GetCachedSize();
3166 childDescent
= child
->GetDescent();
3169 GetRangeSize(wxRichTextRange(lastEndPos
+1, lastPosToUse
), childSize
, childDescent
, dc
, wxRICHTEXT_UNFORMATTED
, rect
.GetPosition());
3172 // 1) There was a line break BEFORE the natural break
3173 // 2) There was a line break AFTER the natural break
3174 // 3) The child still fits (carry on)
3176 if ((lineBreakInThisObject
&& (childSize
.x
+ currentWidth
<= availableSpaceForText
)) ||
3177 (childSize
.x
+ currentWidth
> availableSpaceForText
))
3179 long wrapPosition
= 0;
3181 // Find a place to wrap. This may walk back to previous children,
3182 // for example if a word spans several objects.
3183 if (!FindWrapPosition(wxRichTextRange(lastCompletedEndPos
+1, child
->GetRange().GetEnd()), dc
, availableSpaceForText
, wrapPosition
))
3185 // If the function failed, just cut it off at the end of this child.
3186 wrapPosition
= child
->GetRange().GetEnd();
3189 // FindWrapPosition can still return a value that will put us in an endless wrapping loop
3190 if (wrapPosition
<= lastCompletedEndPos
)
3191 wrapPosition
= wxMax(lastCompletedEndPos
+1,child
->GetRange().GetEnd());
3193 // wxLogDebug(wxT("Split at %ld"), wrapPosition);
3195 // Let's find the actual size of the current line now
3197 wxRichTextRange
actualRange(lastCompletedEndPos
+1, wrapPosition
);
3198 GetRangeSize(actualRange
, actualSize
, childDescent
, dc
, wxRICHTEXT_UNFORMATTED
);
3199 currentWidth
= actualSize
.x
;
3200 lineHeight
= wxMax(lineHeight
, actualSize
.y
);
3201 maxDescent
= wxMax(childDescent
, maxDescent
);
3204 wxRichTextLine
* line
= AllocateLine(lineCount
);
3206 // Set relative range so we won't have to change line ranges when paragraphs are moved
3207 line
->SetRange(wxRichTextRange(actualRange
.GetStart() - GetRange().GetStart(), actualRange
.GetEnd() - GetRange().GetStart()));
3208 line
->SetPosition(currentPosition
);
3209 line
->SetSize(wxSize(currentWidth
, lineHeight
));
3210 line
->SetDescent(maxDescent
);
3212 // Now move down a line. TODO: add margins, spacing
3213 currentPosition
.y
+= lineHeight
;
3214 currentPosition
.y
+= lineSpacing
;
3217 maxWidth
= wxMax(maxWidth
, currentWidth
);
3221 // TODO: account for zero-length objects, such as fields
3222 wxASSERT(wrapPosition
> lastCompletedEndPos
);
3224 lastEndPos
= wrapPosition
;
3225 lastCompletedEndPos
= lastEndPos
;
3229 // May need to set the node back to a previous one, due to searching back in wrapping
3230 wxRichTextObject
* childAfterWrapPosition
= FindObjectAtPosition(wrapPosition
+1);
3231 if (childAfterWrapPosition
)
3232 node
= m_children
.Find(childAfterWrapPosition
);
3234 node
= node
->GetNext();
3238 // We still fit, so don't add a line, and keep going
3239 currentWidth
+= childSize
.x
;
3240 lineHeight
= wxMax(lineHeight
, childSize
.y
);
3241 maxDescent
= wxMax(childDescent
, maxDescent
);
3243 maxWidth
= wxMax(maxWidth
, currentWidth
);
3244 lastEndPos
= child
->GetRange().GetEnd();
3246 node
= node
->GetNext();
3250 // Add the last line - it's the current pos -> last para pos
3251 // Substract -1 because the last position is always the end-paragraph position.
3252 if (lastCompletedEndPos
<= GetRange().GetEnd()-1)
3254 currentPosition
.x
= (lineCount
== 0 ? startPositionFirstLine
: startPositionSubsequentLines
);
3256 wxRichTextLine
* line
= AllocateLine(lineCount
);
3258 wxRichTextRange
actualRange(lastCompletedEndPos
+1, GetRange().GetEnd()-1);
3260 // Set relative range so we won't have to change line ranges when paragraphs are moved
3261 line
->SetRange(wxRichTextRange(actualRange
.GetStart() - GetRange().GetStart(), actualRange
.GetEnd() - GetRange().GetStart()));
3263 line
->SetPosition(currentPosition
);
3265 if (lineHeight
== 0 && GetBuffer())
3267 wxFont
font(GetBuffer()->GetFontTable().FindFont(attr
));
3269 lineHeight
= dc
.GetCharHeight();
3271 if (maxDescent
== 0)
3274 dc
.GetTextExtent(wxT("X"), & w
, &h
, & maxDescent
);
3277 line
->SetSize(wxSize(currentWidth
, lineHeight
));
3278 line
->SetDescent(maxDescent
);
3279 currentPosition
.y
+= lineHeight
;
3280 currentPosition
.y
+= lineSpacing
;
3284 // Remove remaining unused line objects, if any
3285 ClearUnusedLines(lineCount
);
3287 // Apply styles to wrapped lines
3288 ApplyParagraphStyle(attr
, rect
);
3290 SetCachedSize(wxSize(maxWidth
, currentPosition
.y
+ spaceBeforePara
+ spaceAfterPara
));
3297 /// Apply paragraph styles, such as centering, to wrapped lines
3298 void wxRichTextParagraph::ApplyParagraphStyle(const wxTextAttr
& attr
, const wxRect
& rect
)
3300 if (!attr
.HasAlignment())
3303 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3306 wxRichTextLine
* line
= node
->GetData();
3308 wxPoint pos
= line
->GetPosition();
3309 wxSize size
= line
->GetSize();
3311 // centering, right-justification
3312 if (attr
.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_CENTRE
)
3314 pos
.x
= (rect
.GetWidth() - size
.x
)/2 + pos
.x
;
3315 line
->SetPosition(pos
);
3317 else if (attr
.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_RIGHT
)
3319 pos
.x
= pos
.x
+ rect
.GetWidth() - size
.x
;
3320 line
->SetPosition(pos
);
3323 node
= node
->GetNext();
3327 /// Insert text at the given position
3328 bool wxRichTextParagraph::InsertText(long pos
, const wxString
& text
)
3330 wxRichTextObject
* childToUse
= NULL
;
3331 wxRichTextObjectList::compatibility_iterator nodeToUse
= wxRichTextObjectList::compatibility_iterator();
3333 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3336 wxRichTextObject
* child
= node
->GetData();
3337 if (child
->GetRange().Contains(pos
) && child
->GetRange().GetLength() > 0)
3344 node
= node
->GetNext();
3349 wxRichTextPlainText
* textObject
= wxDynamicCast(childToUse
, wxRichTextPlainText
);
3352 int posInString
= pos
- textObject
->GetRange().GetStart();
3354 wxString newText
= textObject
->GetText().Mid(0, posInString
) +
3355 text
+ textObject
->GetText().Mid(posInString
);
3356 textObject
->SetText(newText
);
3358 int textLength
= text
.length();
3360 textObject
->SetRange(wxRichTextRange(textObject
->GetRange().GetStart(),
3361 textObject
->GetRange().GetEnd() + textLength
));
3363 // Increment the end range of subsequent fragments in this paragraph.
3364 // We'll set the paragraph range itself at a higher level.
3366 wxRichTextObjectList::compatibility_iterator node
= nodeToUse
->GetNext();
3369 wxRichTextObject
* child
= node
->GetData();
3370 child
->SetRange(wxRichTextRange(textObject
->GetRange().GetStart() + textLength
,
3371 textObject
->GetRange().GetEnd() + textLength
));
3373 node
= node
->GetNext();
3380 // TODO: if not a text object, insert at closest position, e.g. in front of it
3386 // Don't pass parent initially to suppress auto-setting of parent range.
3387 // We'll do that at a higher level.
3388 wxRichTextPlainText
* textObject
= new wxRichTextPlainText(text
, this);
3390 AppendChild(textObject
);
3397 void wxRichTextParagraph::Copy(const wxRichTextParagraph
& obj
)
3399 wxRichTextBox::Copy(obj
);
3402 /// Clear the cached lines
3403 void wxRichTextParagraph::ClearLines()
3405 WX_CLEAR_LIST(wxRichTextLineList
, m_cachedLines
);
3408 /// Get/set the object size for the given range. Returns false if the range
3409 /// is invalid for this object.
3410 bool wxRichTextParagraph::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
) const
3412 if (!range
.IsWithin(GetRange()))
3415 if (flags
& wxRICHTEXT_UNFORMATTED
)
3417 // Just use unformatted data, assume no line breaks
3418 // TODO: take into account line breaks
3422 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3425 wxRichTextObject
* child
= node
->GetData();
3426 if (!child
->GetRange().IsOutside(range
))
3430 wxRichTextRange rangeToUse
= range
;
3431 rangeToUse
.LimitTo(child
->GetRange());
3432 int childDescent
= 0;
3434 if (child
->GetRangeSize(rangeToUse
, childSize
, childDescent
, dc
, flags
, wxPoint(position
.x
+ sz
.x
, position
.y
)))
3436 sz
.y
= wxMax(sz
.y
, childSize
.y
);
3437 sz
.x
+= childSize
.x
;
3438 descent
= wxMax(descent
, childDescent
);
3442 node
= node
->GetNext();
3448 // Use formatted data, with line breaks
3451 // We're going to loop through each line, and then for each line,
3452 // call GetRangeSize for the fragment that comprises that line.
3453 // Only we have to do that multiple times within the line, because
3454 // the line may be broken into pieces. For now ignore line break commands
3455 // (so we can assume that getting the unformatted size for a fragment
3456 // within a line is the actual size)
3458 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3461 wxRichTextLine
* line
= node
->GetData();
3462 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3463 if (!lineRange
.IsOutside(range
))
3467 wxRichTextObjectList::compatibility_iterator node2
= m_children
.GetFirst();
3470 wxRichTextObject
* child
= node2
->GetData();
3472 if (!child
->GetRange().IsOutside(lineRange
))
3474 wxRichTextRange rangeToUse
= lineRange
;
3475 rangeToUse
.LimitTo(child
->GetRange());
3478 int childDescent
= 0;
3479 if (child
->GetRangeSize(rangeToUse
, childSize
, childDescent
, dc
, flags
, wxPoint(position
.x
+ sz
.x
, position
.y
)))
3481 lineSize
.y
= wxMax(lineSize
.y
, childSize
.y
);
3482 lineSize
.x
+= childSize
.x
;
3484 descent
= wxMax(descent
, childDescent
);
3487 node2
= node2
->GetNext();
3490 // Increase size by a line (TODO: paragraph spacing)
3492 sz
.x
= wxMax(sz
.x
, lineSize
.x
);
3494 node
= node
->GetNext();
3501 /// Finds the absolute position and row height for the given character position
3502 bool wxRichTextParagraph::FindPosition(wxDC
& dc
, long index
, wxPoint
& pt
, int* height
, bool forceLineStart
)
3506 wxRichTextLine
* line
= ((wxRichTextParagraphLayoutBox
*)GetParent())->GetLineAtPosition(0);
3508 *height
= line
->GetSize().y
;
3510 *height
= dc
.GetCharHeight();
3512 // -1 means 'the start of the buffer'.
3515 pt
= pt
+ line
->GetPosition();
3520 // The final position in a paragraph is taken to mean the position
3521 // at the start of the next paragraph.
3522 if (index
== GetRange().GetEnd())
3524 wxRichTextParagraphLayoutBox
* parent
= wxDynamicCast(GetParent(), wxRichTextParagraphLayoutBox
);
3525 wxASSERT( parent
!= NULL
);
3527 // Find the height at the next paragraph, if any
3528 wxRichTextLine
* line
= parent
->GetLineAtPosition(index
+ 1);
3531 *height
= line
->GetSize().y
;
3532 pt
= line
->GetAbsolutePosition();
3536 *height
= dc
.GetCharHeight();
3537 int indent
= ConvertTenthsMMToPixels(dc
, m_attributes
.GetLeftIndent());
3538 pt
= wxPoint(indent
, GetCachedSize().y
);
3544 if (index
< GetRange().GetStart() || index
> GetRange().GetEnd())
3547 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3550 wxRichTextLine
* line
= node
->GetData();
3551 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3552 if (index
>= lineRange
.GetStart() && index
<= lineRange
.GetEnd())
3554 // If this is the last point in the line, and we're forcing the
3555 // returned value to be the start of the next line, do the required
3557 if (index
== lineRange
.GetEnd() && forceLineStart
)
3559 if (node
->GetNext())
3561 wxRichTextLine
* nextLine
= node
->GetNext()->GetData();
3562 *height
= nextLine
->GetSize().y
;
3563 pt
= nextLine
->GetAbsolutePosition();
3568 pt
.y
= line
->GetPosition().y
+ GetPosition().y
;
3570 wxRichTextRange
r(lineRange
.GetStart(), index
);
3574 // We find the size of the line up to this point,
3575 // then we can add this size to the line start position and
3576 // paragraph start position to find the actual position.
3578 if (GetRangeSize(r
, rangeSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, line
->GetPosition()+ GetPosition()))
3580 pt
.x
= line
->GetPosition().x
+ GetPosition().x
+ rangeSize
.x
;
3581 *height
= line
->GetSize().y
;
3588 node
= node
->GetNext();
3594 /// Hit-testing: returns a flag indicating hit test details, plus
3595 /// information about position
3596 int wxRichTextParagraph::HitTest(wxDC
& dc
, const wxPoint
& pt
, long& textPosition
)
3598 wxPoint paraPos
= GetPosition();
3600 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3603 wxRichTextLine
* line
= node
->GetData();
3604 wxPoint linePos
= paraPos
+ line
->GetPosition();
3605 wxSize lineSize
= line
->GetSize();
3606 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3608 if (pt
.y
>= linePos
.y
&& pt
.y
<= linePos
.y
+ lineSize
.y
)
3610 if (pt
.x
< linePos
.x
)
3612 textPosition
= lineRange
.GetStart();
3613 return wxRICHTEXT_HITTEST_BEFORE
|wxRICHTEXT_HITTEST_OUTSIDE
;
3615 else if (pt
.x
>= (linePos
.x
+ lineSize
.x
))
3617 textPosition
= lineRange
.GetEnd();
3618 return wxRICHTEXT_HITTEST_AFTER
|wxRICHTEXT_HITTEST_OUTSIDE
;
3623 int lastX
= linePos
.x
;
3624 for (i
= lineRange
.GetStart(); i
<= lineRange
.GetEnd(); i
++)
3629 wxRichTextRange
rangeToUse(lineRange
.GetStart(), i
);
3631 GetRangeSize(rangeToUse
, childSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, linePos
);
3633 int nextX
= childSize
.x
+ linePos
.x
;
3635 if (pt
.x
>= lastX
&& pt
.x
<= nextX
)
3639 // So now we know it's between i-1 and i.
3640 // Let's see if we can be more precise about
3641 // which side of the position it's on.
3643 int midPoint
= (nextX
- lastX
)/2 + lastX
;
3644 if (pt
.x
>= midPoint
)
3645 return wxRICHTEXT_HITTEST_AFTER
;
3647 return wxRICHTEXT_HITTEST_BEFORE
;
3657 node
= node
->GetNext();
3660 return wxRICHTEXT_HITTEST_NONE
;
3663 /// Split an object at this position if necessary, and return
3664 /// the previous object, or NULL if inserting at beginning.
3665 wxRichTextObject
* wxRichTextParagraph::SplitAt(long pos
, wxRichTextObject
** previousObject
)
3667 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3670 wxRichTextObject
* child
= node
->GetData();
3672 if (pos
== child
->GetRange().GetStart())
3676 if (node
->GetPrevious())
3677 *previousObject
= node
->GetPrevious()->GetData();
3679 *previousObject
= NULL
;
3685 if (child
->GetRange().Contains(pos
))
3687 // This should create a new object, transferring part of
3688 // the content to the old object and the rest to the new object.
3689 wxRichTextObject
* newObject
= child
->DoSplit(pos
);
3691 // If we couldn't split this object, just insert in front of it.
3694 // Maybe this is an empty string, try the next one
3699 // Insert the new object after 'child'
3700 if (node
->GetNext())
3701 m_children
.Insert(node
->GetNext(), newObject
);
3703 m_children
.Append(newObject
);
3704 newObject
->SetParent(this);
3707 *previousObject
= child
;
3713 node
= node
->GetNext();
3716 *previousObject
= NULL
;
3720 /// Move content to a list from obj on
3721 void wxRichTextParagraph::MoveToList(wxRichTextObject
* obj
, wxList
& list
)
3723 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(obj
);
3726 wxRichTextObject
* child
= node
->GetData();
3729 wxRichTextObjectList::compatibility_iterator oldNode
= node
;
3731 node
= node
->GetNext();
3733 m_children
.DeleteNode(oldNode
);
3737 /// Add content back from list
3738 void wxRichTextParagraph::MoveFromList(wxList
& list
)
3740 for (wxList::compatibility_iterator node
= list
.GetFirst(); node
; node
= node
->GetNext())
3742 AppendChild((wxRichTextObject
*) node
->GetData());
3747 void wxRichTextParagraph::CalculateRange(long start
, long& end
)
3749 wxRichTextCompositeObject::CalculateRange(start
, end
);
3751 // Add one for end of paragraph
3754 m_range
.SetRange(start
, end
);
3757 /// Find the object at the given position
3758 wxRichTextObject
* wxRichTextParagraph::FindObjectAtPosition(long position
)
3760 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3763 wxRichTextObject
* obj
= node
->GetData();
3764 if (obj
->GetRange().Contains(position
))
3767 node
= node
->GetNext();
3772 /// Get the plain text searching from the start or end of the range.
3773 /// The resulting string may be shorter than the range given.
3774 bool wxRichTextParagraph::GetContiguousPlainText(wxString
& text
, const wxRichTextRange
& range
, bool fromStart
)
3776 text
= wxEmptyString
;
3780 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3783 wxRichTextObject
* obj
= node
->GetData();
3784 if (!obj
->GetRange().IsOutside(range
))
3786 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
3789 text
+= textObj
->GetTextForRange(range
);
3795 node
= node
->GetNext();
3800 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetLast();
3803 wxRichTextObject
* obj
= node
->GetData();
3804 if (!obj
->GetRange().IsOutside(range
))
3806 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
3809 text
= textObj
->GetTextForRange(range
) + text
;
3815 node
= node
->GetPrevious();
3822 /// Find a suitable wrap position.
3823 bool wxRichTextParagraph::FindWrapPosition(const wxRichTextRange
& range
, wxDC
& dc
, int availableSpace
, long& wrapPosition
)
3825 // Find the first position where the line exceeds the available space.
3828 long breakPosition
= range
.GetEnd();
3829 for (i
= range
.GetStart(); i
<= range
.GetEnd(); i
++)
3832 GetRangeSize(wxRichTextRange(range
.GetStart(), i
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
3834 if (sz
.x
> availableSpace
)
3836 breakPosition
= i
-1;
3841 // Now we know the last position on the line.
3842 // Let's try to find a word break.
3845 if (GetContiguousPlainText(plainText
, wxRichTextRange(range
.GetStart(), breakPosition
), false))
3847 int newLinePos
= plainText
.Find(wxRichTextLineBreakChar
);
3848 if (newLinePos
!= wxNOT_FOUND
)
3850 breakPosition
= wxMax(0, range
.GetStart() + newLinePos
);
3854 int spacePos
= plainText
.Find(wxT(' '), true);
3855 int tabPos
= plainText
.Find(wxT('\t'), true);
3856 int pos
= wxMax(spacePos
, tabPos
);
3857 if (pos
!= wxNOT_FOUND
)
3859 int positionsFromEndOfString
= plainText
.length() - pos
- 1;
3860 breakPosition
= breakPosition
- positionsFromEndOfString
;
3865 wrapPosition
= breakPosition
;
3870 /// Get the bullet text for this paragraph.
3871 wxString
wxRichTextParagraph::GetBulletText()
3873 if (GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE
||
3874 (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP
))
3875 return wxEmptyString
;
3877 int number
= GetAttributes().GetBulletNumber();
3880 if ((GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ARABIC
) || (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
))
3882 text
.Printf(wxT("%d"), number
);
3884 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER
)
3886 // TODO: Unicode, and also check if number > 26
3887 text
.Printf(wxT("%c"), (wxChar
) (number
+64));
3889 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER
)
3891 // TODO: Unicode, and also check if number > 26
3892 text
.Printf(wxT("%c"), (wxChar
) (number
+96));
3894 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER
)
3896 text
= wxRichTextDecimalToRoman(number
);
3898 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER
)
3900 text
= wxRichTextDecimalToRoman(number
);
3903 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL
)
3905 text
= GetAttributes().GetBulletText();
3908 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
)
3910 // The outline style relies on the text being computed statically,
3911 // since it depends on other levels points (e.g. 1.2.1.1). So normally the bullet text
3912 // should be stored in the attributes; if not, just use the number for this
3913 // level, as previously computed.
3914 if (!GetAttributes().GetBulletText().IsEmpty())
3915 text
= GetAttributes().GetBulletText();
3918 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PARENTHESES
)
3920 text
= wxT("(") + text
+ wxT(")");
3922 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS
)
3924 text
= text
+ wxT(")");
3927 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PERIOD
)
3935 /// Allocate or reuse a line object
3936 wxRichTextLine
* wxRichTextParagraph::AllocateLine(int pos
)
3938 if (pos
< (int) m_cachedLines
.GetCount())
3940 wxRichTextLine
* line
= m_cachedLines
.Item(pos
)->GetData();
3946 wxRichTextLine
* line
= new wxRichTextLine(this);
3947 m_cachedLines
.Append(line
);
3952 /// Clear remaining unused line objects, if any
3953 bool wxRichTextParagraph::ClearUnusedLines(int lineCount
)
3955 int cachedLineCount
= m_cachedLines
.GetCount();
3956 if ((int) cachedLineCount
> lineCount
)
3958 for (int i
= 0; i
< (int) (cachedLineCount
- lineCount
); i
++)
3960 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetLast();
3961 wxRichTextLine
* line
= node
->GetData();
3962 m_cachedLines
.Erase(node
);
3969 /// Get combined attributes of the base style, paragraph style and character style. We use this to dynamically
3970 /// retrieve the actual style.
3971 wxTextAttr
wxRichTextParagraph::GetCombinedAttributes(const wxTextAttr
& contentStyle
) const
3974 wxRichTextBuffer
* buf
= wxDynamicCast(GetParent(), wxRichTextBuffer
);
3977 attr
= buf
->GetBasicStyle();
3978 wxRichTextApplyStyle(attr
, GetAttributes());
3981 attr
= GetAttributes();
3983 wxRichTextApplyStyle(attr
, contentStyle
);
3987 /// Get combined attributes of the base style and paragraph style.
3988 wxTextAttr
wxRichTextParagraph::GetCombinedAttributes() const
3991 wxRichTextBuffer
* buf
= wxDynamicCast(GetParent(), wxRichTextBuffer
);
3994 attr
= buf
->GetBasicStyle();
3995 wxRichTextApplyStyle(attr
, GetAttributes());
3998 attr
= GetAttributes();
4003 /// Create default tabstop array
4004 void wxRichTextParagraph::InitDefaultTabs()
4006 // create a default tab list at 10 mm each.
4007 for (int i
= 0; i
< 20; ++i
)
4009 sm_defaultTabs
.Add(i
*100);
4013 /// Clear default tabstop array
4014 void wxRichTextParagraph::ClearDefaultTabs()
4016 sm_defaultTabs
.Clear();
4019 /// Get the first position from pos that has a line break character.
4020 long wxRichTextParagraph::GetFirstLineBreakPosition(long pos
)
4022 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
4025 wxRichTextObject
* obj
= node
->GetData();
4026 if (pos
>= obj
->GetRange().GetStart() && pos
<= obj
->GetRange().GetEnd())
4028 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
4031 long breakPos
= textObj
->GetFirstLineBreakPosition(pos
);
4036 node
= node
->GetNext();
4043 * This object represents a line in a paragraph, and stores
4044 * offsets from the start of the paragraph representing the
4045 * start and end positions of the line.
4048 wxRichTextLine::wxRichTextLine(wxRichTextParagraph
* parent
)
4054 void wxRichTextLine::Init(wxRichTextParagraph
* parent
)
4057 m_range
.SetRange(-1, -1);
4058 m_pos
= wxPoint(0, 0);
4059 m_size
= wxSize(0, 0);
4064 void wxRichTextLine::Copy(const wxRichTextLine
& obj
)
4066 m_range
= obj
.m_range
;
4069 /// Get the absolute object position
4070 wxPoint
wxRichTextLine::GetAbsolutePosition() const
4072 return m_parent
->GetPosition() + m_pos
;
4075 /// Get the absolute range
4076 wxRichTextRange
wxRichTextLine::GetAbsoluteRange() const
4078 wxRichTextRange
range(m_range
.GetStart() + m_parent
->GetRange().GetStart(), 0);
4079 range
.SetEnd(range
.GetStart() + m_range
.GetLength()-1);
4084 * wxRichTextPlainText
4085 * This object represents a single piece of text.
4088 IMPLEMENT_DYNAMIC_CLASS(wxRichTextPlainText
, wxRichTextObject
)
4090 wxRichTextPlainText::wxRichTextPlainText(const wxString
& text
, wxRichTextObject
* parent
, wxTextAttr
* style
):
4091 wxRichTextObject(parent
)
4094 SetAttributes(*style
);
4099 #define USE_KERNING_FIX 1
4101 // If insufficient tabs are defined, this is the tab width used
4102 #define WIDTH_FOR_DEFAULT_TABS 50
4105 bool wxRichTextPlainText::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int descent
, int WXUNUSED(style
))
4107 wxRichTextParagraph
* para
= wxDynamicCast(GetParent(), wxRichTextParagraph
);
4108 wxASSERT (para
!= NULL
);
4110 wxTextAttr
textAttr(para
? para
->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4112 int offset
= GetRange().GetStart();
4114 // Replace line break characters with spaces
4115 wxString str
= m_text
;
4116 wxString toRemove
= wxRichTextLineBreakChar
;
4117 str
.Replace(toRemove
, wxT(" "));
4119 long len
= range
.GetLength();
4120 wxString stringChunk
= str
.Mid(range
.GetStart() - offset
, (size_t) len
);
4121 if (textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
4122 stringChunk
.MakeUpper();
4124 int charHeight
= dc
.GetCharHeight();
4127 int y
= rect
.y
+ (rect
.height
- charHeight
- (descent
- m_descent
));
4129 // Test for the optimized situations where all is selected, or none
4132 wxFont
font(GetBuffer()->GetFontTable().FindFont(textAttr
));
4135 // (a) All selected.
4136 if (selectionRange
.GetStart() <= range
.GetStart() && selectionRange
.GetEnd() >= range
.GetEnd())
4138 DrawTabbedString(dc
, textAttr
, rect
, stringChunk
, x
, y
, true);
4140 // (b) None selected.
4141 else if (selectionRange
.GetEnd() < range
.GetStart() || selectionRange
.GetStart() > range
.GetEnd())
4143 // Draw all unselected
4144 DrawTabbedString(dc
, textAttr
, rect
, stringChunk
, x
, y
, false);
4148 // (c) Part selected, part not
4149 // Let's draw unselected chunk, selected chunk, then unselected chunk.
4151 dc
.SetBackgroundMode(wxTRANSPARENT
);
4153 // 1. Initial unselected chunk, if any, up until start of selection.
4154 if (selectionRange
.GetStart() > range
.GetStart() && selectionRange
.GetStart() <= range
.GetEnd())
4156 int r1
= range
.GetStart();
4157 int s1
= selectionRange
.GetStart()-1;
4158 int fragmentLen
= s1
- r1
+ 1;
4159 if (fragmentLen
< 0)
4160 wxLogDebug(wxT("Mid(%d, %d"), (int)(r1
- offset
), (int)fragmentLen
);
4161 wxString stringFragment
= str
.Mid(r1
- offset
, fragmentLen
);
4163 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, false);
4166 if (stringChunk
.Find(wxT("\t")) == wxNOT_FOUND
)
4168 // Compensate for kerning difference
4169 wxString
stringFragment2(str
.Mid(r1
- offset
, fragmentLen
+1));
4170 wxString
stringFragment3(str
.Mid(r1
- offset
+ fragmentLen
, 1));
4172 wxCoord w1
, h1
, w2
, h2
, w3
, h3
;
4173 dc
.GetTextExtent(stringFragment
, & w1
, & h1
);
4174 dc
.GetTextExtent(stringFragment2
, & w2
, & h2
);
4175 dc
.GetTextExtent(stringFragment3
, & w3
, & h3
);
4177 int kerningDiff
= (w1
+ w3
) - w2
;
4178 x
= x
- kerningDiff
;
4183 // 2. Selected chunk, if any.
4184 if (selectionRange
.GetEnd() >= range
.GetStart())
4186 int s1
= wxMax(selectionRange
.GetStart(), range
.GetStart());
4187 int s2
= wxMin(selectionRange
.GetEnd(), range
.GetEnd());
4189 int fragmentLen
= s2
- s1
+ 1;
4190 if (fragmentLen
< 0)
4191 wxLogDebug(wxT("Mid(%d, %d"), (int)(s1
- offset
), (int)fragmentLen
);
4192 wxString stringFragment
= str
.Mid(s1
- offset
, fragmentLen
);
4194 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, true);
4197 if (stringChunk
.Find(wxT("\t")) == wxNOT_FOUND
)
4199 // Compensate for kerning difference
4200 wxString
stringFragment2(str
.Mid(s1
- offset
, fragmentLen
+1));
4201 wxString
stringFragment3(str
.Mid(s1
- offset
+ fragmentLen
, 1));
4203 wxCoord w1
, h1
, w2
, h2
, w3
, h3
;
4204 dc
.GetTextExtent(stringFragment
, & w1
, & h1
);
4205 dc
.GetTextExtent(stringFragment2
, & w2
, & h2
);
4206 dc
.GetTextExtent(stringFragment3
, & w3
, & h3
);
4208 int kerningDiff
= (w1
+ w3
) - w2
;
4209 x
= x
- kerningDiff
;
4214 // 3. Remaining unselected chunk, if any
4215 if (selectionRange
.GetEnd() < range
.GetEnd())
4217 int s2
= wxMin(selectionRange
.GetEnd()+1, range
.GetEnd());
4218 int r2
= range
.GetEnd();
4220 int fragmentLen
= r2
- s2
+ 1;
4221 if (fragmentLen
< 0)
4222 wxLogDebug(wxT("Mid(%d, %d"), (int)(s2
- offset
), (int)fragmentLen
);
4223 wxString stringFragment
= str
.Mid(s2
- offset
, fragmentLen
);
4225 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, false);
4232 bool wxRichTextPlainText::DrawTabbedString(wxDC
& dc
, const wxTextAttr
& attr
, const wxRect
& rect
,wxString
& str
, wxCoord
& x
, wxCoord
& y
, bool selected
)
4234 bool hasTabs
= (str
.Find(wxT('\t')) != wxNOT_FOUND
);
4236 wxArrayInt tabArray
;
4240 if (attr
.GetTabs().IsEmpty())
4241 tabArray
= wxRichTextParagraph::GetDefaultTabs();
4243 tabArray
= attr
.GetTabs();
4244 tabCount
= tabArray
.GetCount();
4246 for (int i
= 0; i
< tabCount
; ++i
)
4248 int pos
= tabArray
[i
];
4249 pos
= ConvertTenthsMMToPixels(dc
, pos
);
4256 int nextTabPos
= -1;
4262 wxColour
highlightColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT
));
4263 wxColour
highlightTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT
));
4265 dc
.SetBrush(wxBrush(highlightColour
));
4266 dc
.SetPen(wxPen(highlightColour
));
4267 dc
.SetTextForeground(highlightTextColour
);
4268 dc
.SetBackgroundMode(wxTRANSPARENT
);
4272 dc
.SetTextForeground(attr
.GetTextColour());
4274 if (attr
.HasFlag(wxTEXT_ATTR_BACKGROUND_COLOUR
) && attr
.GetBackgroundColour().IsOk())
4276 dc
.SetBackgroundMode(wxSOLID
);
4277 dc
.SetTextBackground(attr
.GetBackgroundColour());
4280 dc
.SetBackgroundMode(wxTRANSPARENT
);
4285 // the string has a tab
4286 // break up the string at the Tab
4287 wxString stringChunk
= str
.BeforeFirst(wxT('\t'));
4288 str
= str
.AfterFirst(wxT('\t'));
4289 dc
.GetTextExtent(stringChunk
, & w
, & h
);
4291 bool not_found
= true;
4292 for (int i
= 0; i
< tabCount
&& not_found
; ++i
)
4294 nextTabPos
= tabArray
.Item(i
);
4296 // Find the next tab position.
4297 // Even if we're at the end of the tab array, we must still draw the chunk.
4299 if (nextTabPos
> tabPos
|| (i
== (tabCount
- 1)))
4301 if (nextTabPos
<= tabPos
)
4303 int defaultTabWidth
= ConvertTenthsMMToPixels(dc
, WIDTH_FOR_DEFAULT_TABS
);
4304 nextTabPos
= tabPos
+ defaultTabWidth
;
4311 wxRect
selRect(x
, rect
.y
, w
, rect
.GetHeight());
4312 dc
.DrawRectangle(selRect
);
4314 dc
.DrawText(stringChunk
, x
, y
);
4316 if (attr
.HasTextEffects() && (attr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH
))
4318 wxPen oldPen
= dc
.GetPen();
4319 dc
.SetPen(wxPen(attr
.GetTextColour(), 1));
4320 dc
.DrawLine(x
, (int) (y
+(h
/2)+0.5), x
+w
, (int) (y
+(h
/2)+0.5));
4327 hasTabs
= (str
.Find(wxT('\t')) != wxNOT_FOUND
);
4332 dc
.GetTextExtent(str
, & w
, & h
);
4335 wxRect
selRect(x
, rect
.y
, w
, rect
.GetHeight());
4336 dc
.DrawRectangle(selRect
);
4338 dc
.DrawText(str
, x
, y
);
4340 if (attr
.HasTextEffects() && (attr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH
))
4342 wxPen oldPen
= dc
.GetPen();
4343 dc
.SetPen(wxPen(attr
.GetTextColour(), 1));
4344 dc
.DrawLine(x
, (int) (y
+(h
/2)+0.5), x
+w
, (int) (y
+(h
/2)+0.5));
4354 /// Lay the item out
4355 bool wxRichTextPlainText::Layout(wxDC
& dc
, const wxRect
& WXUNUSED(rect
), int WXUNUSED(style
))
4357 GetRangeSize(GetRange(), m_size
, m_descent
, dc
, 0, wxPoint(0, 0));
4363 void wxRichTextPlainText::Copy(const wxRichTextPlainText
& obj
)
4365 wxRichTextObject::Copy(obj
);
4367 m_text
= obj
.m_text
;
4370 /// Get/set the object size for the given range. Returns false if the range
4371 /// is invalid for this object.
4372 bool wxRichTextPlainText::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int WXUNUSED(flags
), wxPoint position
) const
4374 if (!range
.IsWithin(GetRange()))
4377 wxRichTextParagraph
* para
= wxDynamicCast(GetParent(), wxRichTextParagraph
);
4378 wxASSERT (para
!= NULL
);
4380 wxTextAttr
textAttr(para
? para
->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4382 // Always assume unformatted text, since at this level we have no knowledge
4383 // of line breaks - and we don't need it, since we'll calculate size within
4384 // formatted text by doing it in chunks according to the line ranges
4386 wxFont
font(GetBuffer()->GetFontTable().FindFont(textAttr
));
4389 int startPos
= range
.GetStart() - GetRange().GetStart();
4390 long len
= range
.GetLength();
4392 wxString
str(m_text
);
4393 wxString toReplace
= wxRichTextLineBreakChar
;
4394 str
.Replace(toReplace
, wxT(" "));
4396 wxString stringChunk
= str
.Mid(startPos
, (size_t) len
);
4398 if (textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
4399 stringChunk
.MakeUpper();
4403 if (stringChunk
.Find(wxT('\t')) != wxNOT_FOUND
)
4405 // the string has a tab
4406 wxArrayInt tabArray
;
4407 if (textAttr
.GetTabs().IsEmpty())
4408 tabArray
= wxRichTextParagraph::GetDefaultTabs();
4410 tabArray
= textAttr
.GetTabs();
4412 int tabCount
= tabArray
.GetCount();
4414 for (int i
= 0; i
< tabCount
; ++i
)
4416 int pos
= tabArray
[i
];
4417 pos
= ((wxRichTextPlainText
*) this)->ConvertTenthsMMToPixels(dc
, pos
);
4421 int nextTabPos
= -1;
4423 while (stringChunk
.Find(wxT('\t')) >= 0)
4425 // the string has a tab
4426 // break up the string at the Tab
4427 wxString stringFragment
= stringChunk
.BeforeFirst(wxT('\t'));
4428 stringChunk
= stringChunk
.AfterFirst(wxT('\t'));
4429 dc
.GetTextExtent(stringFragment
, & w
, & h
);
4431 int absoluteWidth
= width
+ position
.x
;
4433 bool notFound
= true;
4434 for (int i
= 0; i
< tabCount
&& notFound
; ++i
)
4436 nextTabPos
= tabArray
.Item(i
);
4438 // Find the next tab position.
4439 // Even if we're at the end of the tab array, we must still process the chunk.
4441 if (nextTabPos
> absoluteWidth
|| (i
== (tabCount
- 1)))
4443 if (nextTabPos
<= absoluteWidth
)
4445 int defaultTabWidth
= ((wxRichTextPlainText
*) this)->ConvertTenthsMMToPixels(dc
, WIDTH_FOR_DEFAULT_TABS
);
4446 nextTabPos
= absoluteWidth
+ defaultTabWidth
;
4450 width
= nextTabPos
- position
.x
;
4455 dc
.GetTextExtent(stringChunk
, & w
, & h
, & descent
);
4457 size
= wxSize(width
, dc
.GetCharHeight());
4462 /// Do a split, returning an object containing the second part, and setting
4463 /// the first part in 'this'.
4464 wxRichTextObject
* wxRichTextPlainText::DoSplit(long pos
)
4466 long index
= pos
- GetRange().GetStart();
4468 if (index
< 0 || index
>= (int) m_text
.length())
4471 wxString firstPart
= m_text
.Mid(0, index
);
4472 wxString secondPart
= m_text
.Mid(index
);
4476 wxRichTextPlainText
* newObject
= new wxRichTextPlainText(secondPart
);
4477 newObject
->SetAttributes(GetAttributes());
4479 newObject
->SetRange(wxRichTextRange(pos
, GetRange().GetEnd()));
4480 GetRange().SetEnd(pos
-1);
4486 void wxRichTextPlainText::CalculateRange(long start
, long& end
)
4488 end
= start
+ m_text
.length() - 1;
4489 m_range
.SetRange(start
, end
);
4493 bool wxRichTextPlainText::DeleteRange(const wxRichTextRange
& range
)
4495 wxRichTextRange r
= range
;
4497 r
.LimitTo(GetRange());
4499 if (r
.GetStart() == GetRange().GetStart() && r
.GetEnd() == GetRange().GetEnd())
4505 long startIndex
= r
.GetStart() - GetRange().GetStart();
4506 long len
= r
.GetLength();
4508 m_text
= m_text
.Mid(0, startIndex
) + m_text
.Mid(startIndex
+len
);
4512 /// Get text for the given range.
4513 wxString
wxRichTextPlainText::GetTextForRange(const wxRichTextRange
& range
) const
4515 wxRichTextRange r
= range
;
4517 r
.LimitTo(GetRange());
4519 long startIndex
= r
.GetStart() - GetRange().GetStart();
4520 long len
= r
.GetLength();
4522 return m_text
.Mid(startIndex
, len
);
4525 /// Returns true if this object can merge itself with the given one.
4526 bool wxRichTextPlainText::CanMerge(wxRichTextObject
* object
) const
4528 return object
->GetClassInfo() == CLASSINFO(wxRichTextPlainText
) &&
4529 (m_text
.empty() || wxTextAttrEq(GetAttributes(), object
->GetAttributes()));
4532 /// Returns true if this object merged itself with the given one.
4533 /// The calling code will then delete the given object.
4534 bool wxRichTextPlainText::Merge(wxRichTextObject
* object
)
4536 wxRichTextPlainText
* textObject
= wxDynamicCast(object
, wxRichTextPlainText
);
4537 wxASSERT( textObject
!= NULL
);
4541 m_text
+= textObject
->GetText();
4548 /// Dump to output stream for debugging
4549 void wxRichTextPlainText::Dump(wxTextOutputStream
& stream
)
4551 wxRichTextObject::Dump(stream
);
4552 stream
<< m_text
<< wxT("\n");
4555 /// Get the first position from pos that has a line break character.
4556 long wxRichTextPlainText::GetFirstLineBreakPosition(long pos
)
4559 int len
= m_text
.length();
4560 int startPos
= pos
- m_range
.GetStart();
4561 for (i
= startPos
; i
< len
; i
++)
4563 wxChar ch
= m_text
[i
];
4564 if (ch
== wxRichTextLineBreakChar
)
4566 return i
+ m_range
.GetStart();
4574 * This is a kind of box, used to represent the whole buffer
4577 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBuffer
, wxRichTextParagraphLayoutBox
)
4579 wxList
wxRichTextBuffer::sm_handlers
;
4580 wxRichTextRenderer
* wxRichTextBuffer::sm_renderer
= NULL
;
4581 int wxRichTextBuffer::sm_bulletRightMargin
= 20;
4582 float wxRichTextBuffer::sm_bulletProportion
= (float) 0.3;
4585 void wxRichTextBuffer::Init()
4587 m_commandProcessor
= new wxCommandProcessor
;
4588 m_styleSheet
= NULL
;
4590 m_batchedCommandDepth
= 0;
4591 m_batchedCommand
= NULL
;
4598 wxRichTextBuffer::~wxRichTextBuffer()
4600 delete m_commandProcessor
;
4601 delete m_batchedCommand
;
4604 ClearEventHandlers();
4607 void wxRichTextBuffer::ResetAndClearCommands()
4611 GetCommandProcessor()->ClearCommands();
4614 Invalidate(wxRICHTEXT_ALL
);
4617 void wxRichTextBuffer::Copy(const wxRichTextBuffer
& obj
)
4619 wxRichTextParagraphLayoutBox::Copy(obj
);
4621 m_styleSheet
= obj
.m_styleSheet
;
4622 m_modified
= obj
.m_modified
;
4623 m_batchedCommandDepth
= obj
.m_batchedCommandDepth
;
4624 m_batchedCommand
= obj
.m_batchedCommand
;
4625 m_suppressUndo
= obj
.m_suppressUndo
;
4628 /// Push style sheet to top of stack
4629 bool wxRichTextBuffer::PushStyleSheet(wxRichTextStyleSheet
* styleSheet
)
4632 styleSheet
->InsertSheet(m_styleSheet
);
4634 SetStyleSheet(styleSheet
);
4639 /// Pop style sheet from top of stack
4640 wxRichTextStyleSheet
* wxRichTextBuffer::PopStyleSheet()
4644 wxRichTextStyleSheet
* oldSheet
= m_styleSheet
;
4645 m_styleSheet
= oldSheet
->GetNextSheet();
4654 /// Submit command to insert paragraphs
4655 bool wxRichTextBuffer::InsertParagraphsWithUndo(long pos
, const wxRichTextParagraphLayoutBox
& paragraphs
, wxRichTextCtrl
* ctrl
, int flags
)
4657 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4659 wxTextAttr
attr(GetDefaultStyle());
4661 wxTextAttr
* p
= NULL
;
4662 wxTextAttr paraAttr
;
4663 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4665 paraAttr
= GetStyleForNewParagraph(pos
);
4666 if (!paraAttr
.IsDefault())
4672 action
->GetNewParagraphs() = paragraphs
;
4676 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetLast();
4679 wxRichTextParagraph
* obj
= (wxRichTextParagraph
*) node
->GetData();
4680 obj
->SetAttributes(*p
);
4681 node
= node
->GetPrevious();
4685 action
->SetPosition(pos
);
4687 // Set the range we'll need to delete in Undo
4688 action
->SetRange(wxRichTextRange(pos
, pos
+ paragraphs
.GetRange().GetEnd() - 1));
4690 SubmitAction(action
);
4695 /// Submit command to insert the given text
4696 bool wxRichTextBuffer::InsertTextWithUndo(long pos
, const wxString
& text
, wxRichTextCtrl
* ctrl
, int flags
)
4698 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4700 wxTextAttr
* p
= NULL
;
4701 wxTextAttr paraAttr
;
4702 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4704 // Get appropriate paragraph style
4705 paraAttr
= GetStyleForNewParagraph(pos
, false, false);
4706 if (!paraAttr
.IsDefault())
4710 action
->GetNewParagraphs().AddParagraphs(text
, p
);
4712 int length
= action
->GetNewParagraphs().GetRange().GetLength();
4714 if (text
.length() > 0 && text
.Last() != wxT('\n'))
4716 // Don't count the newline when undoing
4718 action
->GetNewParagraphs().SetPartialParagraph(true);
4720 else if (text
.length() > 0 && text
.Last() == wxT('\n'))
4723 action
->SetPosition(pos
);
4725 // Set the range we'll need to delete in Undo
4726 action
->SetRange(wxRichTextRange(pos
, pos
+ length
- 1));
4728 SubmitAction(action
);
4733 /// Submit command to insert the given text
4734 bool wxRichTextBuffer::InsertNewlineWithUndo(long pos
, wxRichTextCtrl
* ctrl
, int flags
)
4736 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4738 wxTextAttr
* p
= NULL
;
4739 wxTextAttr paraAttr
;
4740 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4742 paraAttr
= GetStyleForNewParagraph(pos
, false, true /* look for next paragraph style */);
4743 if (!paraAttr
.IsDefault())
4747 wxTextAttr
attr(GetDefaultStyle());
4749 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(wxEmptyString
, this, & attr
);
4750 action
->GetNewParagraphs().AppendChild(newPara
);
4751 action
->GetNewParagraphs().UpdateRanges();
4752 action
->GetNewParagraphs().SetPartialParagraph(false);
4753 action
->SetPosition(pos
);
4756 newPara
->SetAttributes(*p
);
4758 // Set the range we'll need to delete in Undo
4759 action
->SetRange(wxRichTextRange(pos
, pos
));
4761 SubmitAction(action
);
4766 /// Submit command to insert the given image
4767 bool wxRichTextBuffer::InsertImageWithUndo(long pos
, const wxRichTextImageBlock
& imageBlock
, wxRichTextCtrl
* ctrl
, int flags
)
4769 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Image"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4771 wxTextAttr
* p
= NULL
;
4772 wxTextAttr paraAttr
;
4773 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4775 paraAttr
= GetStyleForNewParagraph(pos
);
4776 if (!paraAttr
.IsDefault())
4780 wxTextAttr
attr(GetDefaultStyle());
4782 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(this, & attr
);
4784 newPara
->SetAttributes(*p
);
4786 wxRichTextImage
* imageObject
= new wxRichTextImage(imageBlock
, newPara
);
4787 newPara
->AppendChild(imageObject
);
4788 action
->GetNewParagraphs().AppendChild(newPara
);
4789 action
->GetNewParagraphs().UpdateRanges();
4791 action
->GetNewParagraphs().SetPartialParagraph(true);
4793 action
->SetPosition(pos
);
4795 // Set the range we'll need to delete in Undo
4796 action
->SetRange(wxRichTextRange(pos
, pos
));
4798 SubmitAction(action
);
4803 /// Get the style that is appropriate for a new paragraph at this position.
4804 /// If the previous paragraph has a paragraph style name, look up the next-paragraph
4806 wxTextAttr
wxRichTextBuffer::GetStyleForNewParagraph(long pos
, bool caretPosition
, bool lookUpNewParaStyle
) const
4808 wxRichTextParagraph
* para
= GetParagraphAtPosition(pos
, caretPosition
);
4812 bool foundAttributes
= false;
4814 // Look for a matching paragraph style
4815 if (lookUpNewParaStyle
&& !para
->GetAttributes().GetParagraphStyleName().IsEmpty() && GetStyleSheet())
4817 wxRichTextParagraphStyleDefinition
* paraDef
= GetStyleSheet()->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
4820 // If we're not at the end of the paragraph, then we apply THIS style, and not the designated next style.
4821 if (para
->GetRange().GetEnd() == pos
&& !paraDef
->GetNextStyle().IsEmpty())
4823 wxRichTextParagraphStyleDefinition
* nextParaDef
= GetStyleSheet()->FindParagraphStyle(paraDef
->GetNextStyle());
4826 foundAttributes
= true;
4827 attr
= nextParaDef
->GetStyleMergedWithBase(GetStyleSheet());
4831 // If we didn't find the 'next style', use this style instead.
4832 if (!foundAttributes
)
4834 foundAttributes
= true;
4835 attr
= paraDef
->GetStyleMergedWithBase(GetStyleSheet());
4839 if (!foundAttributes
)
4841 attr
= para
->GetAttributes();
4842 int flags
= attr
.GetFlags();
4844 // Eliminate character styles
4845 flags
&= ( (~ wxTEXT_ATTR_FONT
) |
4846 (~ wxTEXT_ATTR_TEXT_COLOUR
) |
4847 (~ wxTEXT_ATTR_BACKGROUND_COLOUR
) );
4848 attr
.SetFlags(flags
);
4851 // Now see if we need to number the paragraph.
4852 if (attr
.HasBulletStyle())
4854 wxTextAttr numberingAttr
;
4855 if (FindNextParagraphNumber(para
, numberingAttr
))
4856 wxRichTextApplyStyle(attr
, (const wxTextAttr
&) numberingAttr
);
4862 return wxTextAttr();
4865 /// Submit command to delete this range
4866 bool wxRichTextBuffer::DeleteRangeWithUndo(const wxRichTextRange
& range
, wxRichTextCtrl
* ctrl
)
4868 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Delete"), wxRICHTEXT_DELETE
, this, ctrl
);
4870 action
->SetPosition(ctrl
->GetCaretPosition());
4872 // Set the range to delete
4873 action
->SetRange(range
);
4875 // Copy the fragment that we'll need to restore in Undo
4876 CopyFragment(range
, action
->GetOldParagraphs());
4878 // Special case: if there is only one (non-partial) paragraph,
4879 // we must save the *next* paragraph's style, because that
4880 // is the style we must apply when inserting the content back
4881 // when undoing the delete. (This is because we're merging the
4882 // paragraph with the previous paragraph and throwing away
4883 // the style, and we need to restore it.)
4884 if (!action
->GetOldParagraphs().GetPartialParagraph() && action
->GetOldParagraphs().GetChildCount() == 1)
4886 wxRichTextParagraph
* lastPara
= GetParagraphAtPosition(range
.GetStart());
4889 wxRichTextParagraph
* nextPara
= GetParagraphAtPosition(range
.GetEnd()+1);
4892 wxRichTextParagraph
* para
= (wxRichTextParagraph
*) action
->GetOldParagraphs().GetChild(0);
4893 para
->SetAttributes(nextPara
->GetAttributes());
4898 SubmitAction(action
);
4903 /// Collapse undo/redo commands
4904 bool wxRichTextBuffer::BeginBatchUndo(const wxString
& cmdName
)
4906 if (m_batchedCommandDepth
== 0)
4908 wxASSERT(m_batchedCommand
== NULL
);
4909 if (m_batchedCommand
)
4911 GetCommandProcessor()->Submit(m_batchedCommand
);
4913 m_batchedCommand
= new wxRichTextCommand(cmdName
);
4916 m_batchedCommandDepth
++;
4921 /// Collapse undo/redo commands
4922 bool wxRichTextBuffer::EndBatchUndo()
4924 m_batchedCommandDepth
--;
4926 wxASSERT(m_batchedCommandDepth
>= 0);
4927 wxASSERT(m_batchedCommand
!= NULL
);
4929 if (m_batchedCommandDepth
== 0)
4931 GetCommandProcessor()->Submit(m_batchedCommand
);
4932 m_batchedCommand
= NULL
;
4938 /// Submit immediately, or delay according to whether collapsing is on
4939 bool wxRichTextBuffer::SubmitAction(wxRichTextAction
* action
)
4941 if (BatchingUndo() && m_batchedCommand
&& !SuppressingUndo())
4942 m_batchedCommand
->AddAction(action
);
4945 wxRichTextCommand
* cmd
= new wxRichTextCommand(action
->GetName());
4946 cmd
->AddAction(action
);
4948 // Only store it if we're not suppressing undo.
4949 return GetCommandProcessor()->Submit(cmd
, !SuppressingUndo());
4955 /// Begin suppressing undo/redo commands.
4956 bool wxRichTextBuffer::BeginSuppressUndo()
4963 /// End suppressing undo/redo commands.
4964 bool wxRichTextBuffer::EndSuppressUndo()
4971 /// Begin using a style
4972 bool wxRichTextBuffer::BeginStyle(const wxTextAttr
& style
)
4974 wxTextAttr
newStyle(GetDefaultStyle());
4976 // Save the old default style
4977 m_attributeStack
.Append((wxObject
*) new wxTextAttr(GetDefaultStyle()));
4979 wxRichTextApplyStyle(newStyle
, style
);
4980 newStyle
.SetFlags(style
.GetFlags()|newStyle
.GetFlags());
4982 SetDefaultStyle(newStyle
);
4984 // wxLogDebug("Default style size = %d", GetDefaultStyle().GetFont().GetPointSize());
4990 bool wxRichTextBuffer::EndStyle()
4992 if (!m_attributeStack
.GetFirst())
4994 wxLogDebug(_("Too many EndStyle calls!"));
4998 wxList::compatibility_iterator node
= m_attributeStack
.GetLast();
4999 wxTextAttr
* attr
= (wxTextAttr
*)node
->GetData();
5000 m_attributeStack
.Erase(node
);
5002 SetDefaultStyle(*attr
);
5009 bool wxRichTextBuffer::EndAllStyles()
5011 while (m_attributeStack
.GetCount() != 0)
5016 /// Clear the style stack
5017 void wxRichTextBuffer::ClearStyleStack()
5019 for (wxList::compatibility_iterator node
= m_attributeStack
.GetFirst(); node
; node
= node
->GetNext())
5020 delete (wxTextAttr
*) node
->GetData();
5021 m_attributeStack
.Clear();
5024 /// Begin using bold
5025 bool wxRichTextBuffer::BeginBold()
5028 attr
.SetFontWeight(wxBOLD
);
5030 return BeginStyle(attr
);
5033 /// Begin using italic
5034 bool wxRichTextBuffer::BeginItalic()
5037 attr
.SetFontStyle(wxITALIC
);
5039 return BeginStyle(attr
);
5042 /// Begin using underline
5043 bool wxRichTextBuffer::BeginUnderline()
5046 attr
.SetFontUnderlined(true);
5048 return BeginStyle(attr
);
5051 /// Begin using point size
5052 bool wxRichTextBuffer::BeginFontSize(int pointSize
)
5055 attr
.SetFontSize(pointSize
);
5057 return BeginStyle(attr
);
5060 /// Begin using this font
5061 bool wxRichTextBuffer::BeginFont(const wxFont
& font
)
5066 return BeginStyle(attr
);
5069 /// Begin using this colour
5070 bool wxRichTextBuffer::BeginTextColour(const wxColour
& colour
)
5073 attr
.SetFlags(wxTEXT_ATTR_TEXT_COLOUR
);
5074 attr
.SetTextColour(colour
);
5076 return BeginStyle(attr
);
5079 /// Begin using alignment
5080 bool wxRichTextBuffer::BeginAlignment(wxTextAttrAlignment alignment
)
5083 attr
.SetFlags(wxTEXT_ATTR_ALIGNMENT
);
5084 attr
.SetAlignment(alignment
);
5086 return BeginStyle(attr
);
5089 /// Begin left indent
5090 bool wxRichTextBuffer::BeginLeftIndent(int leftIndent
, int leftSubIndent
)
5093 attr
.SetFlags(wxTEXT_ATTR_LEFT_INDENT
);
5094 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5096 return BeginStyle(attr
);
5099 /// Begin right indent
5100 bool wxRichTextBuffer::BeginRightIndent(int rightIndent
)
5103 attr
.SetFlags(wxTEXT_ATTR_RIGHT_INDENT
);
5104 attr
.SetRightIndent(rightIndent
);
5106 return BeginStyle(attr
);
5109 /// Begin paragraph spacing
5110 bool wxRichTextBuffer::BeginParagraphSpacing(int before
, int after
)
5114 flags
|= wxTEXT_ATTR_PARA_SPACING_BEFORE
;
5116 flags
|= wxTEXT_ATTR_PARA_SPACING_AFTER
;
5119 attr
.SetFlags(flags
);
5120 attr
.SetParagraphSpacingBefore(before
);
5121 attr
.SetParagraphSpacingAfter(after
);
5123 return BeginStyle(attr
);
5126 /// Begin line spacing
5127 bool wxRichTextBuffer::BeginLineSpacing(int lineSpacing
)
5130 attr
.SetFlags(wxTEXT_ATTR_LINE_SPACING
);
5131 attr
.SetLineSpacing(lineSpacing
);
5133 return BeginStyle(attr
);
5136 /// Begin numbered bullet
5137 bool wxRichTextBuffer::BeginNumberedBullet(int bulletNumber
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5140 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5141 attr
.SetBulletStyle(bulletStyle
);
5142 attr
.SetBulletNumber(bulletNumber
);
5143 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5145 return BeginStyle(attr
);
5148 /// Begin symbol bullet
5149 bool wxRichTextBuffer::BeginSymbolBullet(const wxString
& symbol
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5152 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5153 attr
.SetBulletStyle(bulletStyle
);
5154 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5155 attr
.SetBulletText(symbol
);
5157 return BeginStyle(attr
);
5160 /// Begin standard bullet
5161 bool wxRichTextBuffer::BeginStandardBullet(const wxString
& bulletName
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5164 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5165 attr
.SetBulletStyle(bulletStyle
);
5166 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5167 attr
.SetBulletName(bulletName
);
5169 return BeginStyle(attr
);
5172 /// Begin named character style
5173 bool wxRichTextBuffer::BeginCharacterStyle(const wxString
& characterStyle
)
5175 if (GetStyleSheet())
5177 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterStyle
);
5180 wxTextAttr attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5181 return BeginStyle(attr
);
5187 /// Begin named paragraph style
5188 bool wxRichTextBuffer::BeginParagraphStyle(const wxString
& paragraphStyle
)
5190 if (GetStyleSheet())
5192 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(paragraphStyle
);
5195 wxTextAttr attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5196 return BeginStyle(attr
);
5202 /// Begin named list style
5203 bool wxRichTextBuffer::BeginListStyle(const wxString
& listStyle
, int level
, int number
)
5205 if (GetStyleSheet())
5207 wxRichTextListStyleDefinition
* def
= GetStyleSheet()->FindListStyle(listStyle
);
5210 wxTextAttr
attr(def
->GetCombinedStyleForLevel(level
));
5212 attr
.SetBulletNumber(number
);
5214 return BeginStyle(attr
);
5221 bool wxRichTextBuffer::BeginURL(const wxString
& url
, const wxString
& characterStyle
)
5225 if (!characterStyle
.IsEmpty() && GetStyleSheet())
5227 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterStyle
);
5230 attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5235 return BeginStyle(attr
);
5238 /// Adds a handler to the end
5239 void wxRichTextBuffer::AddHandler(wxRichTextFileHandler
*handler
)
5241 sm_handlers
.Append(handler
);
5244 /// Inserts a handler at the front
5245 void wxRichTextBuffer::InsertHandler(wxRichTextFileHandler
*handler
)
5247 sm_handlers
.Insert( handler
);
5250 /// Removes a handler
5251 bool wxRichTextBuffer::RemoveHandler(const wxString
& name
)
5253 wxRichTextFileHandler
*handler
= FindHandler(name
);
5256 sm_handlers
.DeleteObject(handler
);
5264 /// Finds a handler by filename or, if supplied, type
5265 wxRichTextFileHandler
*wxRichTextBuffer::FindHandlerFilenameOrType(const wxString
& filename
, int imageType
)
5267 if (imageType
!= wxRICHTEXT_TYPE_ANY
)
5268 return FindHandler(imageType
);
5269 else if (!filename
.IsEmpty())
5271 wxString path
, file
, ext
;
5272 wxSplitPath(filename
, & path
, & file
, & ext
);
5273 return FindHandler(ext
, imageType
);
5280 /// Finds a handler by name
5281 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(const wxString
& name
)
5283 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5286 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5287 if (handler
->GetName().Lower() == name
.Lower()) return handler
;
5289 node
= node
->GetNext();
5294 /// Finds a handler by extension and type
5295 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(const wxString
& extension
, int type
)
5297 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5300 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5301 if ( handler
->GetExtension().Lower() == extension
.Lower() &&
5302 (type
== wxRICHTEXT_TYPE_ANY
|| handler
->GetType() == type
) )
5304 node
= node
->GetNext();
5309 /// Finds a handler by type
5310 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(int type
)
5312 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5315 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5316 if (handler
->GetType() == type
) return handler
;
5317 node
= node
->GetNext();
5322 void wxRichTextBuffer::InitStandardHandlers()
5324 if (!FindHandler(wxRICHTEXT_TYPE_TEXT
))
5325 AddHandler(new wxRichTextPlainTextHandler
);
5328 void wxRichTextBuffer::CleanUpHandlers()
5330 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5333 wxRichTextFileHandler
* handler
= (wxRichTextFileHandler
*)node
->GetData();
5334 wxList::compatibility_iterator next
= node
->GetNext();
5339 sm_handlers
.Clear();
5342 wxString
wxRichTextBuffer::GetExtWildcard(bool combine
, bool save
, wxArrayInt
* types
)
5349 wxList::compatibility_iterator node
= GetHandlers().GetFirst();
5353 wxRichTextFileHandler
* handler
= (wxRichTextFileHandler
*) node
->GetData();
5354 if (handler
->IsVisible() && ((save
&& handler
->CanSave()) || !save
&& handler
->CanLoad()))
5359 wildcard
+= wxT(";");
5360 wildcard
+= wxT("*.") + handler
->GetExtension();
5365 wildcard
+= wxT("|");
5366 wildcard
+= handler
->GetName();
5367 wildcard
+= wxT(" ");
5368 wildcard
+= _("files");
5369 wildcard
+= wxT(" (*.");
5370 wildcard
+= handler
->GetExtension();
5371 wildcard
+= wxT(")|*.");
5372 wildcard
+= handler
->GetExtension();
5374 types
->Add(handler
->GetType());
5379 node
= node
->GetNext();
5383 wildcard
= wxT("(") + wildcard
+ wxT(")|") + wildcard
;
5388 bool wxRichTextBuffer::LoadFile(const wxString
& filename
, int type
)
5390 wxRichTextFileHandler
* handler
= FindHandlerFilenameOrType(filename
, type
);
5393 SetDefaultStyle(wxTextAttr());
5394 handler
->SetFlags(GetHandlerFlags());
5395 bool success
= handler
->LoadFile(this, filename
);
5396 Invalidate(wxRICHTEXT_ALL
);
5404 bool wxRichTextBuffer::SaveFile(const wxString
& filename
, int type
)
5406 wxRichTextFileHandler
* handler
= FindHandlerFilenameOrType(filename
, type
);
5409 handler
->SetFlags(GetHandlerFlags());
5410 return handler
->SaveFile(this, filename
);
5416 /// Load from a stream
5417 bool wxRichTextBuffer::LoadFile(wxInputStream
& stream
, int type
)
5419 wxRichTextFileHandler
* handler
= FindHandler(type
);
5422 SetDefaultStyle(wxTextAttr());
5423 handler
->SetFlags(GetHandlerFlags());
5424 bool success
= handler
->LoadFile(this, stream
);
5425 Invalidate(wxRICHTEXT_ALL
);
5432 /// Save to a stream
5433 bool wxRichTextBuffer::SaveFile(wxOutputStream
& stream
, int type
)
5435 wxRichTextFileHandler
* handler
= FindHandler(type
);
5438 handler
->SetFlags(GetHandlerFlags());
5439 return handler
->SaveFile(this, stream
);
5445 /// Copy the range to the clipboard
5446 bool wxRichTextBuffer::CopyToClipboard(const wxRichTextRange
& range
)
5448 bool success
= false;
5449 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5451 if (!wxTheClipboard
->IsOpened() && wxTheClipboard
->Open())
5453 wxTheClipboard
->Clear();
5455 // Add composite object
5457 wxDataObjectComposite
* compositeObject
= new wxDataObjectComposite();
5460 wxString text
= GetTextForRange(range
);
5463 text
= wxTextFile::Translate(text
, wxTextFileType_Dos
);
5466 compositeObject
->Add(new wxTextDataObject(text
), false /* not preferred */);
5469 // Add rich text buffer data object. This needs the XML handler to be present.
5471 if (FindHandler(wxRICHTEXT_TYPE_XML
))
5473 wxRichTextBuffer
* richTextBuf
= new wxRichTextBuffer
;
5474 CopyFragment(range
, *richTextBuf
);
5476 compositeObject
->Add(new wxRichTextBufferDataObject(richTextBuf
), true /* preferred */);
5479 if (wxTheClipboard
->SetData(compositeObject
))
5482 wxTheClipboard
->Close();
5491 /// Paste the clipboard content to the buffer
5492 bool wxRichTextBuffer::PasteFromClipboard(long position
)
5494 bool success
= false;
5495 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5496 if (CanPasteFromClipboard())
5498 if (wxTheClipboard
->Open())
5500 if (wxTheClipboard
->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())))
5502 wxRichTextBufferDataObject data
;
5503 wxTheClipboard
->GetData(data
);
5504 wxRichTextBuffer
* richTextBuffer
= data
.GetRichTextBuffer();
5507 InsertParagraphsWithUndo(position
+1, *richTextBuffer
, GetRichTextCtrl(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
);
5508 delete richTextBuffer
;
5511 else if (wxTheClipboard
->IsSupported(wxDF_TEXT
) || wxTheClipboard
->IsSupported(wxDF_UNICODETEXT
))
5513 wxTextDataObject data
;
5514 wxTheClipboard
->GetData(data
);
5515 wxString
text(data
.GetText());
5516 text
.Replace(_T("\r\n"), _T("\n"));
5518 InsertTextWithUndo(position
+1, text
, GetRichTextCtrl());
5522 else if (wxTheClipboard
->IsSupported(wxDF_BITMAP
))
5524 wxBitmapDataObject data
;
5525 wxTheClipboard
->GetData(data
);
5526 wxBitmap
bitmap(data
.GetBitmap());
5527 wxImage
image(bitmap
.ConvertToImage());
5529 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Image"), wxRICHTEXT_INSERT
, this, GetRichTextCtrl(), false);
5531 action
->GetNewParagraphs().AddImage(image
);
5533 if (action
->GetNewParagraphs().GetChildCount() == 1)
5534 action
->GetNewParagraphs().SetPartialParagraph(true);
5536 action
->SetPosition(position
);
5538 // Set the range we'll need to delete in Undo
5539 action
->SetRange(wxRichTextRange(position
, position
));
5541 SubmitAction(action
);
5545 wxTheClipboard
->Close();
5549 wxUnusedVar(position
);
5554 /// Can we paste from the clipboard?
5555 bool wxRichTextBuffer::CanPasteFromClipboard() const
5557 bool canPaste
= false;
5558 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5559 if (!wxTheClipboard
->IsOpened() && wxTheClipboard
->Open())
5561 if (wxTheClipboard
->IsSupported(wxDF_TEXT
) || wxTheClipboard
->IsSupported(wxDF_UNICODETEXT
) ||
5562 wxTheClipboard
->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())) ||
5563 wxTheClipboard
->IsSupported(wxDF_BITMAP
))
5567 wxTheClipboard
->Close();
5573 /// Dumps contents of buffer for debugging purposes
5574 void wxRichTextBuffer::Dump()
5578 wxStringOutputStream
stream(& text
);
5579 wxTextOutputStream
textStream(stream
);
5586 /// Add an event handler
5587 bool wxRichTextBuffer::AddEventHandler(wxEvtHandler
* handler
)
5589 m_eventHandlers
.Append(handler
);
5593 /// Remove an event handler
5594 bool wxRichTextBuffer::RemoveEventHandler(wxEvtHandler
* handler
, bool deleteHandler
)
5596 wxList::compatibility_iterator node
= m_eventHandlers
.Find(handler
);
5599 m_eventHandlers
.Erase(node
);
5609 /// Clear event handlers
5610 void wxRichTextBuffer::ClearEventHandlers()
5612 m_eventHandlers
.Clear();
5615 /// Send event to event handlers. If sendToAll is true, will send to all event handlers,
5616 /// otherwise will stop at the first successful one.
5617 bool wxRichTextBuffer::SendEvent(wxEvent
& event
, bool sendToAll
)
5619 bool success
= false;
5620 for (wxList::compatibility_iterator node
= m_eventHandlers
.GetFirst(); node
; node
= node
->GetNext())
5622 wxEvtHandler
* handler
= (wxEvtHandler
*) node
->GetData();
5623 if (handler
->ProcessEvent(event
))
5633 /// Set style sheet and notify of the change
5634 bool wxRichTextBuffer::SetStyleSheetAndNotify(wxRichTextStyleSheet
* sheet
)
5636 wxRichTextStyleSheet
* oldSheet
= GetStyleSheet();
5638 wxWindowID id
= wxID_ANY
;
5639 if (GetRichTextCtrl())
5640 id
= GetRichTextCtrl()->GetId();
5642 wxRichTextEvent
event(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING
, id
);
5643 event
.SetEventObject(GetRichTextCtrl());
5644 event
.SetOldStyleSheet(oldSheet
);
5645 event
.SetNewStyleSheet(sheet
);
5648 if (SendEvent(event
) && !event
.IsAllowed())
5650 if (sheet
!= oldSheet
)
5656 if (oldSheet
&& oldSheet
!= sheet
)
5659 SetStyleSheet(sheet
);
5661 event
.SetEventType(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED
);
5662 event
.SetOldStyleSheet(NULL
);
5665 return SendEvent(event
);
5668 /// Set renderer, deleting old one
5669 void wxRichTextBuffer::SetRenderer(wxRichTextRenderer
* renderer
)
5673 sm_renderer
= renderer
;
5676 bool wxRichTextStdRenderer::DrawStandardBullet(wxRichTextParagraph
* paragraph
, wxDC
& dc
, const wxTextAttr
& bulletAttr
, const wxRect
& rect
)
5678 if (bulletAttr
.GetTextColour().Ok())
5680 dc
.SetPen(wxPen(bulletAttr
.GetTextColour()));
5681 dc
.SetBrush(wxBrush(bulletAttr
.GetTextColour()));
5685 dc
.SetPen(*wxBLACK_PEN
);
5686 dc
.SetBrush(*wxBLACK_BRUSH
);
5690 if (bulletAttr
.HasFont())
5692 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(bulletAttr
);
5695 font
= (*wxNORMAL_FONT
);
5699 int charHeight
= dc
.GetCharHeight();
5701 int bulletWidth
= (int) (((float) charHeight
) * wxRichTextBuffer::GetBulletProportion());
5702 int bulletHeight
= bulletWidth
;
5706 // Calculate the top position of the character (as opposed to the whole line height)
5707 int y
= rect
.y
+ (rect
.height
- charHeight
);
5709 // Calculate where the bullet should be positioned
5710 y
= y
+ (charHeight
+1)/2 - (bulletHeight
+1)/2;
5712 // The margin between a bullet and text.
5713 int margin
= paragraph
->ConvertTenthsMMToPixels(dc
, wxRichTextBuffer::GetBulletRightMargin());
5715 if (bulletAttr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT
)
5716 x
= rect
.x
+ rect
.width
- bulletWidth
- margin
;
5717 else if (bulletAttr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE
)
5718 x
= x
+ (rect
.width
)/2 - bulletWidth
/2;
5720 if (bulletAttr
.GetBulletName() == wxT("standard/square"))
5722 dc
.DrawRectangle(x
, y
, bulletWidth
, bulletHeight
);
5724 else if (bulletAttr
.GetBulletName() == wxT("standard/diamond"))
5727 pts
[0].x
= x
; pts
[0].y
= y
+ bulletHeight
/2;
5728 pts
[1].x
= x
+ bulletWidth
/2; pts
[1].y
= y
;
5729 pts
[2].x
= x
+ bulletWidth
; pts
[2].y
= y
+ bulletHeight
/2;
5730 pts
[3].x
= x
+ bulletWidth
/2; pts
[3].y
= y
+ bulletHeight
;
5732 dc
.DrawPolygon(4, pts
);
5734 else if (bulletAttr
.GetBulletName() == wxT("standard/triangle"))
5737 pts
[0].x
= x
; pts
[0].y
= y
;
5738 pts
[1].x
= x
+ bulletWidth
; pts
[1].y
= y
+ bulletHeight
/2;
5739 pts
[2].x
= x
; pts
[2].y
= y
+ bulletHeight
;
5741 dc
.DrawPolygon(3, pts
);
5743 else // "standard/circle", and catch-all
5745 dc
.DrawEllipse(x
, y
, bulletWidth
, bulletHeight
);
5751 bool wxRichTextStdRenderer::DrawTextBullet(wxRichTextParagraph
* paragraph
, wxDC
& dc
, const wxTextAttr
& attr
, const wxRect
& rect
, const wxString
& text
)
5756 if ((attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL
) && !attr
.GetBulletFont().IsEmpty() && attr
.HasFont())
5758 wxTextAttr fontAttr
;
5759 fontAttr
.SetFontSize(attr
.GetFontSize());
5760 fontAttr
.SetFontStyle(attr
.GetFontStyle());
5761 fontAttr
.SetFontWeight(attr
.GetFontWeight());
5762 fontAttr
.SetFontUnderlined(attr
.GetFontUnderlined());
5763 fontAttr
.SetFontFaceName(attr
.GetBulletFont());
5764 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(fontAttr
);
5766 else if (attr
.HasFont())
5767 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(attr
);
5769 font
= (*wxNORMAL_FONT
);
5773 if (attr
.GetTextColour().Ok())
5774 dc
.SetTextForeground(attr
.GetTextColour());
5776 dc
.SetBackgroundMode(wxTRANSPARENT
);
5778 int charHeight
= dc
.GetCharHeight();
5780 dc
.GetTextExtent(text
, & tw
, & th
);
5784 // Calculate the top position of the character (as opposed to the whole line height)
5785 int y
= rect
.y
+ (rect
.height
- charHeight
);
5787 // The margin between a bullet and text.
5788 int margin
= paragraph
->ConvertTenthsMMToPixels(dc
, wxRichTextBuffer::GetBulletRightMargin());
5790 if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT
)
5791 x
= (rect
.x
+ rect
.width
) - tw
- margin
;
5792 else if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE
)
5793 x
= x
+ (rect
.width
)/2 - tw
/2;
5795 dc
.DrawText(text
, x
, y
);
5803 bool wxRichTextStdRenderer::DrawBitmapBullet(wxRichTextParagraph
* WXUNUSED(paragraph
), wxDC
& WXUNUSED(dc
), const wxTextAttr
& WXUNUSED(attr
), const wxRect
& WXUNUSED(rect
))
5805 // Currently unimplemented. The intention is to store bitmaps by name in a media store associated
5806 // with the buffer. The store will allow retrieval from memory, disk or other means.
5810 /// Enumerate the standard bullet names currently supported
5811 bool wxRichTextStdRenderer::EnumerateStandardBulletNames(wxArrayString
& bulletNames
)
5813 bulletNames
.Add(wxT("standard/circle"));
5814 bulletNames
.Add(wxT("standard/square"));
5815 bulletNames
.Add(wxT("standard/diamond"));
5816 bulletNames
.Add(wxT("standard/triangle"));
5822 * Module to initialise and clean up handlers
5825 class wxRichTextModule
: public wxModule
5827 DECLARE_DYNAMIC_CLASS(wxRichTextModule
)
5829 wxRichTextModule() {}
5832 wxRichTextBuffer::SetRenderer(new wxRichTextStdRenderer
);
5833 wxRichTextBuffer::InitStandardHandlers();
5834 wxRichTextParagraph::InitDefaultTabs();
5839 wxRichTextBuffer::CleanUpHandlers();
5840 wxRichTextDecimalToRoman(-1);
5841 wxRichTextParagraph::ClearDefaultTabs();
5842 wxRichTextCtrl::ClearAvailableFontNames();
5843 wxRichTextBuffer::SetRenderer(NULL
);
5847 IMPLEMENT_DYNAMIC_CLASS(wxRichTextModule
, wxModule
)
5850 // If the richtext lib is dynamically loaded after the app has already started
5851 // (such as from wxPython) then the built-in module system will not init this
5852 // module. Provide this function to do it manually.
5853 void wxRichTextModuleInit()
5855 wxModule
* module = new wxRichTextModule
;
5857 wxModule::RegisterModule(module);
5862 * Commands for undo/redo
5866 wxRichTextCommand::wxRichTextCommand(const wxString
& name
, wxRichTextCommandId id
, wxRichTextBuffer
* buffer
,
5867 wxRichTextCtrl
* ctrl
, bool ignoreFirstTime
): wxCommand(true, name
)
5869 /* wxRichTextAction* action = */ new wxRichTextAction(this, name
, id
, buffer
, ctrl
, ignoreFirstTime
);
5872 wxRichTextCommand::wxRichTextCommand(const wxString
& name
): wxCommand(true, name
)
5876 wxRichTextCommand::~wxRichTextCommand()
5881 void wxRichTextCommand::AddAction(wxRichTextAction
* action
)
5883 if (!m_actions
.Member(action
))
5884 m_actions
.Append(action
);
5887 bool wxRichTextCommand::Do()
5889 for (wxList::compatibility_iterator node
= m_actions
.GetFirst(); node
; node
= node
->GetNext())
5891 wxRichTextAction
* action
= (wxRichTextAction
*) node
->GetData();
5898 bool wxRichTextCommand::Undo()
5900 for (wxList::compatibility_iterator node
= m_actions
.GetLast(); node
; node
= node
->GetPrevious())
5902 wxRichTextAction
* action
= (wxRichTextAction
*) node
->GetData();
5909 void wxRichTextCommand::ClearActions()
5911 WX_CLEAR_LIST(wxList
, m_actions
);
5919 wxRichTextAction::wxRichTextAction(wxRichTextCommand
* cmd
, const wxString
& name
, wxRichTextCommandId id
, wxRichTextBuffer
* buffer
,
5920 wxRichTextCtrl
* ctrl
, bool ignoreFirstTime
)
5923 m_ignoreThis
= ignoreFirstTime
;
5928 m_newParagraphs
.SetDefaultStyle(buffer
->GetDefaultStyle());
5929 m_newParagraphs
.SetBasicStyle(buffer
->GetBasicStyle());
5931 cmd
->AddAction(this);
5934 wxRichTextAction::~wxRichTextAction()
5938 bool wxRichTextAction::Do()
5940 m_buffer
->Modify(true);
5944 case wxRICHTEXT_INSERT
:
5946 // Store a list of line start character and y positions so we can figure out which area
5947 // we need to refresh
5948 wxArrayInt optimizationLineCharPositions
;
5949 wxArrayInt optimizationLineYPositions
;
5951 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
5952 // NOTE: we're assuming that the buffer is laid out correctly at this point.
5953 // If we had several actions, which only invalidate and leave layout until the
5954 // paint handler is called, then this might not be true. So we may need to switch
5955 // optimisation on only when we're simply adding text and not simultaneously
5956 // deleting a selection, for example. Or, we make sure the buffer is laid out correctly
5957 // first, but of course this means we'll be doing it twice.
5958 if (!m_buffer
->GetDirty() && m_ctrl
) // can only do optimisation if the buffer is already laid out correctly
5960 wxSize clientSize
= m_ctrl
->GetClientSize();
5961 wxPoint firstVisiblePt
= m_ctrl
->GetFirstVisiblePoint();
5962 int lastY
= firstVisiblePt
.y
+ clientSize
.y
;
5964 wxRichTextParagraph
* para
= m_buffer
->GetParagraphAtPosition(GetPosition());
5965 wxRichTextObjectList::compatibility_iterator node
= m_buffer
->GetChildren().Find(para
);
5968 wxRichTextParagraph
* child
= (wxRichTextParagraph
*) node
->GetData();
5969 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
5972 wxRichTextLine
* line
= node2
->GetData();
5973 wxPoint pt
= line
->GetAbsolutePosition();
5974 wxRichTextRange range
= line
->GetAbsoluteRange();
5978 node2
= wxRichTextLineList::compatibility_iterator();
5979 node
= wxRichTextObjectList::compatibility_iterator();
5981 else if (range
.GetStart() > GetPosition() && pt
.y
>= firstVisiblePt
.y
)
5983 optimizationLineCharPositions
.Add(range
.GetStart());
5984 optimizationLineYPositions
.Add(pt
.y
);
5988 node2
= node2
->GetNext();
5992 node
= node
->GetNext();
5997 m_buffer
->InsertFragment(GetPosition(), m_newParagraphs
);
5998 m_buffer
->UpdateRanges();
5999 m_buffer
->Invalidate(GetRange());
6001 long newCaretPosition
= GetPosition() + m_newParagraphs
.GetRange().GetLength();
6003 // Character position to caret position
6004 newCaretPosition
--;
6006 // Don't take into account the last newline
6007 if (m_newParagraphs
.GetPartialParagraph())
6008 newCaretPosition
--;
6010 if (m_newParagraphs
.GetChildren().GetCount() > 1)
6012 wxRichTextObject
* p
= (wxRichTextObject
*) m_newParagraphs
.GetChildren().GetLast()->GetData();
6013 if (p
->GetRange().GetLength() == 1)
6014 newCaretPosition
--;
6017 newCaretPosition
= wxMin(newCaretPosition
, (m_buffer
->GetRange().GetEnd()-1));
6019 if (optimizationLineCharPositions
.GetCount() > 0)
6020 UpdateAppearance(newCaretPosition
, true /* send update event */, & optimizationLineCharPositions
, & optimizationLineYPositions
);
6022 UpdateAppearance(newCaretPosition
, true /* send update event */);
6024 wxRichTextEvent
cmdEvent(
6025 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED
,
6026 m_ctrl
? m_ctrl
->GetId() : -1);
6027 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6028 cmdEvent
.SetRange(GetRange());
6029 cmdEvent
.SetPosition(GetRange().GetStart());
6031 m_buffer
->SendEvent(cmdEvent
);
6035 case wxRICHTEXT_DELETE
:
6037 m_buffer
->DeleteRange(GetRange());
6038 m_buffer
->UpdateRanges();
6039 m_buffer
->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6041 UpdateAppearance(GetRange().GetStart()-1, true /* send update event */);
6043 wxRichTextEvent
cmdEvent(
6044 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED
,
6045 m_ctrl
? m_ctrl
->GetId() : -1);
6046 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6047 cmdEvent
.SetRange(GetRange());
6048 cmdEvent
.SetPosition(GetRange().GetStart());
6050 m_buffer
->SendEvent(cmdEvent
);
6054 case wxRICHTEXT_CHANGE_STYLE
:
6056 ApplyParagraphs(GetNewParagraphs());
6057 m_buffer
->Invalidate(GetRange());
6059 UpdateAppearance(GetPosition());
6061 wxRichTextEvent
cmdEvent(
6062 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED
,
6063 m_ctrl
? m_ctrl
->GetId() : -1);
6064 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6065 cmdEvent
.SetRange(GetRange());
6066 cmdEvent
.SetPosition(GetRange().GetStart());
6068 m_buffer
->SendEvent(cmdEvent
);
6079 bool wxRichTextAction::Undo()
6081 m_buffer
->Modify(true);
6085 case wxRICHTEXT_INSERT
:
6087 m_buffer
->DeleteRange(GetRange());
6088 m_buffer
->UpdateRanges();
6089 m_buffer
->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6091 long newCaretPosition
= GetPosition() - 1;
6093 UpdateAppearance(newCaretPosition
, true /* send update event */);
6095 wxRichTextEvent
cmdEvent(
6096 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED
,
6097 m_ctrl
? m_ctrl
->GetId() : -1);
6098 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6099 cmdEvent
.SetRange(GetRange());
6100 cmdEvent
.SetPosition(GetRange().GetStart());
6102 m_buffer
->SendEvent(cmdEvent
);
6106 case wxRICHTEXT_DELETE
:
6108 m_buffer
->InsertFragment(GetRange().GetStart(), m_oldParagraphs
);
6109 m_buffer
->UpdateRanges();
6110 m_buffer
->Invalidate(GetRange());
6112 UpdateAppearance(GetPosition(), true /* send update event */);
6114 wxRichTextEvent
cmdEvent(
6115 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED
,
6116 m_ctrl
? m_ctrl
->GetId() : -1);
6117 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6118 cmdEvent
.SetRange(GetRange());
6119 cmdEvent
.SetPosition(GetRange().GetStart());
6121 m_buffer
->SendEvent(cmdEvent
);
6125 case wxRICHTEXT_CHANGE_STYLE
:
6127 ApplyParagraphs(GetOldParagraphs());
6128 m_buffer
->Invalidate(GetRange());
6130 UpdateAppearance(GetPosition());
6132 wxRichTextEvent
cmdEvent(
6133 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED
,
6134 m_ctrl
? m_ctrl
->GetId() : -1);
6135 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6136 cmdEvent
.SetRange(GetRange());
6137 cmdEvent
.SetPosition(GetRange().GetStart());
6139 m_buffer
->SendEvent(cmdEvent
);
6150 /// Update the control appearance
6151 void wxRichTextAction::UpdateAppearance(long caretPosition
, bool sendUpdateEvent
, wxArrayInt
* optimizationLineCharPositions
, wxArrayInt
* optimizationLineYPositions
)
6155 m_ctrl
->SetCaretPosition(caretPosition
);
6156 if (!m_ctrl
->IsFrozen())
6158 m_ctrl
->LayoutContent();
6159 m_ctrl
->PositionCaret();
6161 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6162 // Find refresh rectangle if we are in a position to optimise refresh
6163 if (m_cmdId
== wxRICHTEXT_INSERT
&& optimizationLineCharPositions
&& optimizationLineCharPositions
->GetCount() > 0)
6167 wxSize clientSize
= m_ctrl
->GetClientSize();
6168 wxPoint firstVisiblePt
= m_ctrl
->GetFirstVisiblePoint();
6170 // Start/end positions
6172 int lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6174 bool foundStart
= false;
6175 bool foundEnd
= false;
6177 // position offset - how many characters were inserted
6178 int positionOffset
= GetRange().GetLength();
6180 // find the first line which is being drawn at the same position as it was
6181 // before. Since we're talking about a simple insertion, we can assume
6182 // that the rest of the window does not need to be redrawn.
6184 wxRichTextParagraph
* para
= m_buffer
->GetParagraphAtPosition(GetPosition());
6185 wxRichTextObjectList::compatibility_iterator node
= m_buffer
->GetChildren().Find(para
);
6188 wxRichTextParagraph
* child
= (wxRichTextParagraph
*) node
->GetData();
6189 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
6192 wxRichTextLine
* line
= node2
->GetData();
6193 wxPoint pt
= line
->GetAbsolutePosition();
6194 wxRichTextRange range
= line
->GetAbsoluteRange();
6196 // we want to find the first line that is in the same position
6197 // as before. This will mean we're at the end of the changed text.
6199 if (pt
.y
> lastY
) // going past the end of the window, no more info
6201 node2
= wxRichTextLineList::compatibility_iterator();
6202 node
= wxRichTextObjectList::compatibility_iterator();
6208 firstY
= pt
.y
- firstVisiblePt
.y
;
6212 // search for this line being at the same position as before
6213 for (i
= 0; i
< optimizationLineCharPositions
->GetCount(); i
++)
6215 if (((*optimizationLineCharPositions
)[i
] + positionOffset
== range
.GetStart()) &&
6216 ((*optimizationLineYPositions
)[i
] == pt
.y
))
6218 // Stop, we're now the same as we were
6220 lastY
= pt
.y
- firstVisiblePt
.y
;
6222 node2
= wxRichTextLineList::compatibility_iterator();
6223 node
= wxRichTextObjectList::compatibility_iterator();
6231 node2
= node2
->GetNext();
6235 node
= node
->GetNext();
6239 firstY
= firstVisiblePt
.y
;
6241 lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6243 wxRect
rect(firstVisiblePt
.x
, firstY
, firstVisiblePt
.x
+ clientSize
.x
, lastY
- firstY
);
6244 m_ctrl
->RefreshRect(rect
);
6246 // TODO: we need to make sure that lines are only drawn if in the update region. The rect
6247 // passed to Draw is currently used in different ways (to pass the position the content should
6248 // be drawn at as well as the relevant region).
6252 m_ctrl
->Refresh(false);
6254 if (sendUpdateEvent
)
6255 wxTextCtrl::SendTextUpdatedEvent(m_ctrl
);
6260 /// Replace the buffer paragraphs with the new ones.
6261 void wxRichTextAction::ApplyParagraphs(const wxRichTextParagraphLayoutBox
& fragment
)
6263 wxRichTextObjectList::compatibility_iterator node
= fragment
.GetChildren().GetFirst();
6266 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
6267 wxASSERT (para
!= NULL
);
6269 // We'll replace the existing paragraph by finding the paragraph at this position,
6270 // delete its node data, and setting a copy as the new node data.
6271 // TODO: make more efficient by simply swapping old and new paragraph objects.
6273 wxRichTextParagraph
* existingPara
= m_buffer
->GetParagraphAtPosition(para
->GetRange().GetStart());
6276 wxRichTextObjectList::compatibility_iterator bufferParaNode
= m_buffer
->GetChildren().Find(existingPara
);
6279 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(*para
);
6280 newPara
->SetParent(m_buffer
);
6282 bufferParaNode
->SetData(newPara
);
6284 delete existingPara
;
6288 node
= node
->GetNext();
6295 * This stores beginning and end positions for a range of data.
6298 /// Limit this range to be within 'range'
6299 bool wxRichTextRange::LimitTo(const wxRichTextRange
& range
)
6301 if (m_start
< range
.m_start
)
6302 m_start
= range
.m_start
;
6304 if (m_end
> range
.m_end
)
6305 m_end
= range
.m_end
;
6311 * wxRichTextImage implementation
6312 * This object represents an image.
6315 IMPLEMENT_DYNAMIC_CLASS(wxRichTextImage
, wxRichTextObject
)
6317 wxRichTextImage::wxRichTextImage(const wxImage
& image
, wxRichTextObject
* parent
, wxTextAttr
* charStyle
):
6318 wxRichTextObject(parent
)
6322 SetAttributes(*charStyle
);
6325 wxRichTextImage::wxRichTextImage(const wxRichTextImageBlock
& imageBlock
, wxRichTextObject
* parent
, wxTextAttr
* charStyle
):
6326 wxRichTextObject(parent
)
6328 m_imageBlock
= imageBlock
;
6329 m_imageBlock
.Load(m_image
);
6331 SetAttributes(*charStyle
);
6334 /// Load wxImage from the block
6335 bool wxRichTextImage::LoadFromBlock()
6337 m_imageBlock
.Load(m_image
);
6338 return m_imageBlock
.Ok();
6341 /// Make block from the wxImage
6342 bool wxRichTextImage::MakeBlock()
6344 if (m_imageBlock
.GetImageType() == wxBITMAP_TYPE_ANY
|| m_imageBlock
.GetImageType() == -1)
6345 m_imageBlock
.SetImageType(wxBITMAP_TYPE_PNG
);
6347 m_imageBlock
.MakeImageBlock(m_image
, m_imageBlock
.GetImageType());
6348 return m_imageBlock
.Ok();
6353 bool wxRichTextImage::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int WXUNUSED(descent
), int WXUNUSED(style
))
6355 if (!m_image
.Ok() && m_imageBlock
.Ok())
6361 if (m_image
.Ok() && !m_bitmap
.Ok())
6362 m_bitmap
= wxBitmap(m_image
);
6364 int y
= rect
.y
+ (rect
.height
- m_image
.GetHeight());
6367 dc
.DrawBitmap(m_bitmap
, rect
.x
, y
, true);
6369 if (selectionRange
.Contains(range
.GetStart()))
6371 dc
.SetBrush(*wxBLACK_BRUSH
);
6372 dc
.SetPen(*wxBLACK_PEN
);
6373 dc
.SetLogicalFunction(wxINVERT
);
6374 dc
.DrawRectangle(rect
);
6375 dc
.SetLogicalFunction(wxCOPY
);
6381 /// Lay the item out
6382 bool wxRichTextImage::Layout(wxDC
& WXUNUSED(dc
), const wxRect
& rect
, int WXUNUSED(style
))
6389 SetCachedSize(wxSize(m_image
.GetWidth(), m_image
.GetHeight()));
6390 SetPosition(rect
.GetPosition());
6396 /// Get/set the object size for the given range. Returns false if the range
6397 /// is invalid for this object.
6398 bool wxRichTextImage::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& WXUNUSED(descent
), wxDC
& WXUNUSED(dc
), int WXUNUSED(flags
), wxPoint
WXUNUSED(position
)) const
6400 if (!range
.IsWithin(GetRange()))
6406 size
.x
= m_image
.GetWidth();
6407 size
.y
= m_image
.GetHeight();
6413 void wxRichTextImage::Copy(const wxRichTextImage
& obj
)
6415 wxRichTextObject::Copy(obj
);
6417 m_image
= obj
.m_image
;
6418 m_imageBlock
= obj
.m_imageBlock
;
6426 /// Compare two attribute objects
6427 bool wxTextAttrEq(const wxTextAttr
& attr1
, const wxTextAttr
& attr2
)
6429 return (attr1
== attr2
);
6432 // Partial equality test taking flags into account
6433 bool wxTextAttrEqPartial(const wxTextAttr
& attr1
, const wxTextAttr
& attr2
, int flags
)
6435 return attr1
.EqPartial(attr2
, flags
);
6439 bool wxRichTextTabsEq(const wxArrayInt
& tabs1
, const wxArrayInt
& tabs2
)
6441 if (tabs1
.GetCount() != tabs2
.GetCount())
6445 for (i
= 0; i
< tabs1
.GetCount(); i
++)
6447 if (tabs1
[i
] != tabs2
[i
])
6453 bool wxRichTextApplyStyle(wxTextAttr
& destStyle
, const wxTextAttr
& style
, wxTextAttr
* compareWith
)
6455 return destStyle
.Apply(style
, compareWith
);
6458 // Remove attributes
6459 bool wxRichTextRemoveStyle(wxTextAttr
& destStyle
, const wxTextAttr
& style
)
6461 return wxTextAttr::RemoveStyle(destStyle
, style
);
6464 /// Combine two bitlists, specifying the bits of interest with separate flags.
6465 bool wxRichTextCombineBitlists(int& valueA
, int valueB
, int& flagsA
, int flagsB
)
6467 return wxTextAttr::CombineBitlists(valueA
, valueB
, flagsA
, flagsB
);
6470 /// Compare two bitlists
6471 bool wxRichTextBitlistsEqPartial(int valueA
, int valueB
, int flags
)
6473 return wxTextAttr::BitlistsEqPartial(valueA
, valueB
, flags
);
6476 /// Split into paragraph and character styles
6477 bool wxRichTextSplitParaCharStyles(const wxTextAttr
& style
, wxTextAttr
& parStyle
, wxTextAttr
& charStyle
)
6479 return wxTextAttr::SplitParaCharStyles(style
, parStyle
, charStyle
);
6482 /// Convert a decimal to Roman numerals
6483 wxString
wxRichTextDecimalToRoman(long n
)
6485 static wxArrayInt decimalNumbers
;
6486 static wxArrayString romanNumbers
;
6491 decimalNumbers
.Clear();
6492 romanNumbers
.Clear();
6493 return wxEmptyString
;
6496 if (decimalNumbers
.GetCount() == 0)
6498 #define wxRichTextAddDecRom(n, r) decimalNumbers.Add(n); romanNumbers.Add(r);
6500 wxRichTextAddDecRom(1000, wxT("M"));
6501 wxRichTextAddDecRom(900, wxT("CM"));
6502 wxRichTextAddDecRom(500, wxT("D"));
6503 wxRichTextAddDecRom(400, wxT("CD"));
6504 wxRichTextAddDecRom(100, wxT("C"));
6505 wxRichTextAddDecRom(90, wxT("XC"));
6506 wxRichTextAddDecRom(50, wxT("L"));
6507 wxRichTextAddDecRom(40, wxT("XL"));
6508 wxRichTextAddDecRom(10, wxT("X"));
6509 wxRichTextAddDecRom(9, wxT("IX"));
6510 wxRichTextAddDecRom(5, wxT("V"));
6511 wxRichTextAddDecRom(4, wxT("IV"));
6512 wxRichTextAddDecRom(1, wxT("I"));
6518 while (n
> 0 && i
< 13)
6520 if (n
>= decimalNumbers
[i
])
6522 n
-= decimalNumbers
[i
];
6523 roman
+= romanNumbers
[i
];
6530 if (roman
.IsEmpty())
6536 * wxRichTextFileHandler
6537 * Base class for file handlers
6540 IMPLEMENT_CLASS(wxRichTextFileHandler
, wxObject
)
6542 #if wxUSE_FFILE && wxUSE_STREAMS
6543 bool wxRichTextFileHandler::LoadFile(wxRichTextBuffer
*buffer
, const wxString
& filename
)
6545 wxFFileInputStream
stream(filename
);
6547 return LoadFile(buffer
, stream
);
6552 bool wxRichTextFileHandler::SaveFile(wxRichTextBuffer
*buffer
, const wxString
& filename
)
6554 wxFFileOutputStream
stream(filename
);
6556 return SaveFile(buffer
, stream
);
6560 #endif // wxUSE_FFILE && wxUSE_STREAMS
6562 /// Can we handle this filename (if using files)? By default, checks the extension.
6563 bool wxRichTextFileHandler::CanHandle(const wxString
& filename
) const
6565 wxString path
, file
, ext
;
6566 wxSplitPath(filename
, & path
, & file
, & ext
);
6568 return (ext
.Lower() == GetExtension());
6572 * wxRichTextTextHandler
6573 * Plain text handler
6576 IMPLEMENT_CLASS(wxRichTextPlainTextHandler
, wxRichTextFileHandler
)
6579 bool wxRichTextPlainTextHandler::DoLoadFile(wxRichTextBuffer
*buffer
, wxInputStream
& stream
)
6587 while (!stream
.Eof())
6589 int ch
= stream
.GetC();
6593 if (ch
== 10 && lastCh
!= 13)
6596 if (ch
> 0 && ch
!= 10)
6603 buffer
->ResetAndClearCommands();
6605 buffer
->AddParagraphs(str
);
6606 buffer
->UpdateRanges();
6611 bool wxRichTextPlainTextHandler::DoSaveFile(wxRichTextBuffer
*buffer
, wxOutputStream
& stream
)
6616 wxString text
= buffer
->GetText();
6618 wxString newLine
= wxRichTextLineBreakChar
;
6619 text
.Replace(newLine
, wxT("\n"));
6621 wxCharBuffer buf
= text
.ToAscii();
6623 stream
.Write((const char*) buf
, text
.length());
6626 #endif // wxUSE_STREAMS
6629 * Stores information about an image, in binary in-memory form
6632 wxRichTextImageBlock::wxRichTextImageBlock()
6637 wxRichTextImageBlock::wxRichTextImageBlock(const wxRichTextImageBlock
& block
):wxObject()
6643 wxRichTextImageBlock::~wxRichTextImageBlock()
6652 void wxRichTextImageBlock::Init()
6659 void wxRichTextImageBlock::Clear()
6668 // Load the original image into a memory block.
6669 // If the image is not a JPEG, we must convert it into a JPEG
6670 // to conserve space.
6671 // If it's not a JPEG we can make use of 'image', already scaled, so we don't have to
6672 // load the image a 2nd time.
6674 bool wxRichTextImageBlock::MakeImageBlock(const wxString
& filename
, int imageType
, wxImage
& image
, bool convertToJPEG
)
6676 m_imageType
= imageType
;
6678 wxString
filenameToRead(filename
);
6679 bool removeFile
= false;
6681 if (imageType
== -1)
6682 return false; // Could not determine image type
6684 if ((imageType
!= wxBITMAP_TYPE_JPEG
) && convertToJPEG
)
6687 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
6691 wxUnusedVar(success
);
6693 image
.SaveFile(tempFile
, wxBITMAP_TYPE_JPEG
);
6694 filenameToRead
= tempFile
;
6697 m_imageType
= wxBITMAP_TYPE_JPEG
;
6700 if (!file
.Open(filenameToRead
))
6703 m_dataSize
= (size_t) file
.Length();
6708 m_data
= ReadBlock(filenameToRead
, m_dataSize
);
6711 wxRemoveFile(filenameToRead
);
6713 return (m_data
!= NULL
);
6716 // Make an image block from the wxImage in the given
6718 bool wxRichTextImageBlock::MakeImageBlock(wxImage
& image
, int imageType
, int quality
)
6720 m_imageType
= imageType
;
6721 image
.SetOption(wxT("quality"), quality
);
6723 if (imageType
== -1)
6724 return false; // Could not determine image type
6727 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
6730 wxUnusedVar(success
);
6732 if (!image
.SaveFile(tempFile
, m_imageType
))
6734 if (wxFileExists(tempFile
))
6735 wxRemoveFile(tempFile
);
6740 if (!file
.Open(tempFile
))
6743 m_dataSize
= (size_t) file
.Length();
6748 m_data
= ReadBlock(tempFile
, m_dataSize
);
6750 wxRemoveFile(tempFile
);
6752 return (m_data
!= NULL
);
6757 bool wxRichTextImageBlock::Write(const wxString
& filename
)
6759 return WriteBlock(filename
, m_data
, m_dataSize
);
6762 void wxRichTextImageBlock::Copy(const wxRichTextImageBlock
& block
)
6764 m_imageType
= block
.m_imageType
;
6770 m_dataSize
= block
.m_dataSize
;
6771 if (m_dataSize
== 0)
6774 m_data
= new unsigned char[m_dataSize
];
6776 for (i
= 0; i
< m_dataSize
; i
++)
6777 m_data
[i
] = block
.m_data
[i
];
6781 void wxRichTextImageBlock::operator=(const wxRichTextImageBlock
& block
)
6786 // Load a wxImage from the block
6787 bool wxRichTextImageBlock::Load(wxImage
& image
)
6792 // Read in the image.
6794 wxMemoryInputStream
mstream(m_data
, m_dataSize
);
6795 bool success
= image
.LoadFile(mstream
, GetImageType());
6798 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
6801 if (!WriteBlock(tempFile
, m_data
, m_dataSize
))
6805 success
= image
.LoadFile(tempFile
, GetImageType());
6806 wxRemoveFile(tempFile
);
6812 // Write data in hex to a stream
6813 bool wxRichTextImageBlock::WriteHex(wxOutputStream
& stream
)
6815 const int bufSize
= 512;
6816 char buf
[bufSize
+1];
6818 int left
= m_dataSize
;
6823 if (left
*2 > bufSize
)
6825 n
= bufSize
; left
-= (bufSize
/2);
6829 n
= left
*2; left
= 0;
6833 for (i
= 0; i
< (n
/2); i
++)
6835 wxDecToHex(m_data
[j
], b
, b
+1);
6840 stream
.Write((const char*) buf
, n
);
6845 // Read data in hex from a stream
6846 bool wxRichTextImageBlock::ReadHex(wxInputStream
& stream
, int length
, int imageType
)
6848 int dataSize
= length
/2;
6854 m_data
= new unsigned char[dataSize
];
6856 for (i
= 0; i
< dataSize
; i
++)
6858 str
[0] = (char)stream
.GetC();
6859 str
[1] = (char)stream
.GetC();
6861 m_data
[i
] = (unsigned char)wxHexToDec(str
);
6864 m_dataSize
= dataSize
;
6865 m_imageType
= imageType
;
6870 // Allocate and read from stream as a block of memory
6871 unsigned char* wxRichTextImageBlock::ReadBlock(wxInputStream
& stream
, size_t size
)
6873 unsigned char* block
= new unsigned char[size
];
6877 stream
.Read(block
, size
);
6882 unsigned char* wxRichTextImageBlock::ReadBlock(const wxString
& filename
, size_t size
)
6884 wxFileInputStream
stream(filename
);
6888 return ReadBlock(stream
, size
);
6891 // Write memory block to stream
6892 bool wxRichTextImageBlock::WriteBlock(wxOutputStream
& stream
, unsigned char* block
, size_t size
)
6894 stream
.Write((void*) block
, size
);
6895 return stream
.IsOk();
6899 // Write memory block to file
6900 bool wxRichTextImageBlock::WriteBlock(const wxString
& filename
, unsigned char* block
, size_t size
)
6902 wxFileOutputStream
outStream(filename
);
6903 if (!outStream
.Ok())
6906 return WriteBlock(outStream
, block
, size
);
6909 // Gets the extension for the block's type
6910 wxString
wxRichTextImageBlock::GetExtension() const
6912 wxImageHandler
* handler
= wxImage::FindHandler(GetImageType());
6914 return handler
->GetExtension();
6916 return wxEmptyString
;
6922 * The data object for a wxRichTextBuffer
6925 const wxChar
*wxRichTextBufferDataObject::ms_richTextBufferFormatId
= wxT("wxShape");
6927 wxRichTextBufferDataObject::wxRichTextBufferDataObject(wxRichTextBuffer
* richTextBuffer
)
6929 m_richTextBuffer
= richTextBuffer
;
6931 // this string should uniquely identify our format, but is otherwise
6933 m_formatRichTextBuffer
.SetId(GetRichTextBufferFormatId());
6935 SetFormat(m_formatRichTextBuffer
);
6938 wxRichTextBufferDataObject::~wxRichTextBufferDataObject()
6940 delete m_richTextBuffer
;
6943 // after a call to this function, the richTextBuffer is owned by the caller and it
6944 // is responsible for deleting it!
6945 wxRichTextBuffer
* wxRichTextBufferDataObject::GetRichTextBuffer()
6947 wxRichTextBuffer
* richTextBuffer
= m_richTextBuffer
;
6948 m_richTextBuffer
= NULL
;
6950 return richTextBuffer
;
6953 wxDataFormat
wxRichTextBufferDataObject::GetPreferredFormat(Direction
WXUNUSED(dir
)) const
6955 return m_formatRichTextBuffer
;
6958 size_t wxRichTextBufferDataObject::GetDataSize() const
6960 if (!m_richTextBuffer
)
6966 wxStringOutputStream
stream(& bufXML
);
6967 if (!m_richTextBuffer
->SaveFile(stream
, wxRICHTEXT_TYPE_XML
))
6969 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
6975 wxCharBuffer buffer
= bufXML
.mb_str(wxConvUTF8
);
6976 return strlen(buffer
) + 1;
6978 return bufXML
.Length()+1;
6982 bool wxRichTextBufferDataObject::GetDataHere(void *pBuf
) const
6984 if (!pBuf
|| !m_richTextBuffer
)
6990 wxStringOutputStream
stream(& bufXML
);
6991 if (!m_richTextBuffer
->SaveFile(stream
, wxRICHTEXT_TYPE_XML
))
6993 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
6999 wxCharBuffer buffer
= bufXML
.mb_str(wxConvUTF8
);
7000 size_t len
= strlen(buffer
);
7001 memcpy((char*) pBuf
, (const char*) buffer
, len
);
7002 ((char*) pBuf
)[len
] = 0;
7004 size_t len
= bufXML
.Length();
7005 memcpy((char*) pBuf
, (const char*) bufXML
.c_str(), len
);
7006 ((char*) pBuf
)[len
] = 0;
7012 bool wxRichTextBufferDataObject::SetData(size_t WXUNUSED(len
), const void *buf
)
7014 delete m_richTextBuffer
;
7015 m_richTextBuffer
= NULL
;
7017 wxString
bufXML((const char*) buf
, wxConvUTF8
);
7019 m_richTextBuffer
= new wxRichTextBuffer
;
7021 wxStringInputStream
stream(bufXML
);
7022 if (!m_richTextBuffer
->LoadFile(stream
, wxRICHTEXT_TYPE_XML
))
7024 wxLogError(wxT("Could not read the buffer from an XML stream.\nYou may have forgotten to add the XML file handler."));
7026 delete m_richTextBuffer
;
7027 m_richTextBuffer
= NULL
;
7039 * wxRichTextFontTable
7040 * Manages quick access to a pool of fonts for rendering rich text
7043 WX_DECLARE_EXPORTED_STRING_HASH_MAP(wxFont
, wxRichTextFontTableHashMap
);
7045 class wxRichTextFontTableData
: public wxObjectRefData
7048 wxRichTextFontTableData() {}
7050 wxFont
FindFont(const wxTextAttr
& fontSpec
);
7052 wxRichTextFontTableHashMap m_hashMap
;
7055 wxFont
wxRichTextFontTableData::FindFont(const wxTextAttr
& fontSpec
)
7057 wxString
facename(fontSpec
.GetFontFaceName());
7058 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()));
7059 wxRichTextFontTableHashMap::iterator entry
= m_hashMap
.find(spec
);
7061 if ( entry
== m_hashMap
.end() )
7063 wxFont
font(fontSpec
.GetFontSize(), wxDEFAULT
, fontSpec
.GetFontStyle(), fontSpec
.GetFontWeight(), fontSpec
.GetFontUnderlined(), facename
.c_str());
7064 m_hashMap
[spec
] = font
;
7069 return entry
->second
;
7073 IMPLEMENT_DYNAMIC_CLASS(wxRichTextFontTable
, wxObject
)
7075 wxRichTextFontTable::wxRichTextFontTable()
7077 m_refData
= new wxRichTextFontTableData
;
7078 m_refData
->IncRef();
7081 wxRichTextFontTable::wxRichTextFontTable(const wxRichTextFontTable
& table
)
7086 wxRichTextFontTable::~wxRichTextFontTable()
7091 bool wxRichTextFontTable::operator == (const wxRichTextFontTable
& table
) const
7093 return (m_refData
== table
.m_refData
);
7096 void wxRichTextFontTable::operator= (const wxRichTextFontTable
& table
)
7101 wxFont
wxRichTextFontTable::FindFont(const wxTextAttr
& fontSpec
)
7103 wxRichTextFontTableData
* data
= (wxRichTextFontTableData
*) m_refData
;
7105 return data
->FindFont(fontSpec
);
7110 void wxRichTextFontTable::Clear()
7112 wxRichTextFontTableData
* data
= (wxRichTextFontTableData
*) m_refData
;
7114 data
->m_hashMap
.clear();