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/filename.h"
32 #include "wx/clipbrd.h"
33 #include "wx/wfstream.h"
34 #include "wx/mstream.h"
35 #include "wx/sstream.h"
36 #include "wx/textfile.h"
37 #include "wx/hashmap.h"
39 #include "wx/richtext/richtextctrl.h"
40 #include "wx/richtext/richtextstyles.h"
42 #include "wx/listimpl.cpp"
44 WX_DEFINE_LIST(wxRichTextObjectList
)
45 WX_DEFINE_LIST(wxRichTextLineList
)
47 // Switch off if the platform doesn't like it for some reason
48 #define wxRICHTEXT_USE_OPTIMIZED_DRAWING 1
50 const wxChar wxRichTextLineBreakChar
= (wxChar
) 29;
54 * This is the base for drawable objects.
57 IMPLEMENT_CLASS(wxRichTextObject
, wxObject
)
59 wxRichTextObject::wxRichTextObject(wxRichTextObject
* parent
)
71 wxRichTextObject::~wxRichTextObject()
75 void wxRichTextObject::Dereference()
83 void wxRichTextObject::Copy(const wxRichTextObject
& obj
)
87 m_dirty
= obj
.m_dirty
;
88 m_range
= obj
.m_range
;
89 m_attributes
= obj
.m_attributes
;
90 m_descent
= obj
.m_descent
;
93 void wxRichTextObject::SetMargins(int margin
)
95 m_leftMargin
= m_rightMargin
= m_topMargin
= m_bottomMargin
= margin
;
98 void wxRichTextObject::SetMargins(int leftMargin
, int rightMargin
, int topMargin
, int bottomMargin
)
100 m_leftMargin
= leftMargin
;
101 m_rightMargin
= rightMargin
;
102 m_topMargin
= topMargin
;
103 m_bottomMargin
= bottomMargin
;
106 // Convert units in tenths of a millimetre to device units
107 int wxRichTextObject::ConvertTenthsMMToPixels(wxDC
& dc
, int units
)
109 int p
= ConvertTenthsMMToPixels(dc
.GetPPI().x
, units
);
112 wxRichTextBuffer
* buffer
= GetBuffer();
114 p
= (int) ((double)p
/ buffer
->GetScale());
118 // Convert units in tenths of a millimetre to device units
119 int wxRichTextObject::ConvertTenthsMMToPixels(int ppi
, int units
)
121 // There are ppi pixels in 254.1 "1/10 mm"
123 double pixels
= ((double) units
* (double)ppi
) / 254.1;
128 /// Dump to output stream for debugging
129 void wxRichTextObject::Dump(wxTextOutputStream
& stream
)
131 stream
<< GetClassInfo()->GetClassName() << wxT("\n");
132 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");
133 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");
136 /// Gets the containing buffer
137 wxRichTextBuffer
* wxRichTextObject::GetBuffer() const
139 const wxRichTextObject
* obj
= this;
140 while (obj
&& !obj
->IsKindOf(CLASSINFO(wxRichTextBuffer
)))
141 obj
= obj
->GetParent();
142 return wxDynamicCast(obj
, wxRichTextBuffer
);
146 * wxRichTextCompositeObject
147 * This is the base for drawable objects.
150 IMPLEMENT_CLASS(wxRichTextCompositeObject
, wxRichTextObject
)
152 wxRichTextCompositeObject::wxRichTextCompositeObject(wxRichTextObject
* parent
):
153 wxRichTextObject(parent
)
157 wxRichTextCompositeObject::~wxRichTextCompositeObject()
162 /// Get the nth child
163 wxRichTextObject
* wxRichTextCompositeObject::GetChild(size_t n
) const
165 wxASSERT ( n
< m_children
.GetCount() );
167 return m_children
.Item(n
)->GetData();
170 /// Append a child, returning the position
171 size_t wxRichTextCompositeObject::AppendChild(wxRichTextObject
* child
)
173 m_children
.Append(child
);
174 child
->SetParent(this);
175 return m_children
.GetCount() - 1;
178 /// Insert the child in front of the given object, or at the beginning
179 bool wxRichTextCompositeObject::InsertChild(wxRichTextObject
* child
, wxRichTextObject
* inFrontOf
)
183 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(inFrontOf
);
184 m_children
.Insert(node
, child
);
187 m_children
.Insert(child
);
188 child
->SetParent(this);
194 bool wxRichTextCompositeObject::RemoveChild(wxRichTextObject
* child
, bool deleteChild
)
196 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(child
);
199 wxRichTextObject
* obj
= node
->GetData();
200 m_children
.Erase(node
);
209 /// Delete all children
210 bool wxRichTextCompositeObject::DeleteChildren()
212 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
215 wxRichTextObjectList::compatibility_iterator oldNode
= node
;
217 wxRichTextObject
* child
= node
->GetData();
218 child
->Dereference(); // Only delete if reference count is zero
220 node
= node
->GetNext();
221 m_children
.Erase(oldNode
);
227 /// Get the child count
228 size_t wxRichTextCompositeObject::GetChildCount() const
230 return m_children
.GetCount();
234 void wxRichTextCompositeObject::Copy(const wxRichTextCompositeObject
& obj
)
236 wxRichTextObject::Copy(obj
);
240 wxRichTextObjectList::compatibility_iterator node
= obj
.m_children
.GetFirst();
243 wxRichTextObject
* child
= node
->GetData();
244 wxRichTextObject
* newChild
= child
->Clone();
245 newChild
->SetParent(this);
246 m_children
.Append(newChild
);
248 node
= node
->GetNext();
252 /// Hit-testing: returns a flag indicating hit test details, plus
253 /// information about position
254 int wxRichTextCompositeObject::HitTest(wxDC
& dc
, const wxPoint
& pt
, long& textPosition
)
256 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
259 wxRichTextObject
* child
= node
->GetData();
261 int ret
= child
->HitTest(dc
, pt
, textPosition
);
262 if (ret
!= wxRICHTEXT_HITTEST_NONE
)
265 node
= node
->GetNext();
268 return wxRICHTEXT_HITTEST_NONE
;
271 /// Finds the absolute position and row height for the given character position
272 bool wxRichTextCompositeObject::FindPosition(wxDC
& dc
, long index
, wxPoint
& pt
, int* height
, bool forceLineStart
)
274 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
277 wxRichTextObject
* child
= node
->GetData();
279 if (child
->FindPosition(dc
, index
, pt
, height
, forceLineStart
))
282 node
= node
->GetNext();
289 void wxRichTextCompositeObject::CalculateRange(long start
, long& end
)
291 long current
= start
;
292 long lastEnd
= current
;
294 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
297 wxRichTextObject
* child
= node
->GetData();
300 child
->CalculateRange(current
, childEnd
);
303 current
= childEnd
+ 1;
305 node
= node
->GetNext();
310 // An object with no children has zero length
311 if (m_children
.GetCount() == 0)
314 m_range
.SetRange(start
, end
);
317 /// Delete range from layout.
318 bool wxRichTextCompositeObject::DeleteRange(const wxRichTextRange
& range
)
320 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
324 wxRichTextObject
* obj
= (wxRichTextObject
*) node
->GetData();
325 wxRichTextObjectList::compatibility_iterator next
= node
->GetNext();
327 // Delete the range in each paragraph
329 // When a chunk has been deleted, internally the content does not
330 // now match the ranges.
331 // However, so long as deletion is not done on the same object twice this is OK.
332 // If you may delete content from the same object twice, recalculate
333 // the ranges inbetween DeleteRange calls by calling CalculateRanges, and
334 // adjust the range you're deleting accordingly.
336 if (!obj
->GetRange().IsOutside(range
))
338 obj
->DeleteRange(range
);
340 // Delete an empty object, or paragraph within this range.
341 if (obj
->IsEmpty() ||
342 (range
.GetStart() <= obj
->GetRange().GetStart() && range
.GetEnd() >= obj
->GetRange().GetEnd()))
344 // An empty paragraph has length 1, so won't be deleted unless the
345 // whole range is deleted.
346 RemoveChild(obj
, true);
356 /// Get any text in this object for the given range
357 wxString
wxRichTextCompositeObject::GetTextForRange(const wxRichTextRange
& range
) const
360 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
363 wxRichTextObject
* child
= node
->GetData();
364 wxRichTextRange childRange
= range
;
365 if (!child
->GetRange().IsOutside(range
))
367 childRange
.LimitTo(child
->GetRange());
369 wxString childText
= child
->GetTextForRange(childRange
);
373 node
= node
->GetNext();
379 /// Recursively merge all pieces that can be merged.
380 bool wxRichTextCompositeObject::Defragment()
382 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
385 wxRichTextObject
* child
= node
->GetData();
386 wxRichTextCompositeObject
* composite
= wxDynamicCast(child
, wxRichTextCompositeObject
);
388 composite
->Defragment();
392 wxRichTextObject
* nextChild
= node
->GetNext()->GetData();
393 if (child
->CanMerge(nextChild
) && child
->Merge(nextChild
))
395 nextChild
->Dereference();
396 m_children
.Erase(node
->GetNext());
398 // Don't set node -- we'll see if we can merge again with the next
402 node
= node
->GetNext();
405 node
= node
->GetNext();
411 /// Dump to output stream for debugging
412 void wxRichTextCompositeObject::Dump(wxTextOutputStream
& stream
)
414 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
417 wxRichTextObject
* child
= node
->GetData();
419 node
= node
->GetNext();
426 * This defines a 2D space to lay out objects
429 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBox
, wxRichTextCompositeObject
)
431 wxRichTextBox::wxRichTextBox(wxRichTextObject
* parent
):
432 wxRichTextCompositeObject(parent
)
437 bool wxRichTextBox::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& WXUNUSED(rect
), int descent
, int style
)
439 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
442 wxRichTextObject
* child
= node
->GetData();
444 wxRect childRect
= wxRect(child
->GetPosition(), child
->GetCachedSize());
445 child
->Draw(dc
, range
, selectionRange
, childRect
, descent
, style
);
447 node
= node
->GetNext();
453 bool wxRichTextBox::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
455 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
458 wxRichTextObject
* child
= node
->GetData();
459 child
->Layout(dc
, rect
, style
);
461 node
= node
->GetNext();
467 /// Get/set the size for the given range. Assume only has one child.
468 bool wxRichTextBox::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
) const
470 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
473 wxRichTextObject
* child
= node
->GetData();
474 return child
->GetRangeSize(range
, size
, descent
, dc
, flags
, position
);
481 void wxRichTextBox::Copy(const wxRichTextBox
& obj
)
483 wxRichTextCompositeObject::Copy(obj
);
488 * wxRichTextParagraphLayoutBox
489 * This box knows how to lay out paragraphs.
492 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraphLayoutBox
, wxRichTextBox
)
494 wxRichTextParagraphLayoutBox::wxRichTextParagraphLayoutBox(wxRichTextObject
* parent
):
495 wxRichTextBox(parent
)
500 /// Initialize the object.
501 void wxRichTextParagraphLayoutBox::Init()
505 // For now, assume is the only box and has no initial size.
506 m_range
= wxRichTextRange(0, -1);
508 m_invalidRange
.SetRange(-1, -1);
513 m_partialParagraph
= false;
517 bool wxRichTextParagraphLayoutBox::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int descent
, int style
)
519 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
522 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
523 wxASSERT (child
!= NULL
);
525 if (child
&& !child
->GetRange().IsOutside(range
))
527 wxRect
childRect(child
->GetPosition(), child
->GetCachedSize());
529 if (((style
& wxRICHTEXT_DRAW_IGNORE_CACHE
) == 0) && childRect
.GetTop() > rect
.GetBottom())
534 else if (((style
& wxRICHTEXT_DRAW_IGNORE_CACHE
) == 0) && childRect
.GetBottom() < rect
.GetTop())
539 child
->Draw(dc
, range
, selectionRange
, childRect
, descent
, style
);
542 node
= node
->GetNext();
548 bool wxRichTextParagraphLayoutBox::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
550 wxRect availableSpace
;
551 bool formatRect
= (style
& wxRICHTEXT_LAYOUT_SPECIFIED_RECT
) == wxRICHTEXT_LAYOUT_SPECIFIED_RECT
;
553 // If only laying out a specific area, the passed rect has a different meaning:
554 // the visible part of the buffer. This is used in wxRichTextCtrl::OnSize,
555 // so that during a size, only the visible part will be relaid out, or
556 // it would take too long causing flicker. As an approximation, we assume that
557 // everything up to the start of the visible area is laid out correctly.
560 availableSpace
= wxRect(0 + m_leftMargin
,
562 rect
.width
- m_leftMargin
- m_rightMargin
,
565 // Invalidate the part of the buffer from the first visible line
566 // to the end. If other parts of the buffer are currently invalid,
567 // then they too will be taken into account if they are above
568 // the visible point.
570 wxRichTextLine
* line
= GetLineAtYPosition(rect
.y
);
572 startPos
= line
->GetAbsoluteRange().GetStart();
574 Invalidate(wxRichTextRange(startPos
, GetRange().GetEnd()));
577 availableSpace
= wxRect(rect
.x
+ m_leftMargin
,
578 rect
.y
+ m_topMargin
,
579 rect
.width
- m_leftMargin
- m_rightMargin
,
580 rect
.height
- m_topMargin
- m_bottomMargin
);
584 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
586 bool layoutAll
= true;
588 // Get invalid range, rounding to paragraph start/end.
589 wxRichTextRange invalidRange
= GetInvalidRange(true);
591 if (invalidRange
== wxRICHTEXT_NONE
&& !formatRect
)
594 if (invalidRange
== wxRICHTEXT_ALL
)
596 else // If we know what range is affected, start laying out from that point on.
597 if (invalidRange
.GetStart() > GetRange().GetStart())
599 wxRichTextParagraph
* firstParagraph
= GetParagraphAtPosition(invalidRange
.GetStart());
602 wxRichTextObjectList::compatibility_iterator firstNode
= m_children
.Find(firstParagraph
);
603 wxRichTextObjectList::compatibility_iterator previousNode
;
605 previousNode
= firstNode
->GetPrevious();
606 if (firstNode
&& previousNode
)
608 wxRichTextParagraph
* previousParagraph
= wxDynamicCast(previousNode
->GetData(), wxRichTextParagraph
);
609 availableSpace
.y
= previousParagraph
->GetPosition().y
+ previousParagraph
->GetCachedSize().y
;
611 // Now we're going to start iterating from the first affected paragraph.
619 // A way to force speedy rest-of-buffer layout (the 'else' below)
620 bool forceQuickLayout
= false;
624 // Assume this box only contains paragraphs
626 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
627 wxCHECK_MSG( child
, false, _T("Unknown object in layout") );
629 // TODO: what if the child hasn't been laid out (e.g. involved in Undo) but still has 'old' lines
630 if ( !forceQuickLayout
&&
632 child
->GetLines().IsEmpty() ||
633 !child
->GetRange().IsOutside(invalidRange
)) )
635 child
->Layout(dc
, availableSpace
, style
);
637 // Layout must set the cached size
638 availableSpace
.y
+= child
->GetCachedSize().y
;
639 maxWidth
= wxMax(maxWidth
, child
->GetCachedSize().x
);
641 // If we're just formatting the visible part of the buffer,
642 // and we're now past the bottom of the window, start quick
644 if (formatRect
&& child
->GetPosition().y
> rect
.GetBottom())
645 forceQuickLayout
= true;
649 // We're outside the immediately affected range, so now let's just
650 // move everything up or down. This assumes that all the children have previously
651 // been laid out and have wrapped line lists associated with them.
652 // TODO: check all paragraphs before the affected range.
654 int inc
= availableSpace
.y
- child
->GetPosition().y
;
658 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
661 if (child
->GetLines().GetCount() == 0)
662 child
->Layout(dc
, availableSpace
, style
);
664 child
->SetPosition(wxPoint(child
->GetPosition().x
, child
->GetPosition().y
+ inc
));
666 availableSpace
.y
+= child
->GetCachedSize().y
;
667 maxWidth
= wxMax(maxWidth
, child
->GetCachedSize().x
);
670 node
= node
->GetNext();
675 node
= node
->GetNext();
678 SetCachedSize(wxSize(maxWidth
, availableSpace
.y
));
681 m_invalidRange
= wxRICHTEXT_NONE
;
687 void wxRichTextParagraphLayoutBox::Copy(const wxRichTextParagraphLayoutBox
& obj
)
689 wxRichTextBox::Copy(obj
);
691 m_partialParagraph
= obj
.m_partialParagraph
;
692 m_defaultAttributes
= obj
.m_defaultAttributes
;
695 /// Get/set the size for the given range.
696 bool wxRichTextParagraphLayoutBox::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
) const
700 wxRichTextObjectList::compatibility_iterator startPara
= wxRichTextObjectList::compatibility_iterator();
701 wxRichTextObjectList::compatibility_iterator endPara
= wxRichTextObjectList::compatibility_iterator();
703 // First find the first paragraph whose starting position is within the range.
704 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
707 // child is a paragraph
708 wxRichTextObject
* child
= node
->GetData();
709 const wxRichTextRange
& r
= child
->GetRange();
711 if (r
.GetStart() <= range
.GetStart() && r
.GetEnd() >= range
.GetStart())
717 node
= node
->GetNext();
720 // Next find the last paragraph containing part of the range
721 node
= m_children
.GetFirst();
724 // child is a paragraph
725 wxRichTextObject
* child
= node
->GetData();
726 const wxRichTextRange
& r
= child
->GetRange();
728 if (r
.GetStart() <= range
.GetEnd() && r
.GetEnd() >= range
.GetEnd())
734 node
= node
->GetNext();
737 if (!startPara
|| !endPara
)
740 // Now we can add up the sizes
741 for (node
= startPara
; node
; node
= node
->GetNext())
743 // child is a paragraph
744 wxRichTextObject
* child
= node
->GetData();
745 const wxRichTextRange
& childRange
= child
->GetRange();
746 wxRichTextRange rangeToFind
= range
;
747 rangeToFind
.LimitTo(childRange
);
751 int childDescent
= 0;
752 child
->GetRangeSize(rangeToFind
, childSize
, childDescent
, dc
, flags
, position
);
754 descent
= wxMax(childDescent
, descent
);
756 sz
.x
= wxMax(sz
.x
, childSize
.x
);
768 /// Get the paragraph at the given position
769 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphAtPosition(long pos
, bool caretPosition
) const
774 // First find the first paragraph whose starting position is within the range.
775 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
778 // child is a paragraph
779 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
780 wxASSERT (child
!= NULL
);
782 // Return first child in buffer if position is -1
786 if (child
->GetRange().Contains(pos
))
789 node
= node
->GetNext();
794 /// Get the line at the given position
795 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineAtPosition(long pos
, bool caretPosition
) const
800 // First find the first paragraph whose starting position is within the range.
801 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
804 // child is a paragraph
805 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
806 wxASSERT (child
!= NULL
);
808 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
811 wxRichTextLine
* line
= node2
->GetData();
813 wxRichTextRange range
= line
->GetAbsoluteRange();
815 if (range
.Contains(pos
) ||
817 // If the position is end-of-paragraph, then return the last line of
819 (range
.GetEnd() == child
->GetRange().GetEnd()-1) && (pos
== child
->GetRange().GetEnd()))
822 node2
= node2
->GetNext();
825 node
= node
->GetNext();
828 int lineCount
= GetLineCount();
830 return GetLineForVisibleLineNumber(lineCount
-1);
835 /// Get the line at the given y pixel position, or the last line.
836 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineAtYPosition(int y
) const
838 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
841 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
842 wxASSERT (child
!= NULL
);
844 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
847 wxRichTextLine
* line
= node2
->GetData();
849 wxRect
rect(line
->GetRect());
851 if (y
<= rect
.GetBottom())
854 node2
= node2
->GetNext();
857 node
= node
->GetNext();
861 int lineCount
= GetLineCount();
863 return GetLineForVisibleLineNumber(lineCount
-1);
868 /// Get the number of visible lines
869 int wxRichTextParagraphLayoutBox::GetLineCount() const
873 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
876 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
877 wxASSERT (child
!= NULL
);
879 count
+= child
->GetLines().GetCount();
880 node
= node
->GetNext();
886 /// Get the paragraph for a given line
887 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphForLine(wxRichTextLine
* line
) const
889 return GetParagraphAtPosition(line
->GetAbsoluteRange().GetStart());
892 /// Get the line size at the given position
893 wxSize
wxRichTextParagraphLayoutBox::GetLineSizeAtPosition(long pos
, bool caretPosition
) const
895 wxRichTextLine
* line
= GetLineAtPosition(pos
, caretPosition
);
898 return line
->GetSize();
905 /// Convenience function to add a paragraph of text
906 wxRichTextRange
wxRichTextParagraphLayoutBox::AddParagraph(const wxString
& text
, wxTextAttr
* paraStyle
)
908 // Don't use the base style, just the default style, and the base style will
909 // be combined at display time.
910 // Divide into paragraph and character styles.
912 wxTextAttr defaultCharStyle
;
913 wxTextAttr defaultParaStyle
;
915 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
916 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
917 wxTextAttr
* cStyle
= & defaultCharStyle
;
919 wxRichTextParagraph
* para
= new wxRichTextParagraph(text
, this, pStyle
, cStyle
);
926 return para
->GetRange();
929 /// Adds multiple paragraphs, based on newlines.
930 wxRichTextRange
wxRichTextParagraphLayoutBox::AddParagraphs(const wxString
& text
, wxTextAttr
* paraStyle
)
932 // Don't use the base style, just the default style, and the base style will
933 // be combined at display time.
934 // Divide into paragraph and character styles.
936 wxTextAttr defaultCharStyle
;
937 wxTextAttr defaultParaStyle
;
938 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
940 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
941 wxTextAttr
* cStyle
= & defaultCharStyle
;
943 wxRichTextParagraph
* firstPara
= NULL
;
944 wxRichTextParagraph
* lastPara
= NULL
;
946 wxRichTextRange
range(-1, -1);
949 size_t len
= text
.length();
951 wxRichTextParagraph
* para
= new wxRichTextParagraph(wxEmptyString
, this, pStyle
, cStyle
);
961 if (ch
== wxT('\n') || ch
== wxT('\r'))
963 wxRichTextPlainText
* plainText
= (wxRichTextPlainText
*) para
->GetChildren().GetFirst()->GetData();
964 plainText
->SetText(line
);
966 para
= new wxRichTextParagraph(wxEmptyString
, this, pStyle
, cStyle
);
971 line
= wxEmptyString
;
981 wxRichTextPlainText
* plainText
= (wxRichTextPlainText
*) para
->GetChildren().GetFirst()->GetData();
982 plainText
->SetText(line
);
989 return wxRichTextRange(firstPara
->GetRange().GetStart(), lastPara
->GetRange().GetEnd());
992 /// Convenience function to add an image
993 wxRichTextRange
wxRichTextParagraphLayoutBox::AddImage(const wxImage
& image
, wxTextAttr
* paraStyle
)
995 // Don't use the base style, just the default style, and the base style will
996 // be combined at display time.
997 // Divide into paragraph and character styles.
999 wxTextAttr defaultCharStyle
;
1000 wxTextAttr defaultParaStyle
;
1001 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
1003 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
1004 wxTextAttr
* cStyle
= & defaultCharStyle
;
1006 wxRichTextParagraph
* para
= new wxRichTextParagraph(this, pStyle
);
1008 para
->AppendChild(new wxRichTextImage(image
, this, cStyle
));
1013 return para
->GetRange();
1017 /// Insert fragment into this box at the given position. If partialParagraph is true,
1018 /// it is assumed that the last (or only) paragraph is just a piece of data with no paragraph
1021 bool wxRichTextParagraphLayoutBox::InsertFragment(long position
, wxRichTextParagraphLayoutBox
& fragment
)
1025 // First, find the first paragraph whose starting position is within the range.
1026 wxRichTextParagraph
* para
= GetParagraphAtPosition(position
);
1029 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(para
);
1031 // Now split at this position, returning the object to insert the new
1032 // ones in front of.
1033 wxRichTextObject
* nextObject
= para
->SplitAt(position
);
1035 // Special case: partial paragraph, just one paragraph. Might be a small amount of
1036 // text, for example, so let's optimize.
1038 if (fragment
.GetPartialParagraph() && fragment
.GetChildren().GetCount() == 1)
1040 // Add the first para to this para...
1041 wxRichTextObjectList::compatibility_iterator firstParaNode
= fragment
.GetChildren().GetFirst();
1045 // Iterate through the fragment paragraph inserting the content into this paragraph.
1046 wxRichTextParagraph
* firstPara
= wxDynamicCast(firstParaNode
->GetData(), wxRichTextParagraph
);
1047 wxASSERT (firstPara
!= NULL
);
1049 // Apply the new paragraph attributes to the existing paragraph
1050 wxTextAttr
attr(para
->GetAttributes());
1051 wxRichTextApplyStyle(attr
, firstPara
->GetAttributes());
1052 para
->SetAttributes(attr
);
1054 wxRichTextObjectList::compatibility_iterator objectNode
= firstPara
->GetChildren().GetFirst();
1057 wxRichTextObject
* newObj
= objectNode
->GetData()->Clone();
1062 para
->AppendChild(newObj
);
1066 // Insert before nextObject
1067 para
->InsertChild(newObj
, nextObject
);
1070 objectNode
= objectNode
->GetNext();
1077 // Procedure for inserting a fragment consisting of a number of
1080 // 1. Remove and save the content that's after the insertion point, for adding
1081 // back once we've added the fragment.
1082 // 2. Add the content from the first fragment paragraph to the current
1084 // 3. Add remaining fragment paragraphs after the current paragraph.
1085 // 4. Add back the saved content from the first paragraph. If partialParagraph
1086 // is true, add it to the last paragraph added and not a new one.
1088 // 1. Remove and save objects after split point.
1089 wxList savedObjects
;
1091 para
->MoveToList(nextObject
, savedObjects
);
1093 // 2. Add the content from the 1st fragment paragraph.
1094 wxRichTextObjectList::compatibility_iterator firstParaNode
= fragment
.GetChildren().GetFirst();
1098 wxRichTextParagraph
* firstPara
= wxDynamicCast(firstParaNode
->GetData(), wxRichTextParagraph
);
1099 wxASSERT(firstPara
!= NULL
);
1101 wxRichTextObjectList::compatibility_iterator objectNode
= firstPara
->GetChildren().GetFirst();
1104 wxRichTextObject
* newObj
= objectNode
->GetData()->Clone();
1107 para
->AppendChild(newObj
);
1109 objectNode
= objectNode
->GetNext();
1112 // 3. Add remaining fragment paragraphs after the current paragraph.
1113 wxRichTextObjectList::compatibility_iterator nextParagraphNode
= node
->GetNext();
1114 wxRichTextObject
* nextParagraph
= NULL
;
1115 if (nextParagraphNode
)
1116 nextParagraph
= nextParagraphNode
->GetData();
1118 wxRichTextObjectList::compatibility_iterator i
= fragment
.GetChildren().GetFirst()->GetNext();
1119 wxRichTextParagraph
* finalPara
= para
;
1121 // If there was only one paragraph, we need to insert a new one.
1124 finalPara
= new wxRichTextParagraph
;
1126 // TODO: These attributes should come from the subsequent paragraph
1127 // when originally deleted, since the subsequent para takes on
1128 // the previous para's attributes.
1129 finalPara
->SetAttributes(firstPara
->GetAttributes());
1132 InsertChild(finalPara
, nextParagraph
);
1134 AppendChild(finalPara
);
1138 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1139 wxASSERT( para
!= NULL
);
1141 finalPara
= (wxRichTextParagraph
*) para
->Clone();
1144 InsertChild(finalPara
, nextParagraph
);
1146 AppendChild(finalPara
);
1151 // 4. Add back the remaining content.
1154 finalPara
->MoveFromList(savedObjects
);
1156 // Ensure there's at least one object
1157 if (finalPara
->GetChildCount() == 0)
1159 wxRichTextPlainText
* text
= new wxRichTextPlainText(wxEmptyString
);
1161 finalPara
->AppendChild(text
);
1171 wxRichTextObjectList::compatibility_iterator i
= fragment
.GetChildren().GetFirst();
1174 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1175 wxASSERT( para
!= NULL
);
1177 AppendChild(para
->Clone());
1186 /// Make a copy of the fragment corresponding to the given range, putting it in 'fragment'.
1187 /// If there was an incomplete paragraph at the end, partialParagraph is set to true.
1188 bool wxRichTextParagraphLayoutBox::CopyFragment(const wxRichTextRange
& range
, wxRichTextParagraphLayoutBox
& fragment
)
1190 wxRichTextObjectList::compatibility_iterator i
= GetChildren().GetFirst();
1193 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1194 wxASSERT( para
!= NULL
);
1196 if (!para
->GetRange().IsOutside(range
))
1198 fragment
.AppendChild(para
->Clone());
1203 // Now top and tail the first and last paragraphs in our new fragment (which might be the same).
1204 if (!fragment
.IsEmpty())
1206 wxRichTextRange
topTailRange(range
);
1208 wxRichTextParagraph
* firstPara
= wxDynamicCast(fragment
.GetChildren().GetFirst()->GetData(), wxRichTextParagraph
);
1209 wxASSERT( firstPara
!= NULL
);
1211 // Chop off the start of the paragraph
1212 if (topTailRange
.GetStart() > firstPara
->GetRange().GetStart())
1214 wxRichTextRange
r(firstPara
->GetRange().GetStart(), topTailRange
.GetStart()-1);
1215 firstPara
->DeleteRange(r
);
1217 // Make sure the numbering is correct
1219 fragment
.CalculateRange(firstPara
->GetRange().GetStart(), end
);
1221 // Now, we've deleted some positions, so adjust the range
1223 topTailRange
.SetEnd(topTailRange
.GetEnd() - r
.GetLength());
1226 wxRichTextParagraph
* lastPara
= wxDynamicCast(fragment
.GetChildren().GetLast()->GetData(), wxRichTextParagraph
);
1227 wxASSERT( lastPara
!= NULL
);
1229 if (topTailRange
.GetEnd() < (lastPara
->GetRange().GetEnd()-1))
1231 wxRichTextRange
r(topTailRange
.GetEnd()+1, lastPara
->GetRange().GetEnd()-1); /* -1 since actual text ends 1 position before end of para marker */
1232 lastPara
->DeleteRange(r
);
1234 // Make sure the numbering is correct
1236 fragment
.CalculateRange(firstPara
->GetRange().GetStart(), end
);
1238 // We only have part of a paragraph at the end
1239 fragment
.SetPartialParagraph(true);
1243 if (topTailRange
.GetEnd() == (lastPara
->GetRange().GetEnd() - 1))
1244 // We have a partial paragraph (don't save last new paragraph marker)
1245 fragment
.SetPartialParagraph(true);
1247 // We have a complete paragraph
1248 fragment
.SetPartialParagraph(false);
1255 /// Given a position, get the number of the visible line (potentially many to a paragraph),
1256 /// starting from zero at the start of the buffer.
1257 long wxRichTextParagraphLayoutBox::GetVisibleLineNumber(long pos
, bool caretPosition
, bool startOfLine
) const
1264 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1267 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1268 wxASSERT( child
!= NULL
);
1270 if (child
->GetRange().Contains(pos
))
1272 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
1275 wxRichTextLine
* line
= node2
->GetData();
1276 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
1278 if (lineRange
.Contains(pos
))
1280 // If the caret is displayed at the end of the previous wrapped line,
1281 // we want to return the line it's _displayed_ at (not the actual line
1282 // containing the position).
1283 if (lineRange
.GetStart() == pos
&& !startOfLine
&& child
->GetRange().GetStart() != pos
)
1284 return lineCount
- 1;
1291 node2
= node2
->GetNext();
1293 // If we didn't find it in the lines, it must be
1294 // the last position of the paragraph. So return the last line.
1298 lineCount
+= child
->GetLines().GetCount();
1300 node
= node
->GetNext();
1307 /// Given a line number, get the corresponding wxRichTextLine object.
1308 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineForVisibleLineNumber(long lineNumber
) const
1312 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1315 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1316 wxASSERT(child
!= NULL
);
1318 if (lineNumber
< (int) (child
->GetLines().GetCount() + lineCount
))
1320 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
1323 wxRichTextLine
* line
= node2
->GetData();
1325 if (lineCount
== lineNumber
)
1330 node2
= node2
->GetNext();
1334 lineCount
+= child
->GetLines().GetCount();
1336 node
= node
->GetNext();
1343 /// Delete range from layout.
1344 bool wxRichTextParagraphLayoutBox::DeleteRange(const wxRichTextRange
& range
)
1346 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1350 wxRichTextParagraph
* obj
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1351 wxASSERT (obj
!= NULL
);
1353 wxRichTextObjectList::compatibility_iterator next
= node
->GetNext();
1355 // Delete the range in each paragraph
1357 if (!obj
->GetRange().IsOutside(range
))
1359 // Deletes the content of this object within the given range
1360 obj
->DeleteRange(range
);
1362 // If the whole paragraph is within the range to delete,
1363 // delete the whole thing.
1364 if (range
.GetStart() <= obj
->GetRange().GetStart() && range
.GetEnd() >= obj
->GetRange().GetEnd())
1366 // Delete the whole object
1367 RemoveChild(obj
, true);
1369 // If the range includes the paragraph end, we need to join this
1370 // and the next paragraph.
1371 else if (range
.Contains(obj
->GetRange().GetEnd()))
1373 // We need to move the objects from the next paragraph
1374 // to this paragraph
1378 wxRichTextParagraph
* nextParagraph
= wxDynamicCast(next
->GetData(), wxRichTextParagraph
);
1379 next
= next
->GetNext();
1382 // Delete the stuff we need to delete
1383 nextParagraph
->DeleteRange(range
);
1385 // Move the objects to the previous para
1386 wxRichTextObjectList::compatibility_iterator node1
= nextParagraph
->GetChildren().GetFirst();
1390 wxRichTextObject
* obj1
= node1
->GetData();
1392 // If the object is empty, optimise it out
1393 if (obj1
->IsEmpty())
1399 obj
->AppendChild(obj1
);
1402 wxRichTextObjectList::compatibility_iterator next1
= node1
->GetNext();
1403 nextParagraph
->GetChildren().Erase(node1
);
1408 // Delete the paragraph
1409 RemoveChild(nextParagraph
, true);
1423 /// Get any text in this object for the given range
1424 wxString
wxRichTextParagraphLayoutBox::GetTextForRange(const wxRichTextRange
& range
) const
1428 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1431 wxRichTextObject
* child
= node
->GetData();
1432 if (!child
->GetRange().IsOutside(range
))
1434 wxRichTextRange childRange
= range
;
1435 childRange
.LimitTo(child
->GetRange());
1437 wxString childText
= child
->GetTextForRange(childRange
);
1441 if ((childRange
.GetEnd() == child
->GetRange().GetEnd()) && node
->GetNext())
1446 node
= node
->GetNext();
1452 /// Get all the text
1453 wxString
wxRichTextParagraphLayoutBox::GetText() const
1455 return GetTextForRange(GetRange());
1458 /// Get the paragraph by number
1459 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphAtLine(long paragraphNumber
) const
1461 if ((size_t) paragraphNumber
>= GetChildCount())
1464 return (wxRichTextParagraph
*) GetChild((size_t) paragraphNumber
);
1467 /// Get the length of the paragraph
1468 int wxRichTextParagraphLayoutBox::GetParagraphLength(long paragraphNumber
) const
1470 wxRichTextParagraph
* para
= GetParagraphAtLine(paragraphNumber
);
1472 return para
->GetRange().GetLength() - 1; // don't include newline
1477 /// Get the text of the paragraph
1478 wxString
wxRichTextParagraphLayoutBox::GetParagraphText(long paragraphNumber
) const
1480 wxRichTextParagraph
* para
= GetParagraphAtLine(paragraphNumber
);
1482 return para
->GetTextForRange(para
->GetRange());
1484 return wxEmptyString
;
1487 /// Convert zero-based line column and paragraph number to a position.
1488 long wxRichTextParagraphLayoutBox::XYToPosition(long x
, long y
) const
1490 wxRichTextParagraph
* para
= GetParagraphAtLine(y
);
1493 return para
->GetRange().GetStart() + x
;
1499 /// Convert zero-based position to line column and paragraph number
1500 bool wxRichTextParagraphLayoutBox::PositionToXY(long pos
, long* x
, long* y
) const
1502 wxRichTextParagraph
* para
= GetParagraphAtPosition(pos
);
1506 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1509 wxRichTextObject
* child
= node
->GetData();
1513 node
= node
->GetNext();
1517 *x
= pos
- para
->GetRange().GetStart();
1525 /// Get the leaf object in a paragraph at this position.
1526 /// Given a line number, get the corresponding wxRichTextLine object.
1527 wxRichTextObject
* wxRichTextParagraphLayoutBox::GetLeafObjectAtPosition(long position
) const
1529 wxRichTextParagraph
* para
= GetParagraphAtPosition(position
);
1532 wxRichTextObjectList::compatibility_iterator node
= para
->GetChildren().GetFirst();
1536 wxRichTextObject
* child
= node
->GetData();
1537 if (child
->GetRange().Contains(position
))
1540 node
= node
->GetNext();
1542 if (position
== para
->GetRange().GetEnd() && para
->GetChildCount() > 0)
1543 return para
->GetChildren().GetLast()->GetData();
1548 /// Set character or paragraph text attributes: apply character styles only to immediate text nodes
1549 bool wxRichTextParagraphLayoutBox::SetStyle(const wxRichTextRange
& range
, const wxTextAttr
& style
, int flags
)
1551 bool characterStyle
= false;
1552 bool paragraphStyle
= false;
1554 if (style
.IsCharacterStyle())
1555 characterStyle
= true;
1556 if (style
.IsParagraphStyle())
1557 paragraphStyle
= true;
1559 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
1560 bool applyMinimal
= ((flags
& wxRICHTEXT_SETSTYLE_OPTIMIZE
) != 0);
1561 bool parasOnly
= ((flags
& wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY
) != 0);
1562 bool charactersOnly
= ((flags
& wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY
) != 0);
1563 bool resetExistingStyle
= ((flags
& wxRICHTEXT_SETSTYLE_RESET
) != 0);
1564 bool removeStyle
= ((flags
& wxRICHTEXT_SETSTYLE_REMOVE
) != 0);
1566 // Apply paragraph style first, if any
1567 wxTextAttr
wholeStyle(style
);
1569 if (!removeStyle
&& wholeStyle
.HasParagraphStyleName() && GetStyleSheet())
1571 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(wholeStyle
.GetParagraphStyleName());
1573 wxRichTextApplyStyle(wholeStyle
, def
->GetStyleMergedWithBase(GetStyleSheet()));
1576 // Limit the attributes to be set to the content to only character attributes.
1577 wxTextAttr
characterAttributes(wholeStyle
);
1578 characterAttributes
.SetFlags(characterAttributes
.GetFlags() & (wxTEXT_ATTR_CHARACTER
));
1580 if (!removeStyle
&& characterAttributes
.HasCharacterStyleName() && GetStyleSheet())
1582 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterAttributes
.GetCharacterStyleName());
1584 wxRichTextApplyStyle(characterAttributes
, def
->GetStyleMergedWithBase(GetStyleSheet()));
1587 // If we are associated with a control, make undoable; otherwise, apply immediately
1590 bool haveControl
= (GetRichTextCtrl() != NULL
);
1592 wxRichTextAction
* action
= NULL
;
1594 if (haveControl
&& withUndo
)
1596 action
= new wxRichTextAction(NULL
, _("Change Style"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
1597 action
->SetRange(range
);
1598 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
1601 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1604 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1605 wxASSERT (para
!= NULL
);
1607 if (para
&& para
->GetChildCount() > 0)
1609 // Stop searching if we're beyond the range of interest
1610 if (para
->GetRange().GetStart() > range
.GetEnd())
1613 if (!para
->GetRange().IsOutside(range
))
1615 // We'll be using a copy of the paragraph to make style changes,
1616 // not updating the buffer directly.
1617 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
1619 if (haveControl
&& withUndo
)
1621 newPara
= new wxRichTextParagraph(*para
);
1622 action
->GetNewParagraphs().AppendChild(newPara
);
1624 // Also store the old ones for Undo
1625 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
1630 // If we're specifying paragraphs only, then we really mean character formatting
1631 // to be included in the paragraph style
1632 if ((paragraphStyle
|| parasOnly
) && !charactersOnly
)
1636 // Removes the given style from the paragraph
1637 wxRichTextRemoveStyle(newPara
->GetAttributes(), style
);
1639 else if (resetExistingStyle
)
1640 newPara
->GetAttributes() = wholeStyle
;
1645 // Only apply attributes that will make a difference to the combined
1646 // style as seen on the display
1647 wxTextAttr
combinedAttr(para
->GetCombinedAttributes());
1648 wxRichTextApplyStyle(newPara
->GetAttributes(), wholeStyle
, & combinedAttr
);
1651 wxRichTextApplyStyle(newPara
->GetAttributes(), wholeStyle
);
1655 // When applying paragraph styles dynamically, don't change the text objects' attributes
1656 // since they will computed as needed. Only apply the character styling if it's _only_
1657 // character styling. This policy is subject to change and might be put under user control.
1659 // Hm. we might well be applying a mix of paragraph and character styles, in which
1660 // case we _do_ want to apply character styles regardless of what para styles are set.
1661 // But if we're applying a paragraph style, which has some character attributes, but
1662 // we only want the paragraphs to hold this character style, then we _don't_ want to
1663 // apply the character style. So we need to be able to choose.
1665 // if (!paragraphStyle && characterStyle && range.GetStart() != newPara->GetRange().GetEnd())
1666 if (!parasOnly
&& characterStyle
&& range
.GetStart() != newPara
->GetRange().GetEnd())
1668 wxRichTextRange
childRange(range
);
1669 childRange
.LimitTo(newPara
->GetRange());
1671 // Find the starting position and if necessary split it so
1672 // we can start applying a different style.
1673 // TODO: check that the style actually changes or is different
1674 // from style outside of range
1675 wxRichTextObject
* firstObject
wxDUMMY_INITIALIZE(NULL
);
1676 wxRichTextObject
* lastObject
wxDUMMY_INITIALIZE(NULL
);
1678 if (childRange
.GetStart() == newPara
->GetRange().GetStart())
1679 firstObject
= newPara
->GetChildren().GetFirst()->GetData();
1681 firstObject
= newPara
->SplitAt(range
.GetStart());
1683 // Increment by 1 because we're apply the style one _after_ the split point
1684 long splitPoint
= childRange
.GetEnd();
1685 if (splitPoint
!= newPara
->GetRange().GetEnd())
1689 if (splitPoint
== newPara
->GetRange().GetEnd() || splitPoint
== (newPara
->GetRange().GetEnd() - 1))
1690 lastObject
= newPara
->GetChildren().GetLast()->GetData();
1692 // lastObject is set as a side-effect of splitting. It's
1693 // returned as the object before the new object.
1694 (void) newPara
->SplitAt(splitPoint
, & lastObject
);
1696 wxASSERT(firstObject
!= NULL
);
1697 wxASSERT(lastObject
!= NULL
);
1699 if (!firstObject
|| !lastObject
)
1702 wxRichTextObjectList::compatibility_iterator firstNode
= newPara
->GetChildren().Find(firstObject
);
1703 wxRichTextObjectList::compatibility_iterator lastNode
= newPara
->GetChildren().Find(lastObject
);
1705 wxASSERT(firstNode
);
1708 wxRichTextObjectList::compatibility_iterator node2
= firstNode
;
1712 wxRichTextObject
* child
= node2
->GetData();
1716 // Removes the given style from the paragraph
1717 wxRichTextRemoveStyle(child
->GetAttributes(), style
);
1719 else if (resetExistingStyle
)
1720 child
->GetAttributes() = characterAttributes
;
1725 // Only apply attributes that will make a difference to the combined
1726 // style as seen on the display
1727 wxTextAttr
combinedAttr(newPara
->GetCombinedAttributes(child
->GetAttributes()));
1728 wxRichTextApplyStyle(child
->GetAttributes(), characterAttributes
, & combinedAttr
);
1731 wxRichTextApplyStyle(child
->GetAttributes(), characterAttributes
);
1734 if (node2
== lastNode
)
1737 node2
= node2
->GetNext();
1743 node
= node
->GetNext();
1746 // Do action, or delay it until end of batch.
1747 if (haveControl
&& withUndo
)
1748 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
1753 /// Get the text attributes for this position.
1754 bool wxRichTextParagraphLayoutBox::GetStyle(long position
, wxTextAttr
& style
)
1756 return DoGetStyle(position
, style
, true);
1759 bool wxRichTextParagraphLayoutBox::GetUncombinedStyle(long position
, wxTextAttr
& style
)
1761 return DoGetStyle(position
, style
, false);
1764 /// Implementation helper for GetStyle. If combineStyles is true, combine base, paragraph and
1765 /// context attributes.
1766 bool wxRichTextParagraphLayoutBox::DoGetStyle(long position
, wxTextAttr
& style
, bool combineStyles
)
1768 wxRichTextObject
* obj
wxDUMMY_INITIALIZE(NULL
);
1770 if (style
.IsParagraphStyle())
1772 obj
= GetParagraphAtPosition(position
);
1777 // Start with the base style
1778 style
= GetAttributes();
1780 // Apply the paragraph style
1781 wxRichTextApplyStyle(style
, obj
->GetAttributes());
1784 style
= obj
->GetAttributes();
1791 obj
= GetLeafObjectAtPosition(position
);
1796 wxRichTextParagraph
* para
= wxDynamicCast(obj
->GetParent(), wxRichTextParagraph
);
1797 style
= para
? para
->GetCombinedAttributes(obj
->GetAttributes()) : obj
->GetAttributes();
1800 style
= obj
->GetAttributes();
1808 static bool wxHasStyle(long flags
, long style
)
1810 return (flags
& style
) != 0;
1813 /// Combines 'style' with 'currentStyle' for the purpose of summarising the attributes of a range of
1815 bool wxRichTextParagraphLayoutBox::CollectStyle(wxTextAttr
& currentStyle
, const wxTextAttr
& style
, long& multipleStyleAttributes
, int& multipleTextEffectAttributes
)
1817 if (style
.HasFont())
1819 if (style
.HasFontSize() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_SIZE
))
1821 if (currentStyle
.HasFontSize())
1823 if (currentStyle
.GetFontSize() != style
.GetFontSize())
1825 // Clash of style - mark as such
1826 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_SIZE
;
1827 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_SIZE
);
1832 currentStyle
.SetFontSize(style
.GetFontSize());
1836 if (style
.HasFontItalic() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_ITALIC
))
1838 if (currentStyle
.HasFontItalic())
1840 if (currentStyle
.GetFontStyle() != style
.GetFontStyle())
1842 // Clash of style - mark as such
1843 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_ITALIC
;
1844 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_ITALIC
);
1849 currentStyle
.SetFontStyle(style
.GetFontStyle());
1853 if (style
.HasFontWeight() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_WEIGHT
))
1855 if (currentStyle
.HasFontWeight())
1857 if (currentStyle
.GetFontWeight() != style
.GetFontWeight())
1859 // Clash of style - mark as such
1860 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_WEIGHT
;
1861 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_WEIGHT
);
1866 currentStyle
.SetFontWeight(style
.GetFontWeight());
1870 if (style
.HasFontFaceName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_FACE
))
1872 if (currentStyle
.HasFontFaceName())
1874 wxString
faceName1(currentStyle
.GetFontFaceName());
1875 wxString
faceName2(style
.GetFontFaceName());
1877 if (faceName1
!= faceName2
)
1879 // Clash of style - mark as such
1880 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_FACE
;
1881 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_FACE
);
1886 currentStyle
.SetFontFaceName(style
.GetFontFaceName());
1890 if (style
.HasFontUnderlined() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_UNDERLINE
))
1892 if (currentStyle
.HasFontUnderlined())
1894 if (currentStyle
.GetFontUnderlined() != style
.GetFontUnderlined())
1896 // Clash of style - mark as such
1897 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_UNDERLINE
;
1898 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_UNDERLINE
);
1903 currentStyle
.SetFontUnderlined(style
.GetFontUnderlined());
1908 if (style
.HasTextColour() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_TEXT_COLOUR
))
1910 if (currentStyle
.HasTextColour())
1912 if (currentStyle
.GetTextColour() != style
.GetTextColour())
1914 // Clash of style - mark as such
1915 multipleStyleAttributes
|= wxTEXT_ATTR_TEXT_COLOUR
;
1916 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_TEXT_COLOUR
);
1920 currentStyle
.SetTextColour(style
.GetTextColour());
1923 if (style
.HasBackgroundColour() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BACKGROUND_COLOUR
))
1925 if (currentStyle
.HasBackgroundColour())
1927 if (currentStyle
.GetBackgroundColour() != style
.GetBackgroundColour())
1929 // Clash of style - mark as such
1930 multipleStyleAttributes
|= wxTEXT_ATTR_BACKGROUND_COLOUR
;
1931 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BACKGROUND_COLOUR
);
1935 currentStyle
.SetBackgroundColour(style
.GetBackgroundColour());
1938 if (style
.HasAlignment() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_ALIGNMENT
))
1940 if (currentStyle
.HasAlignment())
1942 if (currentStyle
.GetAlignment() != style
.GetAlignment())
1944 // Clash of style - mark as such
1945 multipleStyleAttributes
|= wxTEXT_ATTR_ALIGNMENT
;
1946 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_ALIGNMENT
);
1950 currentStyle
.SetAlignment(style
.GetAlignment());
1953 if (style
.HasTabs() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_TABS
))
1955 if (currentStyle
.HasTabs())
1957 if (!wxRichTextTabsEq(currentStyle
.GetTabs(), style
.GetTabs()))
1959 // Clash of style - mark as such
1960 multipleStyleAttributes
|= wxTEXT_ATTR_TABS
;
1961 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_TABS
);
1965 currentStyle
.SetTabs(style
.GetTabs());
1968 if (style
.HasLeftIndent() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_LEFT_INDENT
))
1970 if (currentStyle
.HasLeftIndent())
1972 if (currentStyle
.GetLeftIndent() != style
.GetLeftIndent() || currentStyle
.GetLeftSubIndent() != style
.GetLeftSubIndent())
1974 // Clash of style - mark as such
1975 multipleStyleAttributes
|= wxTEXT_ATTR_LEFT_INDENT
;
1976 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LEFT_INDENT
);
1980 currentStyle
.SetLeftIndent(style
.GetLeftIndent(), style
.GetLeftSubIndent());
1983 if (style
.HasRightIndent() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_RIGHT_INDENT
))
1985 if (currentStyle
.HasRightIndent())
1987 if (currentStyle
.GetRightIndent() != style
.GetRightIndent())
1989 // Clash of style - mark as such
1990 multipleStyleAttributes
|= wxTEXT_ATTR_RIGHT_INDENT
;
1991 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_RIGHT_INDENT
);
1995 currentStyle
.SetRightIndent(style
.GetRightIndent());
1998 if (style
.HasParagraphSpacingAfter() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_PARA_SPACING_AFTER
))
2000 if (currentStyle
.HasParagraphSpacingAfter())
2002 if (currentStyle
.GetParagraphSpacingAfter() != style
.GetParagraphSpacingAfter())
2004 // Clash of style - mark as such
2005 multipleStyleAttributes
|= wxTEXT_ATTR_PARA_SPACING_AFTER
;
2006 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARA_SPACING_AFTER
);
2010 currentStyle
.SetParagraphSpacingAfter(style
.GetParagraphSpacingAfter());
2013 if (style
.HasParagraphSpacingBefore() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_PARA_SPACING_BEFORE
))
2015 if (currentStyle
.HasParagraphSpacingBefore())
2017 if (currentStyle
.GetParagraphSpacingBefore() != style
.GetParagraphSpacingBefore())
2019 // Clash of style - mark as such
2020 multipleStyleAttributes
|= wxTEXT_ATTR_PARA_SPACING_BEFORE
;
2021 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARA_SPACING_BEFORE
);
2025 currentStyle
.SetParagraphSpacingBefore(style
.GetParagraphSpacingBefore());
2028 if (style
.HasLineSpacing() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_LINE_SPACING
))
2030 if (currentStyle
.HasLineSpacing())
2032 if (currentStyle
.GetLineSpacing() != style
.GetLineSpacing())
2034 // Clash of style - mark as such
2035 multipleStyleAttributes
|= wxTEXT_ATTR_LINE_SPACING
;
2036 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LINE_SPACING
);
2040 currentStyle
.SetLineSpacing(style
.GetLineSpacing());
2043 if (style
.HasCharacterStyleName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_CHARACTER_STYLE_NAME
))
2045 if (currentStyle
.HasCharacterStyleName())
2047 if (currentStyle
.GetCharacterStyleName() != style
.GetCharacterStyleName())
2049 // Clash of style - mark as such
2050 multipleStyleAttributes
|= wxTEXT_ATTR_CHARACTER_STYLE_NAME
;
2051 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_CHARACTER_STYLE_NAME
);
2055 currentStyle
.SetCharacterStyleName(style
.GetCharacterStyleName());
2058 if (style
.HasParagraphStyleName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
))
2060 if (currentStyle
.HasParagraphStyleName())
2062 if (currentStyle
.GetParagraphStyleName() != style
.GetParagraphStyleName())
2064 // Clash of style - mark as such
2065 multipleStyleAttributes
|= wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
;
2066 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
);
2070 currentStyle
.SetParagraphStyleName(style
.GetParagraphStyleName());
2073 if (style
.HasListStyleName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_LIST_STYLE_NAME
))
2075 if (currentStyle
.HasListStyleName())
2077 if (currentStyle
.GetListStyleName() != style
.GetListStyleName())
2079 // Clash of style - mark as such
2080 multipleStyleAttributes
|= wxTEXT_ATTR_LIST_STYLE_NAME
;
2081 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LIST_STYLE_NAME
);
2085 currentStyle
.SetListStyleName(style
.GetListStyleName());
2088 if (style
.HasBulletStyle() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_STYLE
))
2090 if (currentStyle
.HasBulletStyle())
2092 if (currentStyle
.GetBulletStyle() != style
.GetBulletStyle())
2094 // Clash of style - mark as such
2095 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_STYLE
;
2096 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_STYLE
);
2100 currentStyle
.SetBulletStyle(style
.GetBulletStyle());
2103 if (style
.HasBulletNumber() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_NUMBER
))
2105 if (currentStyle
.HasBulletNumber())
2107 if (currentStyle
.GetBulletNumber() != style
.GetBulletNumber())
2109 // Clash of style - mark as such
2110 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_NUMBER
;
2111 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_NUMBER
);
2115 currentStyle
.SetBulletNumber(style
.GetBulletNumber());
2118 if (style
.HasBulletText() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_TEXT
))
2120 if (currentStyle
.HasBulletText())
2122 if (currentStyle
.GetBulletText() != style
.GetBulletText())
2124 // Clash of style - mark as such
2125 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_TEXT
;
2126 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_TEXT
);
2131 currentStyle
.SetBulletText(style
.GetBulletText());
2132 currentStyle
.SetBulletFont(style
.GetBulletFont());
2136 if (style
.HasBulletName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_NAME
))
2138 if (currentStyle
.HasBulletName())
2140 if (currentStyle
.GetBulletName() != style
.GetBulletName())
2142 // Clash of style - mark as such
2143 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_NAME
;
2144 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_NAME
);
2149 currentStyle
.SetBulletName(style
.GetBulletName());
2153 if (style
.HasURL() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_URL
))
2155 if (currentStyle
.HasURL())
2157 if (currentStyle
.GetURL() != style
.GetURL())
2159 // Clash of style - mark as such
2160 multipleStyleAttributes
|= wxTEXT_ATTR_URL
;
2161 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_URL
);
2166 currentStyle
.SetURL(style
.GetURL());
2170 if (style
.HasTextEffects() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_EFFECTS
))
2172 if (currentStyle
.HasTextEffects())
2174 // We need to find the bits in the new style that are different:
2175 // just look at those bits that are specified by the new style.
2177 int currentRelevantTextEffects
= currentStyle
.GetTextEffects() & style
.GetTextEffectFlags();
2178 int newRelevantTextEffects
= style
.GetTextEffects() & style
.GetTextEffectFlags();
2180 if (currentRelevantTextEffects
!= newRelevantTextEffects
)
2182 // Find the text effects that were different, using XOR
2183 int differentEffects
= currentRelevantTextEffects
^ newRelevantTextEffects
;
2185 // Clash of style - mark as such
2186 multipleTextEffectAttributes
|= differentEffects
;
2187 currentStyle
.SetTextEffectFlags(currentStyle
.GetTextEffectFlags() & ~differentEffects
);
2192 currentStyle
.SetTextEffects(style
.GetTextEffects());
2193 currentStyle
.SetTextEffectFlags(style
.GetTextEffectFlags());
2197 if (style
.HasOutlineLevel() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_OUTLINE_LEVEL
))
2199 if (currentStyle
.HasOutlineLevel())
2201 if (currentStyle
.GetOutlineLevel() != style
.GetOutlineLevel())
2203 // Clash of style - mark as such
2204 multipleStyleAttributes
|= wxTEXT_ATTR_OUTLINE_LEVEL
;
2205 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_OUTLINE_LEVEL
);
2209 currentStyle
.SetOutlineLevel(style
.GetOutlineLevel());
2215 /// Get the combined style for a range - if any attribute is different within the range,
2216 /// that attribute is not present within the flags.
2217 /// *** Note that this is not recursive, and so assumes that content inside a paragraph is not itself
2219 bool wxRichTextParagraphLayoutBox::GetStyleForRange(const wxRichTextRange
& range
, wxTextAttr
& style
)
2221 style
= wxTextAttr();
2223 // The attributes that aren't valid because of multiple styles within the range
2224 long multipleStyleAttributes
= 0;
2225 int multipleTextEffectAttributes
= 0;
2227 wxRichTextObjectList::compatibility_iterator node
= GetChildren().GetFirst();
2230 wxRichTextParagraph
* para
= (wxRichTextParagraph
*) node
->GetData();
2231 if (!(para
->GetRange().GetStart() > range
.GetEnd() || para
->GetRange().GetEnd() < range
.GetStart()))
2233 if (para
->GetChildren().GetCount() == 0)
2235 wxTextAttr paraStyle
= para
->GetCombinedAttributes();
2237 CollectStyle(style
, paraStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
);
2241 wxRichTextRange
paraRange(para
->GetRange());
2242 paraRange
.LimitTo(range
);
2244 // First collect paragraph attributes only
2245 wxTextAttr paraStyle
= para
->GetCombinedAttributes();
2246 paraStyle
.SetFlags(paraStyle
.GetFlags() & wxTEXT_ATTR_PARAGRAPH
);
2247 CollectStyle(style
, paraStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
);
2249 wxRichTextObjectList::compatibility_iterator childNode
= para
->GetChildren().GetFirst();
2253 wxRichTextObject
* child
= childNode
->GetData();
2254 if (!(child
->GetRange().GetStart() > range
.GetEnd() || child
->GetRange().GetEnd() < range
.GetStart()))
2256 wxTextAttr childStyle
= para
->GetCombinedAttributes(child
->GetAttributes());
2258 // Now collect character attributes only
2259 childStyle
.SetFlags(childStyle
.GetFlags() & wxTEXT_ATTR_CHARACTER
);
2261 CollectStyle(style
, childStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
);
2264 childNode
= childNode
->GetNext();
2268 node
= node
->GetNext();
2273 /// Set default style
2274 bool wxRichTextParagraphLayoutBox::SetDefaultStyle(const wxTextAttr
& style
)
2276 m_defaultAttributes
= style
;
2280 /// Test if this whole range has character attributes of the specified kind. If any
2281 /// of the attributes are different within the range, the test fails. You
2282 /// can use this to implement, for example, bold button updating. style must have
2283 /// flags indicating which attributes are of interest.
2284 bool wxRichTextParagraphLayoutBox::HasCharacterAttributes(const wxRichTextRange
& range
, const wxTextAttr
& style
) const
2287 int matchingCount
= 0;
2289 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2292 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2293 wxASSERT (para
!= NULL
);
2297 // Stop searching if we're beyond the range of interest
2298 if (para
->GetRange().GetStart() > range
.GetEnd())
2299 return foundCount
== matchingCount
;
2301 if (!para
->GetRange().IsOutside(range
))
2303 wxRichTextObjectList::compatibility_iterator node2
= para
->GetChildren().GetFirst();
2307 wxRichTextObject
* child
= node2
->GetData();
2308 if (!child
->GetRange().IsOutside(range
) && child
->IsKindOf(CLASSINFO(wxRichTextPlainText
)))
2311 wxTextAttr textAttr
= para
->GetCombinedAttributes(child
->GetAttributes());
2313 if (wxTextAttrEqPartial(textAttr
, style
, style
.GetFlags()))
2317 node2
= node2
->GetNext();
2322 node
= node
->GetNext();
2325 return foundCount
== matchingCount
;
2328 /// Test if this whole range has paragraph attributes of the specified kind. If any
2329 /// of the attributes are different within the range, the test fails. You
2330 /// can use this to implement, for example, centering button updating. style must have
2331 /// flags indicating which attributes are of interest.
2332 bool wxRichTextParagraphLayoutBox::HasParagraphAttributes(const wxRichTextRange
& range
, const wxTextAttr
& style
) const
2335 int matchingCount
= 0;
2337 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2340 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2341 wxASSERT (para
!= NULL
);
2345 // Stop searching if we're beyond the range of interest
2346 if (para
->GetRange().GetStart() > range
.GetEnd())
2347 return foundCount
== matchingCount
;
2349 if (!para
->GetRange().IsOutside(range
))
2351 wxTextAttr textAttr
= GetAttributes();
2352 // Apply the paragraph style
2353 wxRichTextApplyStyle(textAttr
, para
->GetAttributes());
2356 if (wxTextAttrEqPartial(textAttr
, style
, style
.GetFlags()))
2361 node
= node
->GetNext();
2363 return foundCount
== matchingCount
;
2366 void wxRichTextParagraphLayoutBox::Clear()
2371 void wxRichTextParagraphLayoutBox::Reset()
2375 AddParagraph(wxEmptyString
);
2377 Invalidate(wxRICHTEXT_ALL
);
2380 /// Invalidate the buffer. With no argument, invalidates whole buffer.
2381 void wxRichTextParagraphLayoutBox::Invalidate(const wxRichTextRange
& invalidRange
)
2385 if (invalidRange
== wxRICHTEXT_ALL
)
2387 m_invalidRange
= wxRICHTEXT_ALL
;
2391 // Already invalidating everything
2392 if (m_invalidRange
== wxRICHTEXT_ALL
)
2395 if ((invalidRange
.GetStart() < m_invalidRange
.GetStart()) || m_invalidRange
.GetStart() == -1)
2396 m_invalidRange
.SetStart(invalidRange
.GetStart());
2397 if (invalidRange
.GetEnd() > m_invalidRange
.GetEnd())
2398 m_invalidRange
.SetEnd(invalidRange
.GetEnd());
2401 /// Get invalid range, rounding to entire paragraphs if argument is true.
2402 wxRichTextRange
wxRichTextParagraphLayoutBox::GetInvalidRange(bool wholeParagraphs
) const
2404 if (m_invalidRange
== wxRICHTEXT_ALL
|| m_invalidRange
== wxRICHTEXT_NONE
)
2405 return m_invalidRange
;
2407 wxRichTextRange range
= m_invalidRange
;
2409 if (wholeParagraphs
)
2411 wxRichTextParagraph
* para1
= GetParagraphAtPosition(range
.GetStart());
2412 wxRichTextParagraph
* para2
= GetParagraphAtPosition(range
.GetEnd());
2414 range
.SetStart(para1
->GetRange().GetStart());
2416 range
.SetEnd(para2
->GetRange().GetEnd());
2421 /// Apply the style sheet to the buffer, for example if the styles have changed.
2422 bool wxRichTextParagraphLayoutBox::ApplyStyleSheet(wxRichTextStyleSheet
* styleSheet
)
2424 wxASSERT(styleSheet
!= NULL
);
2430 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2433 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2434 wxASSERT (para
!= NULL
);
2438 // Combine paragraph and list styles. If there is a list style in the original attributes,
2439 // the current indentation overrides anything else and is used to find the item indentation.
2440 // Also, for applying paragraph styles, consider having 2 modes: (1) we merge with what we have,
2441 // thereby taking into account all user changes, (2) reset the style completely (except for indentation/list
2442 // exception as above).
2443 // Problem: when changing from one list style to another, there's a danger that the level info will get lost.
2444 // So when changing a list style interactively, could retrieve level based on current style, then
2445 // set appropriate indent and apply new style.
2447 if (!para
->GetAttributes().GetParagraphStyleName().IsEmpty() && !para
->GetAttributes().GetListStyleName().IsEmpty())
2449 int currentIndent
= para
->GetAttributes().GetLeftIndent();
2451 wxRichTextParagraphStyleDefinition
* paraDef
= styleSheet
->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
2452 wxRichTextListStyleDefinition
* listDef
= styleSheet
->FindListStyle(para
->GetAttributes().GetListStyleName());
2453 if (paraDef
&& !listDef
)
2455 para
->GetAttributes() = paraDef
->GetStyleMergedWithBase(styleSheet
);
2458 else if (listDef
&& !paraDef
)
2460 // Set overall style defined for the list style definition
2461 para
->GetAttributes() = listDef
->GetStyleMergedWithBase(styleSheet
);
2463 // Apply the style for this level
2464 wxRichTextApplyStyle(para
->GetAttributes(), * listDef
->GetLevelAttributes(listDef
->FindLevelForIndent(currentIndent
)));
2467 else if (listDef
&& paraDef
)
2469 // Combines overall list style, style for level, and paragraph style
2470 para
->GetAttributes() = listDef
->CombineWithParagraphStyle(currentIndent
, paraDef
->GetStyleMergedWithBase(styleSheet
));
2474 else if (para
->GetAttributes().GetParagraphStyleName().IsEmpty() && !para
->GetAttributes().GetListStyleName().IsEmpty())
2476 int currentIndent
= para
->GetAttributes().GetLeftIndent();
2478 wxRichTextListStyleDefinition
* listDef
= styleSheet
->FindListStyle(para
->GetAttributes().GetListStyleName());
2480 // Overall list definition style
2481 para
->GetAttributes() = listDef
->GetStyleMergedWithBase(styleSheet
);
2483 // Style for this level
2484 wxRichTextApplyStyle(para
->GetAttributes(), * listDef
->GetLevelAttributes(listDef
->FindLevelForIndent(currentIndent
)));
2488 else if (!para
->GetAttributes().GetParagraphStyleName().IsEmpty() && para
->GetAttributes().GetListStyleName().IsEmpty())
2490 wxRichTextParagraphStyleDefinition
* def
= styleSheet
->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
2493 para
->GetAttributes() = def
->GetStyleMergedWithBase(styleSheet
);
2499 node
= node
->GetNext();
2501 return foundCount
!= 0;
2505 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2507 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2509 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
2510 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2511 bool specifyLevel
= ((flags
& wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL
) != 0);
2512 bool renumber
= ((flags
& wxRICHTEXT_SETSTYLE_RENUMBER
) != 0);
2514 // Current number, if numbering
2517 wxASSERT (!specifyLevel
|| (specifyLevel
&& (specifiedLevel
>= 0)));
2519 // If we are associated with a control, make undoable; otherwise, apply immediately
2522 bool haveControl
= (GetRichTextCtrl() != NULL
);
2524 wxRichTextAction
* action
= NULL
;
2526 if (haveControl
&& withUndo
)
2528 action
= new wxRichTextAction(NULL
, _("Change List Style"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2529 action
->SetRange(range
);
2530 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2533 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2536 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2537 wxASSERT (para
!= NULL
);
2539 if (para
&& para
->GetChildCount() > 0)
2541 // Stop searching if we're beyond the range of interest
2542 if (para
->GetRange().GetStart() > range
.GetEnd())
2545 if (!para
->GetRange().IsOutside(range
))
2547 // We'll be using a copy of the paragraph to make style changes,
2548 // not updating the buffer directly.
2549 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
2551 if (haveControl
&& withUndo
)
2553 newPara
= new wxRichTextParagraph(*para
);
2554 action
->GetNewParagraphs().AppendChild(newPara
);
2556 // Also store the old ones for Undo
2557 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
2564 int thisIndent
= newPara
->GetAttributes().GetLeftIndent();
2565 int thisLevel
= specifyLevel
? specifiedLevel
: def
->FindLevelForIndent(thisIndent
);
2567 // How is numbering going to work?
2568 // If we are renumbering, or numbering for the first time, we need to keep
2569 // track of the number for each level. But we might be simply applying a different
2571 // In Word, applying a style to several paragraphs, even if at different levels,
2572 // reverts the level back to the same one. So we could do the same here.
2573 // Renumbering will need to be done when we promote/demote a paragraph.
2575 // Apply the overall list style, and item style for this level
2576 wxTextAttr
listStyle(def
->GetCombinedStyleForLevel(thisLevel
, styleSheet
));
2577 wxRichTextApplyStyle(newPara
->GetAttributes(), listStyle
);
2579 // Now we need to do numbering
2582 newPara
->GetAttributes().SetBulletNumber(n
);
2587 else if (!newPara
->GetAttributes().GetListStyleName().IsEmpty())
2589 // if def is NULL, remove list style, applying any associated paragraph style
2590 // to restore the attributes
2592 newPara
->GetAttributes().SetListStyleName(wxEmptyString
);
2593 newPara
->GetAttributes().SetLeftIndent(0, 0);
2594 newPara
->GetAttributes().SetBulletText(wxEmptyString
);
2596 // Eliminate the main list-related attributes
2597 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
);
2599 if (styleSheet
&& !newPara
->GetAttributes().GetParagraphStyleName().IsEmpty())
2601 wxRichTextParagraphStyleDefinition
* def
= styleSheet
->FindParagraphStyle(newPara
->GetAttributes().GetParagraphStyleName());
2604 newPara
->GetAttributes() = def
->GetStyleMergedWithBase(styleSheet
);
2611 node
= node
->GetNext();
2614 // Do action, or delay it until end of batch.
2615 if (haveControl
&& withUndo
)
2616 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
2621 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int startFrom
, int specifiedLevel
)
2623 if (GetStyleSheet())
2625 wxRichTextListStyleDefinition
* def
= GetStyleSheet()->FindListStyle(defName
);
2627 return SetListStyle(range
, def
, flags
, startFrom
, specifiedLevel
);
2632 /// Clear list for given range
2633 bool wxRichTextParagraphLayoutBox::ClearListStyle(const wxRichTextRange
& range
, int flags
)
2635 return SetListStyle(range
, NULL
, flags
);
2638 /// Number/renumber any list elements in the given range
2639 bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2641 return DoNumberList(range
, range
, 0, def
, flags
, startFrom
, specifiedLevel
);
2644 /// Number/renumber any list elements in the given range. Also do promotion or demotion of items, if specified
2645 bool wxRichTextParagraphLayoutBox::DoNumberList(const wxRichTextRange
& range
, const wxRichTextRange
& promotionRange
, int promoteBy
,
2646 wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2648 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2650 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
2651 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2653 bool specifyLevel
= ((flags
& wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL
) != 0);
2656 bool renumber
= ((flags
& wxRICHTEXT_SETSTYLE_RENUMBER
) != 0);
2658 // Max number of levels
2659 const int maxLevels
= 10;
2661 // The level we're looking at now
2662 int currentLevel
= -1;
2664 // The item number for each level
2665 int levels
[maxLevels
];
2668 // Reset all numbering
2669 for (i
= 0; i
< maxLevels
; i
++)
2671 if (startFrom
!= -1)
2672 levels
[i
] = startFrom
-1;
2673 else if (renumber
) // start again
2676 levels
[i
] = -1; // start from the number we found, if any
2679 wxASSERT(!specifyLevel
|| (specifyLevel
&& (specifiedLevel
>= 0)));
2681 // If we are associated with a control, make undoable; otherwise, apply immediately
2684 bool haveControl
= (GetRichTextCtrl() != NULL
);
2686 wxRichTextAction
* action
= NULL
;
2688 if (haveControl
&& withUndo
)
2690 action
= new wxRichTextAction(NULL
, _("Renumber List"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2691 action
->SetRange(range
);
2692 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2695 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2698 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2699 wxASSERT (para
!= NULL
);
2701 if (para
&& para
->GetChildCount() > 0)
2703 // Stop searching if we're beyond the range of interest
2704 if (para
->GetRange().GetStart() > range
.GetEnd())
2707 if (!para
->GetRange().IsOutside(range
))
2709 // We'll be using a copy of the paragraph to make style changes,
2710 // not updating the buffer directly.
2711 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
2713 if (haveControl
&& withUndo
)
2715 newPara
= new wxRichTextParagraph(*para
);
2716 action
->GetNewParagraphs().AppendChild(newPara
);
2718 // Also store the old ones for Undo
2719 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
2724 wxRichTextListStyleDefinition
* defToUse
= def
;
2727 if (styleSheet
&& !newPara
->GetAttributes().GetListStyleName().IsEmpty())
2728 defToUse
= styleSheet
->FindListStyle(newPara
->GetAttributes().GetListStyleName());
2733 int thisIndent
= newPara
->GetAttributes().GetLeftIndent();
2734 int thisLevel
= defToUse
->FindLevelForIndent(thisIndent
);
2736 // If we've specified a level to apply to all, change the level.
2737 if (specifiedLevel
!= -1)
2738 thisLevel
= specifiedLevel
;
2740 // Do promotion if specified
2741 if ((promoteBy
!= 0) && !para
->GetRange().IsOutside(promotionRange
))
2743 thisLevel
= thisLevel
- promoteBy
;
2750 // Apply the overall list style, and item style for this level
2751 wxTextAttr
listStyle(defToUse
->GetCombinedStyleForLevel(thisLevel
, styleSheet
));
2752 wxRichTextApplyStyle(newPara
->GetAttributes(), listStyle
);
2754 // OK, we've (re)applied the style, now let's get the numbering right.
2756 if (currentLevel
== -1)
2757 currentLevel
= thisLevel
;
2759 // Same level as before, do nothing except increment level's number afterwards
2760 if (currentLevel
== thisLevel
)
2763 // A deeper level: start renumbering all levels after current level
2764 else if (thisLevel
> currentLevel
)
2766 for (i
= currentLevel
+1; i
<= thisLevel
; i
++)
2770 currentLevel
= thisLevel
;
2772 else if (thisLevel
< currentLevel
)
2774 currentLevel
= thisLevel
;
2777 // Use the current numbering if -1 and we have a bullet number already
2778 if (levels
[currentLevel
] == -1)
2780 if (newPara
->GetAttributes().HasBulletNumber())
2781 levels
[currentLevel
] = newPara
->GetAttributes().GetBulletNumber();
2783 levels
[currentLevel
] = 1;
2787 levels
[currentLevel
] ++;
2790 newPara
->GetAttributes().SetBulletNumber(levels
[currentLevel
]);
2792 // Create the bullet text if an outline list
2793 if (listStyle
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
)
2796 for (i
= 0; i
<= currentLevel
; i
++)
2798 if (!text
.IsEmpty())
2800 text
+= wxString::Format(wxT("%d"), levels
[i
]);
2802 newPara
->GetAttributes().SetBulletText(text
);
2808 node
= node
->GetNext();
2811 // Do action, or delay it until end of batch.
2812 if (haveControl
&& withUndo
)
2813 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
2818 bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int startFrom
, int specifiedLevel
)
2820 if (GetStyleSheet())
2822 wxRichTextListStyleDefinition
* def
= NULL
;
2823 if (!defName
.IsEmpty())
2824 def
= GetStyleSheet()->FindListStyle(defName
);
2825 return NumberList(range
, def
, flags
, startFrom
, specifiedLevel
);
2830 /// Promote the list items within the given range. promoteBy can be a positive or negative number, e.g. 1 or -1
2831 bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy
, const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int specifiedLevel
)
2834 // One strategy is to first work out the range within which renumbering must occur. Then could pass these two ranges
2835 // to NumberList with a flag indicating promotion is required within one of the ranges.
2836 // Find first and last paragraphs in range. Then for first, calculate new indentation and look back until we find
2837 // a paragraph that either has no list style, or has one that is different or whose indentation is less.
2838 // We start renumbering from the para after that different para we found. We specify that the numbering of that
2839 // list position will start from 1.
2840 // Similarly, we look after the last para in the promote range for an indentation that is less (or no list style).
2841 // We can end the renumbering at this point.
2843 // For now, only renumber within the promotion range.
2845 return DoNumberList(range
, range
, promoteBy
, def
, flags
, 1, specifiedLevel
);
2848 bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy
, const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int specifiedLevel
)
2850 if (GetStyleSheet())
2852 wxRichTextListStyleDefinition
* def
= NULL
;
2853 if (!defName
.IsEmpty())
2854 def
= GetStyleSheet()->FindListStyle(defName
);
2855 return PromoteList(promoteBy
, range
, def
, flags
, specifiedLevel
);
2860 /// Fills in the attributes for numbering a paragraph after previousParagraph. It also finds the
2861 /// position of the paragraph that it had to start looking from.
2862 bool wxRichTextParagraphLayoutBox::FindNextParagraphNumber(wxRichTextParagraph
* previousParagraph
, wxTextAttr
& attr
) const
2864 if (!previousParagraph
->GetAttributes().HasFlag(wxTEXT_ATTR_BULLET_STYLE
) || previousParagraph
->GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE
)
2867 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2868 if (styleSheet
&& !previousParagraph
->GetAttributes().GetListStyleName().IsEmpty())
2870 wxRichTextListStyleDefinition
* def
= styleSheet
->FindListStyle(previousParagraph
->GetAttributes().GetListStyleName());
2873 // int thisIndent = previousParagraph->GetAttributes().GetLeftIndent();
2874 // int thisLevel = def->FindLevelForIndent(thisIndent);
2876 bool isOutline
= (previousParagraph
->GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
) != 0;
2878 attr
.SetFlags(previousParagraph
->GetAttributes().GetFlags() & (wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_BULLET_NUMBER
|wxTEXT_ATTR_BULLET_TEXT
|wxTEXT_ATTR_BULLET_NAME
));
2879 if (previousParagraph
->GetAttributes().HasBulletName())
2880 attr
.SetBulletName(previousParagraph
->GetAttributes().GetBulletName());
2881 attr
.SetBulletStyle(previousParagraph
->GetAttributes().GetBulletStyle());
2882 attr
.SetListStyleName(previousParagraph
->GetAttributes().GetListStyleName());
2884 int nextNumber
= previousParagraph
->GetAttributes().GetBulletNumber() + 1;
2885 attr
.SetBulletNumber(nextNumber
);
2889 wxString text
= previousParagraph
->GetAttributes().GetBulletText();
2890 if (!text
.IsEmpty())
2892 int pos
= text
.Find(wxT('.'), true);
2893 if (pos
!= wxNOT_FOUND
)
2895 text
= text
.Mid(0, text
.Length() - pos
- 1);
2898 text
= wxEmptyString
;
2899 if (!text
.IsEmpty())
2901 text
+= wxString::Format(wxT("%d"), nextNumber
);
2902 attr
.SetBulletText(text
);
2916 * wxRichTextParagraph
2917 * This object represents a single paragraph (or in a straight text editor, a line).
2920 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraph
, wxRichTextBox
)
2922 wxArrayInt
wxRichTextParagraph::sm_defaultTabs
;
2924 wxRichTextParagraph::wxRichTextParagraph(wxRichTextObject
* parent
, wxTextAttr
* style
):
2925 wxRichTextBox(parent
)
2928 SetAttributes(*style
);
2931 wxRichTextParagraph::wxRichTextParagraph(const wxString
& text
, wxRichTextObject
* parent
, wxTextAttr
* paraStyle
, wxTextAttr
* charStyle
):
2932 wxRichTextBox(parent
)
2935 SetAttributes(*paraStyle
);
2937 AppendChild(new wxRichTextPlainText(text
, this, charStyle
));
2940 wxRichTextParagraph::~wxRichTextParagraph()
2946 bool wxRichTextParagraph::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& WXUNUSED(rect
), int WXUNUSED(descent
), int style
)
2948 wxTextAttr attr
= GetCombinedAttributes();
2950 // Draw the bullet, if any
2951 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
2953 if (attr
.GetLeftSubIndent() != 0)
2955 int spaceBeforePara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingBefore());
2956 int leftIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftIndent());
2958 wxTextAttr
bulletAttr(GetCombinedAttributes());
2960 // Combine with the font of the first piece of content, if one is specified
2961 if (GetChildren().GetCount() > 0)
2963 wxRichTextObject
* firstObj
= (wxRichTextObject
*) GetChildren().GetFirst()->GetData();
2964 if (firstObj
->GetAttributes().HasFont())
2966 wxRichTextApplyStyle(bulletAttr
, firstObj
->GetAttributes());
2970 // Get line height from first line, if any
2971 wxRichTextLine
* line
= m_cachedLines
.GetFirst() ? (wxRichTextLine
* ) m_cachedLines
.GetFirst()->GetData() : (wxRichTextLine
*) NULL
;
2974 int lineHeight
wxDUMMY_INITIALIZE(0);
2977 lineHeight
= line
->GetSize().y
;
2978 linePos
= line
->GetPosition() + GetPosition();
2983 if (bulletAttr
.HasFont() && GetBuffer())
2984 font
= GetBuffer()->GetFontTable().FindFont(bulletAttr
);
2986 font
= (*wxNORMAL_FONT
);
2990 lineHeight
= dc
.GetCharHeight();
2991 linePos
= GetPosition();
2992 linePos
.y
+= spaceBeforePara
;
2995 wxRect
bulletRect(GetPosition().x
+ leftIndent
, linePos
.y
, linePos
.x
- (GetPosition().x
+ leftIndent
), lineHeight
);
2997 if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP
)
2999 if (wxRichTextBuffer::GetRenderer())
3000 wxRichTextBuffer::GetRenderer()->DrawBitmapBullet(this, dc
, bulletAttr
, bulletRect
);
3002 else if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_STANDARD
)
3004 if (wxRichTextBuffer::GetRenderer())
3005 wxRichTextBuffer::GetRenderer()->DrawStandardBullet(this, dc
, bulletAttr
, bulletRect
);
3009 wxString bulletText
= GetBulletText();
3011 if (!bulletText
.empty() && wxRichTextBuffer::GetRenderer())
3012 wxRichTextBuffer::GetRenderer()->DrawTextBullet(this, dc
, bulletAttr
, bulletRect
, bulletText
);
3017 // Draw the range for each line, one object at a time.
3019 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3022 wxRichTextLine
* line
= node
->GetData();
3023 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3025 int maxDescent
= line
->GetDescent();
3027 // Lines are specified relative to the paragraph
3029 wxPoint linePosition
= line
->GetPosition() + GetPosition();
3030 wxPoint objectPosition
= linePosition
;
3032 // Loop through objects until we get to the one within range
3033 wxRichTextObjectList::compatibility_iterator node2
= m_children
.GetFirst();
3036 wxRichTextObject
* child
= node2
->GetData();
3038 if (!child
->GetRange().IsOutside(lineRange
) && !lineRange
.IsOutside(range
))
3040 // Draw this part of the line at the correct position
3041 wxRichTextRange
objectRange(child
->GetRange());
3042 objectRange
.LimitTo(lineRange
);
3046 child
->GetRangeSize(objectRange
, objectSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, objectPosition
);
3048 // Use the child object's width, but the whole line's height
3049 wxRect
childRect(objectPosition
, wxSize(objectSize
.x
, line
->GetSize().y
));
3050 child
->Draw(dc
, objectRange
, selectionRange
, childRect
, maxDescent
, style
);
3052 objectPosition
.x
+= objectSize
.x
;
3054 else if (child
->GetRange().GetStart() > lineRange
.GetEnd())
3055 // Can break out of inner loop now since we've passed this line's range
3058 node2
= node2
->GetNext();
3061 node
= node
->GetNext();
3067 /// Lay the item out
3068 bool wxRichTextParagraph::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
3070 wxTextAttr attr
= GetCombinedAttributes();
3074 // Increase the size of the paragraph due to spacing
3075 int spaceBeforePara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingBefore());
3076 int spaceAfterPara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingAfter());
3077 int leftIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftIndent());
3078 int leftSubIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftSubIndent());
3079 int rightIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetRightIndent());
3081 int lineSpacing
= 0;
3083 // Let's assume line spacing of 10 is normal, 15 is 1.5, 20 is 2, etc.
3084 if (attr
.GetLineSpacing() != 10 && GetBuffer())
3086 wxFont
font(GetBuffer()->GetFontTable().FindFont(attr
));
3088 lineSpacing
= (ConvertTenthsMMToPixels(dc
, dc
.GetCharHeight()) * attr
.GetLineSpacing())/10;
3091 // Available space for text on each line differs.
3092 int availableTextSpaceFirstLine
= rect
.GetWidth() - leftIndent
- rightIndent
;
3094 // Bullets start the text at the same position as subsequent lines
3095 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3096 availableTextSpaceFirstLine
-= leftSubIndent
;
3098 int availableTextSpaceSubsequentLines
= rect
.GetWidth() - leftIndent
- rightIndent
- leftSubIndent
;
3100 // Start position for each line relative to the paragraph
3101 int startPositionFirstLine
= leftIndent
;
3102 int startPositionSubsequentLines
= leftIndent
+ leftSubIndent
;
3104 // If we have a bullet in this paragraph, the start position for the first line's text
3105 // is actually leftIndent + leftSubIndent.
3106 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3107 startPositionFirstLine
= startPositionSubsequentLines
;
3109 long lastEndPos
= GetRange().GetStart()-1;
3110 long lastCompletedEndPos
= lastEndPos
;
3112 int currentWidth
= 0;
3113 SetPosition(rect
.GetPosition());
3115 wxPoint
currentPosition(0, spaceBeforePara
); // We will calculate lines relative to paragraph
3124 // We may need to go back to a previous child, in which case create the new line,
3125 // find the child corresponding to the start position of the string, and
3128 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3131 wxRichTextObject
* child
= node
->GetData();
3133 // If this is e.g. a composite text box, it will need to be laid out itself.
3134 // But if just a text fragment or image, for example, this will
3135 // do nothing. NB: won't we need to set the position after layout?
3136 // since for example if position is dependent on vertical line size, we
3137 // can't tell the position until the size is determined. So possibly introduce
3138 // another layout phase.
3140 // TODO: can't this be called only once per child?
3141 child
->Layout(dc
, rect
, style
);
3143 // Available width depends on whether we're on the first or subsequent lines
3144 int availableSpaceForText
= (lineCount
== 0 ? availableTextSpaceFirstLine
: availableTextSpaceSubsequentLines
);
3146 currentPosition
.x
= (lineCount
== 0 ? startPositionFirstLine
: startPositionSubsequentLines
);
3148 // We may only be looking at part of a child, if we searched back for wrapping
3149 // and found a suitable point some way into the child. So get the size for the fragment
3152 long nextBreakPos
= GetFirstLineBreakPosition(lastEndPos
+1);
3153 long lastPosToUse
= child
->GetRange().GetEnd();
3154 bool lineBreakInThisObject
= (nextBreakPos
> -1 && nextBreakPos
<= child
->GetRange().GetEnd());
3156 if (lineBreakInThisObject
)
3157 lastPosToUse
= nextBreakPos
;
3160 int childDescent
= 0;
3162 if ((nextBreakPos
== -1) && (lastEndPos
== child
->GetRange().GetStart() - 1)) // i.e. we want to get the whole thing
3164 childSize
= child
->GetCachedSize();
3165 childDescent
= child
->GetDescent();
3168 GetRangeSize(wxRichTextRange(lastEndPos
+1, lastPosToUse
), childSize
, childDescent
, dc
, wxRICHTEXT_UNFORMATTED
, rect
.GetPosition());
3171 // 1) There was a line break BEFORE the natural break
3172 // 2) There was a line break AFTER the natural break
3173 // 3) The child still fits (carry on)
3175 if ((lineBreakInThisObject
&& (childSize
.x
+ currentWidth
<= availableSpaceForText
)) ||
3176 (childSize
.x
+ currentWidth
> availableSpaceForText
))
3178 long wrapPosition
= 0;
3180 // Find a place to wrap. This may walk back to previous children,
3181 // for example if a word spans several objects.
3182 if (!FindWrapPosition(wxRichTextRange(lastCompletedEndPos
+1, child
->GetRange().GetEnd()), dc
, availableSpaceForText
, wrapPosition
))
3184 // If the function failed, just cut it off at the end of this child.
3185 wrapPosition
= child
->GetRange().GetEnd();
3188 // FindWrapPosition can still return a value that will put us in an endless wrapping loop
3189 if (wrapPosition
<= lastCompletedEndPos
)
3190 wrapPosition
= wxMax(lastCompletedEndPos
+1,child
->GetRange().GetEnd());
3192 // wxLogDebug(wxT("Split at %ld"), wrapPosition);
3194 // Let's find the actual size of the current line now
3196 wxRichTextRange
actualRange(lastCompletedEndPos
+1, wrapPosition
);
3197 GetRangeSize(actualRange
, actualSize
, childDescent
, dc
, wxRICHTEXT_UNFORMATTED
);
3198 currentWidth
= actualSize
.x
;
3199 lineHeight
= wxMax(lineHeight
, actualSize
.y
);
3200 maxDescent
= wxMax(childDescent
, maxDescent
);
3203 wxRichTextLine
* line
= AllocateLine(lineCount
);
3205 // Set relative range so we won't have to change line ranges when paragraphs are moved
3206 line
->SetRange(wxRichTextRange(actualRange
.GetStart() - GetRange().GetStart(), actualRange
.GetEnd() - GetRange().GetStart()));
3207 line
->SetPosition(currentPosition
);
3208 line
->SetSize(wxSize(currentWidth
, lineHeight
));
3209 line
->SetDescent(maxDescent
);
3211 // Now move down a line. TODO: add margins, spacing
3212 currentPosition
.y
+= lineHeight
;
3213 currentPosition
.y
+= lineSpacing
;
3216 maxWidth
= wxMax(maxWidth
, currentWidth
);
3220 // TODO: account for zero-length objects, such as fields
3221 wxASSERT(wrapPosition
> lastCompletedEndPos
);
3223 lastEndPos
= wrapPosition
;
3224 lastCompletedEndPos
= lastEndPos
;
3228 // May need to set the node back to a previous one, due to searching back in wrapping
3229 wxRichTextObject
* childAfterWrapPosition
= FindObjectAtPosition(wrapPosition
+1);
3230 if (childAfterWrapPosition
)
3231 node
= m_children
.Find(childAfterWrapPosition
);
3233 node
= node
->GetNext();
3237 // We still fit, so don't add a line, and keep going
3238 currentWidth
+= childSize
.x
;
3239 lineHeight
= wxMax(lineHeight
, childSize
.y
);
3240 maxDescent
= wxMax(childDescent
, maxDescent
);
3242 maxWidth
= wxMax(maxWidth
, currentWidth
);
3243 lastEndPos
= child
->GetRange().GetEnd();
3245 node
= node
->GetNext();
3249 // Add the last line - it's the current pos -> last para pos
3250 // Substract -1 because the last position is always the end-paragraph position.
3251 if (lastCompletedEndPos
<= GetRange().GetEnd()-1)
3253 currentPosition
.x
= (lineCount
== 0 ? startPositionFirstLine
: startPositionSubsequentLines
);
3255 wxRichTextLine
* line
= AllocateLine(lineCount
);
3257 wxRichTextRange
actualRange(lastCompletedEndPos
+1, GetRange().GetEnd()-1);
3259 // Set relative range so we won't have to change line ranges when paragraphs are moved
3260 line
->SetRange(wxRichTextRange(actualRange
.GetStart() - GetRange().GetStart(), actualRange
.GetEnd() - GetRange().GetStart()));
3262 line
->SetPosition(currentPosition
);
3264 if (lineHeight
== 0 && GetBuffer())
3266 wxFont
font(GetBuffer()->GetFontTable().FindFont(attr
));
3268 lineHeight
= dc
.GetCharHeight();
3270 if (maxDescent
== 0)
3273 dc
.GetTextExtent(wxT("X"), & w
, &h
, & maxDescent
);
3276 line
->SetSize(wxSize(currentWidth
, lineHeight
));
3277 line
->SetDescent(maxDescent
);
3278 currentPosition
.y
+= lineHeight
;
3279 currentPosition
.y
+= lineSpacing
;
3283 // Remove remaining unused line objects, if any
3284 ClearUnusedLines(lineCount
);
3286 // Apply styles to wrapped lines
3287 ApplyParagraphStyle(attr
, rect
);
3289 SetCachedSize(wxSize(maxWidth
, currentPosition
.y
+ spaceBeforePara
+ spaceAfterPara
));
3296 /// Apply paragraph styles, such as centering, to wrapped lines
3297 void wxRichTextParagraph::ApplyParagraphStyle(const wxTextAttr
& attr
, const wxRect
& rect
)
3299 if (!attr
.HasAlignment())
3302 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3305 wxRichTextLine
* line
= node
->GetData();
3307 wxPoint pos
= line
->GetPosition();
3308 wxSize size
= line
->GetSize();
3310 // centering, right-justification
3311 if (attr
.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_CENTRE
)
3313 pos
.x
= (rect
.GetWidth() - size
.x
)/2 + pos
.x
;
3314 line
->SetPosition(pos
);
3316 else if (attr
.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_RIGHT
)
3318 pos
.x
= pos
.x
+ rect
.GetWidth() - size
.x
;
3319 line
->SetPosition(pos
);
3322 node
= node
->GetNext();
3326 /// Insert text at the given position
3327 bool wxRichTextParagraph::InsertText(long pos
, const wxString
& text
)
3329 wxRichTextObject
* childToUse
= NULL
;
3330 wxRichTextObjectList::compatibility_iterator nodeToUse
= wxRichTextObjectList::compatibility_iterator();
3332 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3335 wxRichTextObject
* child
= node
->GetData();
3336 if (child
->GetRange().Contains(pos
) && child
->GetRange().GetLength() > 0)
3343 node
= node
->GetNext();
3348 wxRichTextPlainText
* textObject
= wxDynamicCast(childToUse
, wxRichTextPlainText
);
3351 int posInString
= pos
- textObject
->GetRange().GetStart();
3353 wxString newText
= textObject
->GetText().Mid(0, posInString
) +
3354 text
+ textObject
->GetText().Mid(posInString
);
3355 textObject
->SetText(newText
);
3357 int textLength
= text
.length();
3359 textObject
->SetRange(wxRichTextRange(textObject
->GetRange().GetStart(),
3360 textObject
->GetRange().GetEnd() + textLength
));
3362 // Increment the end range of subsequent fragments in this paragraph.
3363 // We'll set the paragraph range itself at a higher level.
3365 wxRichTextObjectList::compatibility_iterator node
= nodeToUse
->GetNext();
3368 wxRichTextObject
* child
= node
->GetData();
3369 child
->SetRange(wxRichTextRange(textObject
->GetRange().GetStart() + textLength
,
3370 textObject
->GetRange().GetEnd() + textLength
));
3372 node
= node
->GetNext();
3379 // TODO: if not a text object, insert at closest position, e.g. in front of it
3385 // Don't pass parent initially to suppress auto-setting of parent range.
3386 // We'll do that at a higher level.
3387 wxRichTextPlainText
* textObject
= new wxRichTextPlainText(text
, this);
3389 AppendChild(textObject
);
3396 void wxRichTextParagraph::Copy(const wxRichTextParagraph
& obj
)
3398 wxRichTextBox::Copy(obj
);
3401 /// Clear the cached lines
3402 void wxRichTextParagraph::ClearLines()
3404 WX_CLEAR_LIST(wxRichTextLineList
, m_cachedLines
);
3407 /// Get/set the object size for the given range. Returns false if the range
3408 /// is invalid for this object.
3409 bool wxRichTextParagraph::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
) const
3411 if (!range
.IsWithin(GetRange()))
3414 if (flags
& wxRICHTEXT_UNFORMATTED
)
3416 // Just use unformatted data, assume no line breaks
3417 // TODO: take into account line breaks
3421 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3424 wxRichTextObject
* child
= node
->GetData();
3425 if (!child
->GetRange().IsOutside(range
))
3429 wxRichTextRange rangeToUse
= range
;
3430 rangeToUse
.LimitTo(child
->GetRange());
3431 int childDescent
= 0;
3433 if (child
->GetRangeSize(rangeToUse
, childSize
, childDescent
, dc
, flags
, wxPoint(position
.x
+ sz
.x
, position
.y
)))
3435 sz
.y
= wxMax(sz
.y
, childSize
.y
);
3436 sz
.x
+= childSize
.x
;
3437 descent
= wxMax(descent
, childDescent
);
3441 node
= node
->GetNext();
3447 // Use formatted data, with line breaks
3450 // We're going to loop through each line, and then for each line,
3451 // call GetRangeSize for the fragment that comprises that line.
3452 // Only we have to do that multiple times within the line, because
3453 // the line may be broken into pieces. For now ignore line break commands
3454 // (so we can assume that getting the unformatted size for a fragment
3455 // within a line is the actual size)
3457 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3460 wxRichTextLine
* line
= node
->GetData();
3461 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3462 if (!lineRange
.IsOutside(range
))
3466 wxRichTextObjectList::compatibility_iterator node2
= m_children
.GetFirst();
3469 wxRichTextObject
* child
= node2
->GetData();
3471 if (!child
->GetRange().IsOutside(lineRange
))
3473 wxRichTextRange rangeToUse
= lineRange
;
3474 rangeToUse
.LimitTo(child
->GetRange());
3477 int childDescent
= 0;
3478 if (child
->GetRangeSize(rangeToUse
, childSize
, childDescent
, dc
, flags
, wxPoint(position
.x
+ sz
.x
, position
.y
)))
3480 lineSize
.y
= wxMax(lineSize
.y
, childSize
.y
);
3481 lineSize
.x
+= childSize
.x
;
3483 descent
= wxMax(descent
, childDescent
);
3486 node2
= node2
->GetNext();
3489 // Increase size by a line (TODO: paragraph spacing)
3491 sz
.x
= wxMax(sz
.x
, lineSize
.x
);
3493 node
= node
->GetNext();
3500 /// Finds the absolute position and row height for the given character position
3501 bool wxRichTextParagraph::FindPosition(wxDC
& dc
, long index
, wxPoint
& pt
, int* height
, bool forceLineStart
)
3505 wxRichTextLine
* line
= ((wxRichTextParagraphLayoutBox
*)GetParent())->GetLineAtPosition(0);
3507 *height
= line
->GetSize().y
;
3509 *height
= dc
.GetCharHeight();
3511 // -1 means 'the start of the buffer'.
3514 pt
= pt
+ line
->GetPosition();
3519 // The final position in a paragraph is taken to mean the position
3520 // at the start of the next paragraph.
3521 if (index
== GetRange().GetEnd())
3523 wxRichTextParagraphLayoutBox
* parent
= wxDynamicCast(GetParent(), wxRichTextParagraphLayoutBox
);
3524 wxASSERT( parent
!= NULL
);
3526 // Find the height at the next paragraph, if any
3527 wxRichTextLine
* line
= parent
->GetLineAtPosition(index
+ 1);
3530 *height
= line
->GetSize().y
;
3531 pt
= line
->GetAbsolutePosition();
3535 *height
= dc
.GetCharHeight();
3536 int indent
= ConvertTenthsMMToPixels(dc
, m_attributes
.GetLeftIndent());
3537 pt
= wxPoint(indent
, GetCachedSize().y
);
3543 if (index
< GetRange().GetStart() || index
> GetRange().GetEnd())
3546 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3549 wxRichTextLine
* line
= node
->GetData();
3550 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3551 if (index
>= lineRange
.GetStart() && index
<= lineRange
.GetEnd())
3553 // If this is the last point in the line, and we're forcing the
3554 // returned value to be the start of the next line, do the required
3556 if (index
== lineRange
.GetEnd() && forceLineStart
)
3558 if (node
->GetNext())
3560 wxRichTextLine
* nextLine
= node
->GetNext()->GetData();
3561 *height
= nextLine
->GetSize().y
;
3562 pt
= nextLine
->GetAbsolutePosition();
3567 pt
.y
= line
->GetPosition().y
+ GetPosition().y
;
3569 wxRichTextRange
r(lineRange
.GetStart(), index
);
3573 // We find the size of the line up to this point,
3574 // then we can add this size to the line start position and
3575 // paragraph start position to find the actual position.
3577 if (GetRangeSize(r
, rangeSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, line
->GetPosition()+ GetPosition()))
3579 pt
.x
= line
->GetPosition().x
+ GetPosition().x
+ rangeSize
.x
;
3580 *height
= line
->GetSize().y
;
3587 node
= node
->GetNext();
3593 /// Hit-testing: returns a flag indicating hit test details, plus
3594 /// information about position
3595 int wxRichTextParagraph::HitTest(wxDC
& dc
, const wxPoint
& pt
, long& textPosition
)
3597 wxPoint paraPos
= GetPosition();
3599 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3602 wxRichTextLine
* line
= node
->GetData();
3603 wxPoint linePos
= paraPos
+ line
->GetPosition();
3604 wxSize lineSize
= line
->GetSize();
3605 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3607 if (pt
.y
>= linePos
.y
&& pt
.y
<= linePos
.y
+ lineSize
.y
)
3609 if (pt
.x
< linePos
.x
)
3611 textPosition
= lineRange
.GetStart();
3612 return wxRICHTEXT_HITTEST_BEFORE
|wxRICHTEXT_HITTEST_OUTSIDE
;
3614 else if (pt
.x
>= (linePos
.x
+ lineSize
.x
))
3616 textPosition
= lineRange
.GetEnd();
3617 return wxRICHTEXT_HITTEST_AFTER
|wxRICHTEXT_HITTEST_OUTSIDE
;
3622 int lastX
= linePos
.x
;
3623 for (i
= lineRange
.GetStart(); i
<= lineRange
.GetEnd(); i
++)
3628 wxRichTextRange
rangeToUse(lineRange
.GetStart(), i
);
3630 GetRangeSize(rangeToUse
, childSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, linePos
);
3632 int nextX
= childSize
.x
+ linePos
.x
;
3634 if (pt
.x
>= lastX
&& pt
.x
<= nextX
)
3638 // So now we know it's between i-1 and i.
3639 // Let's see if we can be more precise about
3640 // which side of the position it's on.
3642 int midPoint
= (nextX
- lastX
)/2 + lastX
;
3643 if (pt
.x
>= midPoint
)
3644 return wxRICHTEXT_HITTEST_AFTER
;
3646 return wxRICHTEXT_HITTEST_BEFORE
;
3656 node
= node
->GetNext();
3659 return wxRICHTEXT_HITTEST_NONE
;
3662 /// Split an object at this position if necessary, and return
3663 /// the previous object, or NULL if inserting at beginning.
3664 wxRichTextObject
* wxRichTextParagraph::SplitAt(long pos
, wxRichTextObject
** previousObject
)
3666 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3669 wxRichTextObject
* child
= node
->GetData();
3671 if (pos
== child
->GetRange().GetStart())
3675 if (node
->GetPrevious())
3676 *previousObject
= node
->GetPrevious()->GetData();
3678 *previousObject
= NULL
;
3684 if (child
->GetRange().Contains(pos
))
3686 // This should create a new object, transferring part of
3687 // the content to the old object and the rest to the new object.
3688 wxRichTextObject
* newObject
= child
->DoSplit(pos
);
3690 // If we couldn't split this object, just insert in front of it.
3693 // Maybe this is an empty string, try the next one
3698 // Insert the new object after 'child'
3699 if (node
->GetNext())
3700 m_children
.Insert(node
->GetNext(), newObject
);
3702 m_children
.Append(newObject
);
3703 newObject
->SetParent(this);
3706 *previousObject
= child
;
3712 node
= node
->GetNext();
3715 *previousObject
= NULL
;
3719 /// Move content to a list from obj on
3720 void wxRichTextParagraph::MoveToList(wxRichTextObject
* obj
, wxList
& list
)
3722 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(obj
);
3725 wxRichTextObject
* child
= node
->GetData();
3728 wxRichTextObjectList::compatibility_iterator oldNode
= node
;
3730 node
= node
->GetNext();
3732 m_children
.DeleteNode(oldNode
);
3736 /// Add content back from list
3737 void wxRichTextParagraph::MoveFromList(wxList
& list
)
3739 for (wxList::compatibility_iterator node
= list
.GetFirst(); node
; node
= node
->GetNext())
3741 AppendChild((wxRichTextObject
*) node
->GetData());
3746 void wxRichTextParagraph::CalculateRange(long start
, long& end
)
3748 wxRichTextCompositeObject::CalculateRange(start
, end
);
3750 // Add one for end of paragraph
3753 m_range
.SetRange(start
, end
);
3756 /// Find the object at the given position
3757 wxRichTextObject
* wxRichTextParagraph::FindObjectAtPosition(long position
)
3759 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3762 wxRichTextObject
* obj
= node
->GetData();
3763 if (obj
->GetRange().Contains(position
))
3766 node
= node
->GetNext();
3771 /// Get the plain text searching from the start or end of the range.
3772 /// The resulting string may be shorter than the range given.
3773 bool wxRichTextParagraph::GetContiguousPlainText(wxString
& text
, const wxRichTextRange
& range
, bool fromStart
)
3775 text
= wxEmptyString
;
3779 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3782 wxRichTextObject
* obj
= node
->GetData();
3783 if (!obj
->GetRange().IsOutside(range
))
3785 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
3788 text
+= textObj
->GetTextForRange(range
);
3794 node
= node
->GetNext();
3799 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetLast();
3802 wxRichTextObject
* obj
= node
->GetData();
3803 if (!obj
->GetRange().IsOutside(range
))
3805 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
3808 text
= textObj
->GetTextForRange(range
) + text
;
3814 node
= node
->GetPrevious();
3821 /// Find a suitable wrap position.
3822 bool wxRichTextParagraph::FindWrapPosition(const wxRichTextRange
& range
, wxDC
& dc
, int availableSpace
, long& wrapPosition
)
3824 // Find the first position where the line exceeds the available space.
3827 long breakPosition
= range
.GetEnd();
3828 for (i
= range
.GetStart(); i
<= range
.GetEnd(); i
++)
3831 GetRangeSize(wxRichTextRange(range
.GetStart(), i
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
3833 if (sz
.x
> availableSpace
)
3835 breakPosition
= i
-1;
3840 // Now we know the last position on the line.
3841 // Let's try to find a word break.
3844 if (GetContiguousPlainText(plainText
, wxRichTextRange(range
.GetStart(), breakPosition
), false))
3846 int newLinePos
= plainText
.Find(wxRichTextLineBreakChar
);
3847 if (newLinePos
!= wxNOT_FOUND
)
3849 breakPosition
= wxMax(0, range
.GetStart() + newLinePos
);
3853 int spacePos
= plainText
.Find(wxT(' '), true);
3854 int tabPos
= plainText
.Find(wxT('\t'), true);
3855 int pos
= wxMax(spacePos
, tabPos
);
3856 if (pos
!= wxNOT_FOUND
)
3858 int positionsFromEndOfString
= plainText
.length() - pos
- 1;
3859 breakPosition
= breakPosition
- positionsFromEndOfString
;
3864 wrapPosition
= breakPosition
;
3869 /// Get the bullet text for this paragraph.
3870 wxString
wxRichTextParagraph::GetBulletText()
3872 if (GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE
||
3873 (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP
))
3874 return wxEmptyString
;
3876 int number
= GetAttributes().GetBulletNumber();
3879 if ((GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ARABIC
) || (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
))
3881 text
.Printf(wxT("%d"), number
);
3883 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER
)
3885 // TODO: Unicode, and also check if number > 26
3886 text
.Printf(wxT("%c"), (wxChar
) (number
+64));
3888 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER
)
3890 // TODO: Unicode, and also check if number > 26
3891 text
.Printf(wxT("%c"), (wxChar
) (number
+96));
3893 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER
)
3895 text
= wxRichTextDecimalToRoman(number
);
3897 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER
)
3899 text
= wxRichTextDecimalToRoman(number
);
3902 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL
)
3904 text
= GetAttributes().GetBulletText();
3907 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
)
3909 // The outline style relies on the text being computed statically,
3910 // since it depends on other levels points (e.g. 1.2.1.1). So normally the bullet text
3911 // should be stored in the attributes; if not, just use the number for this
3912 // level, as previously computed.
3913 if (!GetAttributes().GetBulletText().IsEmpty())
3914 text
= GetAttributes().GetBulletText();
3917 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PARENTHESES
)
3919 text
= wxT("(") + text
+ wxT(")");
3921 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS
)
3923 text
= text
+ wxT(")");
3926 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PERIOD
)
3934 /// Allocate or reuse a line object
3935 wxRichTextLine
* wxRichTextParagraph::AllocateLine(int pos
)
3937 if (pos
< (int) m_cachedLines
.GetCount())
3939 wxRichTextLine
* line
= m_cachedLines
.Item(pos
)->GetData();
3945 wxRichTextLine
* line
= new wxRichTextLine(this);
3946 m_cachedLines
.Append(line
);
3951 /// Clear remaining unused line objects, if any
3952 bool wxRichTextParagraph::ClearUnusedLines(int lineCount
)
3954 int cachedLineCount
= m_cachedLines
.GetCount();
3955 if ((int) cachedLineCount
> lineCount
)
3957 for (int i
= 0; i
< (int) (cachedLineCount
- lineCount
); i
++)
3959 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetLast();
3960 wxRichTextLine
* line
= node
->GetData();
3961 m_cachedLines
.Erase(node
);
3968 /// Get combined attributes of the base style, paragraph style and character style. We use this to dynamically
3969 /// retrieve the actual style.
3970 wxTextAttr
wxRichTextParagraph::GetCombinedAttributes(const wxTextAttr
& contentStyle
) const
3973 wxRichTextBuffer
* buf
= wxDynamicCast(GetParent(), wxRichTextBuffer
);
3976 attr
= buf
->GetBasicStyle();
3977 wxRichTextApplyStyle(attr
, GetAttributes());
3980 attr
= GetAttributes();
3982 wxRichTextApplyStyle(attr
, contentStyle
);
3986 /// Get combined attributes of the base style and paragraph style.
3987 wxTextAttr
wxRichTextParagraph::GetCombinedAttributes() const
3990 wxRichTextBuffer
* buf
= wxDynamicCast(GetParent(), wxRichTextBuffer
);
3993 attr
= buf
->GetBasicStyle();
3994 wxRichTextApplyStyle(attr
, GetAttributes());
3997 attr
= GetAttributes();
4002 /// Create default tabstop array
4003 void wxRichTextParagraph::InitDefaultTabs()
4005 // create a default tab list at 10 mm each.
4006 for (int i
= 0; i
< 20; ++i
)
4008 sm_defaultTabs
.Add(i
*100);
4012 /// Clear default tabstop array
4013 void wxRichTextParagraph::ClearDefaultTabs()
4015 sm_defaultTabs
.Clear();
4018 /// Get the first position from pos that has a line break character.
4019 long wxRichTextParagraph::GetFirstLineBreakPosition(long pos
)
4021 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
4024 wxRichTextObject
* obj
= node
->GetData();
4025 if (pos
>= obj
->GetRange().GetStart() && pos
<= obj
->GetRange().GetEnd())
4027 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
4030 long breakPos
= textObj
->GetFirstLineBreakPosition(pos
);
4035 node
= node
->GetNext();
4042 * This object represents a line in a paragraph, and stores
4043 * offsets from the start of the paragraph representing the
4044 * start and end positions of the line.
4047 wxRichTextLine::wxRichTextLine(wxRichTextParagraph
* parent
)
4053 void wxRichTextLine::Init(wxRichTextParagraph
* parent
)
4056 m_range
.SetRange(-1, -1);
4057 m_pos
= wxPoint(0, 0);
4058 m_size
= wxSize(0, 0);
4063 void wxRichTextLine::Copy(const wxRichTextLine
& obj
)
4065 m_range
= obj
.m_range
;
4068 /// Get the absolute object position
4069 wxPoint
wxRichTextLine::GetAbsolutePosition() const
4071 return m_parent
->GetPosition() + m_pos
;
4074 /// Get the absolute range
4075 wxRichTextRange
wxRichTextLine::GetAbsoluteRange() const
4077 wxRichTextRange
range(m_range
.GetStart() + m_parent
->GetRange().GetStart(), 0);
4078 range
.SetEnd(range
.GetStart() + m_range
.GetLength()-1);
4083 * wxRichTextPlainText
4084 * This object represents a single piece of text.
4087 IMPLEMENT_DYNAMIC_CLASS(wxRichTextPlainText
, wxRichTextObject
)
4089 wxRichTextPlainText::wxRichTextPlainText(const wxString
& text
, wxRichTextObject
* parent
, wxTextAttr
* style
):
4090 wxRichTextObject(parent
)
4093 SetAttributes(*style
);
4098 #define USE_KERNING_FIX 1
4100 // If insufficient tabs are defined, this is the tab width used
4101 #define WIDTH_FOR_DEFAULT_TABS 50
4104 bool wxRichTextPlainText::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int descent
, int WXUNUSED(style
))
4106 wxRichTextParagraph
* para
= wxDynamicCast(GetParent(), wxRichTextParagraph
);
4107 wxASSERT (para
!= NULL
);
4109 wxTextAttr
textAttr(para
? para
->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4111 int offset
= GetRange().GetStart();
4113 // Replace line break characters with spaces
4114 wxString str
= m_text
;
4115 wxString toRemove
= wxRichTextLineBreakChar
;
4116 str
.Replace(toRemove
, wxT(" "));
4118 long len
= range
.GetLength();
4119 wxString stringChunk
= str
.Mid(range
.GetStart() - offset
, (size_t) len
);
4120 if (textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
4121 stringChunk
.MakeUpper();
4123 int charHeight
= dc
.GetCharHeight();
4126 int y
= rect
.y
+ (rect
.height
- charHeight
- (descent
- m_descent
));
4128 // Test for the optimized situations where all is selected, or none
4131 wxFont
font(GetBuffer()->GetFontTable().FindFont(textAttr
));
4134 // (a) All selected.
4135 if (selectionRange
.GetStart() <= range
.GetStart() && selectionRange
.GetEnd() >= range
.GetEnd())
4137 DrawTabbedString(dc
, textAttr
, rect
, stringChunk
, x
, y
, true);
4139 // (b) None selected.
4140 else if (selectionRange
.GetEnd() < range
.GetStart() || selectionRange
.GetStart() > range
.GetEnd())
4142 // Draw all unselected
4143 DrawTabbedString(dc
, textAttr
, rect
, stringChunk
, x
, y
, false);
4147 // (c) Part selected, part not
4148 // Let's draw unselected chunk, selected chunk, then unselected chunk.
4150 dc
.SetBackgroundMode(wxTRANSPARENT
);
4152 // 1. Initial unselected chunk, if any, up until start of selection.
4153 if (selectionRange
.GetStart() > range
.GetStart() && selectionRange
.GetStart() <= range
.GetEnd())
4155 int r1
= range
.GetStart();
4156 int s1
= selectionRange
.GetStart()-1;
4157 int fragmentLen
= s1
- r1
+ 1;
4158 if (fragmentLen
< 0)
4159 wxLogDebug(wxT("Mid(%d, %d"), (int)(r1
- offset
), (int)fragmentLen
);
4160 wxString stringFragment
= str
.Mid(r1
- offset
, fragmentLen
);
4162 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, false);
4165 if (stringChunk
.Find(wxT("\t")) == wxNOT_FOUND
)
4167 // Compensate for kerning difference
4168 wxString
stringFragment2(str
.Mid(r1
- offset
, fragmentLen
+1));
4169 wxString
stringFragment3(str
.Mid(r1
- offset
+ fragmentLen
, 1));
4171 wxCoord w1
, h1
, w2
, h2
, w3
, h3
;
4172 dc
.GetTextExtent(stringFragment
, & w1
, & h1
);
4173 dc
.GetTextExtent(stringFragment2
, & w2
, & h2
);
4174 dc
.GetTextExtent(stringFragment3
, & w3
, & h3
);
4176 int kerningDiff
= (w1
+ w3
) - w2
;
4177 x
= x
- kerningDiff
;
4182 // 2. Selected chunk, if any.
4183 if (selectionRange
.GetEnd() >= range
.GetStart())
4185 int s1
= wxMax(selectionRange
.GetStart(), range
.GetStart());
4186 int s2
= wxMin(selectionRange
.GetEnd(), range
.GetEnd());
4188 int fragmentLen
= s2
- s1
+ 1;
4189 if (fragmentLen
< 0)
4190 wxLogDebug(wxT("Mid(%d, %d"), (int)(s1
- offset
), (int)fragmentLen
);
4191 wxString stringFragment
= str
.Mid(s1
- offset
, fragmentLen
);
4193 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, true);
4196 if (stringChunk
.Find(wxT("\t")) == wxNOT_FOUND
)
4198 // Compensate for kerning difference
4199 wxString
stringFragment2(str
.Mid(s1
- offset
, fragmentLen
+1));
4200 wxString
stringFragment3(str
.Mid(s1
- offset
+ fragmentLen
, 1));
4202 wxCoord w1
, h1
, w2
, h2
, w3
, h3
;
4203 dc
.GetTextExtent(stringFragment
, & w1
, & h1
);
4204 dc
.GetTextExtent(stringFragment2
, & w2
, & h2
);
4205 dc
.GetTextExtent(stringFragment3
, & w3
, & h3
);
4207 int kerningDiff
= (w1
+ w3
) - w2
;
4208 x
= x
- kerningDiff
;
4213 // 3. Remaining unselected chunk, if any
4214 if (selectionRange
.GetEnd() < range
.GetEnd())
4216 int s2
= wxMin(selectionRange
.GetEnd()+1, range
.GetEnd());
4217 int r2
= range
.GetEnd();
4219 int fragmentLen
= r2
- s2
+ 1;
4220 if (fragmentLen
< 0)
4221 wxLogDebug(wxT("Mid(%d, %d"), (int)(s2
- offset
), (int)fragmentLen
);
4222 wxString stringFragment
= str
.Mid(s2
- offset
, fragmentLen
);
4224 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, false);
4231 bool wxRichTextPlainText::DrawTabbedString(wxDC
& dc
, const wxTextAttr
& attr
, const wxRect
& rect
,wxString
& str
, wxCoord
& x
, wxCoord
& y
, bool selected
)
4233 bool hasTabs
= (str
.Find(wxT('\t')) != wxNOT_FOUND
);
4235 wxArrayInt tabArray
;
4239 if (attr
.GetTabs().IsEmpty())
4240 tabArray
= wxRichTextParagraph::GetDefaultTabs();
4242 tabArray
= attr
.GetTabs();
4243 tabCount
= tabArray
.GetCount();
4245 for (int i
= 0; i
< tabCount
; ++i
)
4247 int pos
= tabArray
[i
];
4248 pos
= ConvertTenthsMMToPixels(dc
, pos
);
4255 int nextTabPos
= -1;
4261 dc
.SetBrush(*wxBLACK_BRUSH
);
4262 dc
.SetPen(*wxBLACK_PEN
);
4263 dc
.SetTextForeground(*wxWHITE
);
4264 dc
.SetBackgroundMode(wxTRANSPARENT
);
4268 dc
.SetTextForeground(attr
.GetTextColour());
4270 if (attr
.HasFlag(wxTEXT_ATTR_BACKGROUND_COLOUR
) && attr
.GetBackgroundColour().IsOk())
4272 dc
.SetBackgroundMode(wxSOLID
);
4273 dc
.SetTextBackground(attr
.GetBackgroundColour());
4276 dc
.SetBackgroundMode(wxTRANSPARENT
);
4281 // the string has a tab
4282 // break up the string at the Tab
4283 wxString stringChunk
= str
.BeforeFirst(wxT('\t'));
4284 str
= str
.AfterFirst(wxT('\t'));
4285 dc
.GetTextExtent(stringChunk
, & w
, & h
);
4287 bool not_found
= true;
4288 for (int i
= 0; i
< tabCount
&& not_found
; ++i
)
4290 nextTabPos
= tabArray
.Item(i
);
4292 // Find the next tab position.
4293 // Even if we're at the end of the tab array, we must still draw the chunk.
4295 if (nextTabPos
> tabPos
|| (i
== (tabCount
- 1)))
4297 if (nextTabPos
<= tabPos
)
4299 int defaultTabWidth
= ConvertTenthsMMToPixels(dc
, WIDTH_FOR_DEFAULT_TABS
);
4300 nextTabPos
= tabPos
+ defaultTabWidth
;
4307 wxRect
selRect(x
, rect
.y
, w
, rect
.GetHeight());
4308 dc
.DrawRectangle(selRect
);
4310 dc
.DrawText(stringChunk
, x
, y
);
4312 if (attr
.HasTextEffects() && (attr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH
))
4314 wxPen oldPen
= dc
.GetPen();
4315 dc
.SetPen(wxPen(attr
.GetTextColour(), 1));
4316 dc
.DrawLine(x
, (int) (y
+(h
/2)+0.5), x
+w
, (int) (y
+(h
/2)+0.5));
4323 hasTabs
= (str
.Find(wxT('\t')) != wxNOT_FOUND
);
4328 dc
.GetTextExtent(str
, & w
, & h
);
4331 wxRect
selRect(x
, rect
.y
, w
, rect
.GetHeight());
4332 dc
.DrawRectangle(selRect
);
4334 dc
.DrawText(str
, x
, y
);
4336 if (attr
.HasTextEffects() && (attr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH
))
4338 wxPen oldPen
= dc
.GetPen();
4339 dc
.SetPen(wxPen(attr
.GetTextColour(), 1));
4340 dc
.DrawLine(x
, (int) (y
+(h
/2)+0.5), x
+w
, (int) (y
+(h
/2)+0.5));
4350 /// Lay the item out
4351 bool wxRichTextPlainText::Layout(wxDC
& dc
, const wxRect
& WXUNUSED(rect
), int WXUNUSED(style
))
4353 GetRangeSize(GetRange(), m_size
, m_descent
, dc
, 0, wxPoint(0, 0));
4359 void wxRichTextPlainText::Copy(const wxRichTextPlainText
& obj
)
4361 wxRichTextObject::Copy(obj
);
4363 m_text
= obj
.m_text
;
4366 /// Get/set the object size for the given range. Returns false if the range
4367 /// is invalid for this object.
4368 bool wxRichTextPlainText::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int WXUNUSED(flags
), wxPoint position
) const
4370 if (!range
.IsWithin(GetRange()))
4373 wxRichTextParagraph
* para
= wxDynamicCast(GetParent(), wxRichTextParagraph
);
4374 wxASSERT (para
!= NULL
);
4376 wxTextAttr
textAttr(para
? para
->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4378 // Always assume unformatted text, since at this level we have no knowledge
4379 // of line breaks - and we don't need it, since we'll calculate size within
4380 // formatted text by doing it in chunks according to the line ranges
4382 wxFont
font(GetBuffer()->GetFontTable().FindFont(textAttr
));
4385 int startPos
= range
.GetStart() - GetRange().GetStart();
4386 long len
= range
.GetLength();
4388 wxString
str(m_text
);
4389 wxString toReplace
= wxRichTextLineBreakChar
;
4390 str
.Replace(toReplace
, wxT(" "));
4392 wxString stringChunk
= str
.Mid(startPos
, (size_t) len
);
4394 if (textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
4395 stringChunk
.MakeUpper();
4399 if (stringChunk
.Find(wxT('\t')) != wxNOT_FOUND
)
4401 // the string has a tab
4402 wxArrayInt tabArray
;
4403 if (textAttr
.GetTabs().IsEmpty())
4404 tabArray
= wxRichTextParagraph::GetDefaultTabs();
4406 tabArray
= textAttr
.GetTabs();
4408 int tabCount
= tabArray
.GetCount();
4410 for (int i
= 0; i
< tabCount
; ++i
)
4412 int pos
= tabArray
[i
];
4413 pos
= ((wxRichTextPlainText
*) this)->ConvertTenthsMMToPixels(dc
, pos
);
4417 int nextTabPos
= -1;
4419 while (stringChunk
.Find(wxT('\t')) >= 0)
4421 // the string has a tab
4422 // break up the string at the Tab
4423 wxString stringFragment
= stringChunk
.BeforeFirst(wxT('\t'));
4424 stringChunk
= stringChunk
.AfterFirst(wxT('\t'));
4425 dc
.GetTextExtent(stringFragment
, & w
, & h
);
4427 int absoluteWidth
= width
+ position
.x
;
4429 bool notFound
= true;
4430 for (int i
= 0; i
< tabCount
&& notFound
; ++i
)
4432 nextTabPos
= tabArray
.Item(i
);
4434 // Find the next tab position.
4435 // Even if we're at the end of the tab array, we must still process the chunk.
4437 if (nextTabPos
> absoluteWidth
|| (i
== (tabCount
- 1)))
4439 if (nextTabPos
<= absoluteWidth
)
4441 int defaultTabWidth
= ((wxRichTextPlainText
*) this)->ConvertTenthsMMToPixels(dc
, WIDTH_FOR_DEFAULT_TABS
);
4442 nextTabPos
= absoluteWidth
+ defaultTabWidth
;
4446 width
= nextTabPos
- position
.x
;
4451 dc
.GetTextExtent(stringChunk
, & w
, & h
, & descent
);
4453 size
= wxSize(width
, dc
.GetCharHeight());
4458 /// Do a split, returning an object containing the second part, and setting
4459 /// the first part in 'this'.
4460 wxRichTextObject
* wxRichTextPlainText::DoSplit(long pos
)
4462 long index
= pos
- GetRange().GetStart();
4464 if (index
< 0 || index
>= (int) m_text
.length())
4467 wxString firstPart
= m_text
.Mid(0, index
);
4468 wxString secondPart
= m_text
.Mid(index
);
4472 wxRichTextPlainText
* newObject
= new wxRichTextPlainText(secondPart
);
4473 newObject
->SetAttributes(GetAttributes());
4475 newObject
->SetRange(wxRichTextRange(pos
, GetRange().GetEnd()));
4476 GetRange().SetEnd(pos
-1);
4482 void wxRichTextPlainText::CalculateRange(long start
, long& end
)
4484 end
= start
+ m_text
.length() - 1;
4485 m_range
.SetRange(start
, end
);
4489 bool wxRichTextPlainText::DeleteRange(const wxRichTextRange
& range
)
4491 wxRichTextRange r
= range
;
4493 r
.LimitTo(GetRange());
4495 if (r
.GetStart() == GetRange().GetStart() && r
.GetEnd() == GetRange().GetEnd())
4501 long startIndex
= r
.GetStart() - GetRange().GetStart();
4502 long len
= r
.GetLength();
4504 m_text
= m_text
.Mid(0, startIndex
) + m_text
.Mid(startIndex
+len
);
4508 /// Get text for the given range.
4509 wxString
wxRichTextPlainText::GetTextForRange(const wxRichTextRange
& range
) const
4511 wxRichTextRange r
= range
;
4513 r
.LimitTo(GetRange());
4515 long startIndex
= r
.GetStart() - GetRange().GetStart();
4516 long len
= r
.GetLength();
4518 return m_text
.Mid(startIndex
, len
);
4521 /// Returns true if this object can merge itself with the given one.
4522 bool wxRichTextPlainText::CanMerge(wxRichTextObject
* object
) const
4524 return object
->GetClassInfo() == CLASSINFO(wxRichTextPlainText
) &&
4525 (m_text
.empty() || wxTextAttrEq(GetAttributes(), object
->GetAttributes()));
4528 /// Returns true if this object merged itself with the given one.
4529 /// The calling code will then delete the given object.
4530 bool wxRichTextPlainText::Merge(wxRichTextObject
* object
)
4532 wxRichTextPlainText
* textObject
= wxDynamicCast(object
, wxRichTextPlainText
);
4533 wxASSERT( textObject
!= NULL
);
4537 m_text
+= textObject
->GetText();
4544 /// Dump to output stream for debugging
4545 void wxRichTextPlainText::Dump(wxTextOutputStream
& stream
)
4547 wxRichTextObject::Dump(stream
);
4548 stream
<< m_text
<< wxT("\n");
4551 /// Get the first position from pos that has a line break character.
4552 long wxRichTextPlainText::GetFirstLineBreakPosition(long pos
)
4555 int len
= m_text
.length();
4556 int startPos
= pos
- m_range
.GetStart();
4557 for (i
= startPos
; i
< len
; i
++)
4559 wxChar ch
= m_text
[i
];
4560 if (ch
== wxRichTextLineBreakChar
)
4562 return i
+ m_range
.GetStart();
4570 * This is a kind of box, used to represent the whole buffer
4573 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBuffer
, wxRichTextParagraphLayoutBox
)
4575 wxList
wxRichTextBuffer::sm_handlers
;
4576 wxRichTextRenderer
* wxRichTextBuffer::sm_renderer
= NULL
;
4577 int wxRichTextBuffer::sm_bulletRightMargin
= 20;
4578 float wxRichTextBuffer::sm_bulletProportion
= (float) 0.3;
4581 void wxRichTextBuffer::Init()
4583 m_commandProcessor
= new wxCommandProcessor
;
4584 m_styleSheet
= NULL
;
4586 m_batchedCommandDepth
= 0;
4587 m_batchedCommand
= NULL
;
4594 wxRichTextBuffer::~wxRichTextBuffer()
4596 delete m_commandProcessor
;
4597 delete m_batchedCommand
;
4600 ClearEventHandlers();
4603 void wxRichTextBuffer::ResetAndClearCommands()
4607 GetCommandProcessor()->ClearCommands();
4610 Invalidate(wxRICHTEXT_ALL
);
4613 void wxRichTextBuffer::Copy(const wxRichTextBuffer
& obj
)
4615 wxRichTextParagraphLayoutBox::Copy(obj
);
4617 m_styleSheet
= obj
.m_styleSheet
;
4618 m_modified
= obj
.m_modified
;
4619 m_batchedCommandDepth
= obj
.m_batchedCommandDepth
;
4620 m_batchedCommand
= obj
.m_batchedCommand
;
4621 m_suppressUndo
= obj
.m_suppressUndo
;
4624 /// Push style sheet to top of stack
4625 bool wxRichTextBuffer::PushStyleSheet(wxRichTextStyleSheet
* styleSheet
)
4628 styleSheet
->InsertSheet(m_styleSheet
);
4630 SetStyleSheet(styleSheet
);
4635 /// Pop style sheet from top of stack
4636 wxRichTextStyleSheet
* wxRichTextBuffer::PopStyleSheet()
4640 wxRichTextStyleSheet
* oldSheet
= m_styleSheet
;
4641 m_styleSheet
= oldSheet
->GetNextSheet();
4650 /// Submit command to insert paragraphs
4651 bool wxRichTextBuffer::InsertParagraphsWithUndo(long pos
, const wxRichTextParagraphLayoutBox
& paragraphs
, wxRichTextCtrl
* ctrl
, int flags
)
4653 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4655 wxTextAttr
attr(GetDefaultStyle());
4657 wxTextAttr
* p
= NULL
;
4658 wxTextAttr paraAttr
;
4659 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4661 paraAttr
= GetStyleForNewParagraph(pos
);
4662 if (!paraAttr
.IsDefault())
4668 action
->GetNewParagraphs() = paragraphs
;
4672 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetLast();
4675 wxRichTextParagraph
* obj
= (wxRichTextParagraph
*) node
->GetData();
4676 obj
->SetAttributes(*p
);
4677 node
= node
->GetPrevious();
4681 action
->SetPosition(pos
);
4683 // Set the range we'll need to delete in Undo
4684 action
->SetRange(wxRichTextRange(pos
, pos
+ paragraphs
.GetRange().GetEnd() - 1));
4686 SubmitAction(action
);
4691 /// Submit command to insert the given text
4692 bool wxRichTextBuffer::InsertTextWithUndo(long pos
, const wxString
& text
, wxRichTextCtrl
* ctrl
, int flags
)
4694 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4696 wxTextAttr
* p
= NULL
;
4697 wxTextAttr paraAttr
;
4698 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4700 // Get appropriate paragraph style
4701 paraAttr
= GetStyleForNewParagraph(pos
, false, false);
4702 if (!paraAttr
.IsDefault())
4706 action
->GetNewParagraphs().AddParagraphs(text
, p
);
4708 int length
= action
->GetNewParagraphs().GetRange().GetLength();
4710 if (text
.length() > 0 && text
.Last() != wxT('\n'))
4712 // Don't count the newline when undoing
4714 action
->GetNewParagraphs().SetPartialParagraph(true);
4716 else if (text
.length() > 0 && text
.Last() == wxT('\n'))
4719 action
->SetPosition(pos
);
4721 // Set the range we'll need to delete in Undo
4722 action
->SetRange(wxRichTextRange(pos
, pos
+ length
- 1));
4724 SubmitAction(action
);
4729 /// Submit command to insert the given text
4730 bool wxRichTextBuffer::InsertNewlineWithUndo(long pos
, wxRichTextCtrl
* ctrl
, int flags
)
4732 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4734 wxTextAttr
* p
= NULL
;
4735 wxTextAttr paraAttr
;
4736 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4738 paraAttr
= GetStyleForNewParagraph(pos
, false, true /* look for next paragraph style */);
4739 if (!paraAttr
.IsDefault())
4743 wxTextAttr
attr(GetDefaultStyle());
4745 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(wxEmptyString
, this, & attr
);
4746 action
->GetNewParagraphs().AppendChild(newPara
);
4747 action
->GetNewParagraphs().UpdateRanges();
4748 action
->GetNewParagraphs().SetPartialParagraph(false);
4749 action
->SetPosition(pos
);
4752 newPara
->SetAttributes(*p
);
4754 // Set the range we'll need to delete in Undo
4755 action
->SetRange(wxRichTextRange(pos
, pos
));
4757 SubmitAction(action
);
4762 /// Submit command to insert the given image
4763 bool wxRichTextBuffer::InsertImageWithUndo(long pos
, const wxRichTextImageBlock
& imageBlock
, wxRichTextCtrl
* ctrl
, int flags
)
4765 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Image"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4767 wxTextAttr
* p
= NULL
;
4768 wxTextAttr paraAttr
;
4769 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4771 paraAttr
= GetStyleForNewParagraph(pos
);
4772 if (!paraAttr
.IsDefault())
4776 wxTextAttr
attr(GetDefaultStyle());
4778 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(this, & attr
);
4780 newPara
->SetAttributes(*p
);
4782 wxRichTextImage
* imageObject
= new wxRichTextImage(imageBlock
, newPara
);
4783 newPara
->AppendChild(imageObject
);
4784 action
->GetNewParagraphs().AppendChild(newPara
);
4785 action
->GetNewParagraphs().UpdateRanges();
4787 action
->GetNewParagraphs().SetPartialParagraph(true);
4789 action
->SetPosition(pos
);
4791 // Set the range we'll need to delete in Undo
4792 action
->SetRange(wxRichTextRange(pos
, pos
));
4794 SubmitAction(action
);
4799 /// Get the style that is appropriate for a new paragraph at this position.
4800 /// If the previous paragraph has a paragraph style name, look up the next-paragraph
4802 wxTextAttr
wxRichTextBuffer::GetStyleForNewParagraph(long pos
, bool caretPosition
, bool lookUpNewParaStyle
) const
4804 wxRichTextParagraph
* para
= GetParagraphAtPosition(pos
, caretPosition
);
4808 bool foundAttributes
= false;
4810 // Look for a matching paragraph style
4811 if (lookUpNewParaStyle
&& !para
->GetAttributes().GetParagraphStyleName().IsEmpty() && GetStyleSheet())
4813 wxRichTextParagraphStyleDefinition
* paraDef
= GetStyleSheet()->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
4816 if (!paraDef
->GetNextStyle().IsEmpty())
4818 wxRichTextParagraphStyleDefinition
* nextParaDef
= GetStyleSheet()->FindParagraphStyle(paraDef
->GetNextStyle());
4821 foundAttributes
= true;
4822 attr
= nextParaDef
->GetStyleMergedWithBase(GetStyleSheet());
4826 // If we didn't find the 'next style', use this style instead.
4827 if (!foundAttributes
)
4829 foundAttributes
= true;
4830 attr
= paraDef
->GetStyleMergedWithBase(GetStyleSheet());
4834 if (!foundAttributes
)
4836 attr
= para
->GetAttributes();
4837 int flags
= attr
.GetFlags();
4839 // Eliminate character styles
4840 flags
&= ( (~ wxTEXT_ATTR_FONT
) |
4841 (~ wxTEXT_ATTR_TEXT_COLOUR
) |
4842 (~ wxTEXT_ATTR_BACKGROUND_COLOUR
) );
4843 attr
.SetFlags(flags
);
4846 // Now see if we need to number the paragraph.
4847 if (attr
.HasBulletStyle())
4849 wxTextAttr numberingAttr
;
4850 if (FindNextParagraphNumber(para
, numberingAttr
))
4851 wxRichTextApplyStyle(attr
, (const wxTextAttr
&) numberingAttr
);
4857 return wxTextAttr();
4860 /// Submit command to delete this range
4861 bool wxRichTextBuffer::DeleteRangeWithUndo(const wxRichTextRange
& range
, wxRichTextCtrl
* ctrl
)
4863 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Delete"), wxRICHTEXT_DELETE
, this, ctrl
);
4865 action
->SetPosition(ctrl
->GetCaretPosition());
4867 // Set the range to delete
4868 action
->SetRange(range
);
4870 // Copy the fragment that we'll need to restore in Undo
4871 CopyFragment(range
, action
->GetOldParagraphs());
4873 // Special case: if there is only one (non-partial) paragraph,
4874 // we must save the *next* paragraph's style, because that
4875 // is the style we must apply when inserting the content back
4876 // when undoing the delete. (This is because we're merging the
4877 // paragraph with the previous paragraph and throwing away
4878 // the style, and we need to restore it.)
4879 if (!action
->GetOldParagraphs().GetPartialParagraph() && action
->GetOldParagraphs().GetChildCount() == 1)
4881 wxRichTextParagraph
* lastPara
= GetParagraphAtPosition(range
.GetStart());
4884 wxRichTextParagraph
* nextPara
= GetParagraphAtPosition(range
.GetEnd()+1);
4887 wxRichTextParagraph
* para
= (wxRichTextParagraph
*) action
->GetOldParagraphs().GetChild(0);
4888 para
->SetAttributes(nextPara
->GetAttributes());
4893 SubmitAction(action
);
4898 /// Collapse undo/redo commands
4899 bool wxRichTextBuffer::BeginBatchUndo(const wxString
& cmdName
)
4901 if (m_batchedCommandDepth
== 0)
4903 wxASSERT(m_batchedCommand
== NULL
);
4904 if (m_batchedCommand
)
4906 GetCommandProcessor()->Submit(m_batchedCommand
);
4908 m_batchedCommand
= new wxRichTextCommand(cmdName
);
4911 m_batchedCommandDepth
++;
4916 /// Collapse undo/redo commands
4917 bool wxRichTextBuffer::EndBatchUndo()
4919 m_batchedCommandDepth
--;
4921 wxASSERT(m_batchedCommandDepth
>= 0);
4922 wxASSERT(m_batchedCommand
!= NULL
);
4924 if (m_batchedCommandDepth
== 0)
4926 GetCommandProcessor()->Submit(m_batchedCommand
);
4927 m_batchedCommand
= NULL
;
4933 /// Submit immediately, or delay according to whether collapsing is on
4934 bool wxRichTextBuffer::SubmitAction(wxRichTextAction
* action
)
4936 if (BatchingUndo() && m_batchedCommand
&& !SuppressingUndo())
4937 m_batchedCommand
->AddAction(action
);
4940 wxRichTextCommand
* cmd
= new wxRichTextCommand(action
->GetName());
4941 cmd
->AddAction(action
);
4943 // Only store it if we're not suppressing undo.
4944 return GetCommandProcessor()->Submit(cmd
, !SuppressingUndo());
4950 /// Begin suppressing undo/redo commands.
4951 bool wxRichTextBuffer::BeginSuppressUndo()
4958 /// End suppressing undo/redo commands.
4959 bool wxRichTextBuffer::EndSuppressUndo()
4966 /// Begin using a style
4967 bool wxRichTextBuffer::BeginStyle(const wxTextAttr
& style
)
4969 wxTextAttr
newStyle(GetDefaultStyle());
4971 // Save the old default style
4972 m_attributeStack
.Append((wxObject
*) new wxTextAttr(GetDefaultStyle()));
4974 wxRichTextApplyStyle(newStyle
, style
);
4975 newStyle
.SetFlags(style
.GetFlags()|newStyle
.GetFlags());
4977 SetDefaultStyle(newStyle
);
4979 // wxLogDebug("Default style size = %d", GetDefaultStyle().GetFont().GetPointSize());
4985 bool wxRichTextBuffer::EndStyle()
4987 if (!m_attributeStack
.GetFirst())
4989 wxLogDebug(_("Too many EndStyle calls!"));
4993 wxList::compatibility_iterator node
= m_attributeStack
.GetLast();
4994 wxTextAttr
* attr
= (wxTextAttr
*)node
->GetData();
4995 m_attributeStack
.Erase(node
);
4997 SetDefaultStyle(*attr
);
5004 bool wxRichTextBuffer::EndAllStyles()
5006 while (m_attributeStack
.GetCount() != 0)
5011 /// Clear the style stack
5012 void wxRichTextBuffer::ClearStyleStack()
5014 for (wxList::compatibility_iterator node
= m_attributeStack
.GetFirst(); node
; node
= node
->GetNext())
5015 delete (wxTextAttr
*) node
->GetData();
5016 m_attributeStack
.Clear();
5019 /// Begin using bold
5020 bool wxRichTextBuffer::BeginBold()
5023 attr
.SetFontWeight(wxBOLD
);
5025 return BeginStyle(attr
);
5028 /// Begin using italic
5029 bool wxRichTextBuffer::BeginItalic()
5032 attr
.SetFontStyle(wxITALIC
);
5034 return BeginStyle(attr
);
5037 /// Begin using underline
5038 bool wxRichTextBuffer::BeginUnderline()
5041 attr
.SetFontUnderlined(true);
5043 return BeginStyle(attr
);
5046 /// Begin using point size
5047 bool wxRichTextBuffer::BeginFontSize(int pointSize
)
5050 attr
.SetFontSize(pointSize
);
5052 return BeginStyle(attr
);
5055 /// Begin using this font
5056 bool wxRichTextBuffer::BeginFont(const wxFont
& font
)
5061 return BeginStyle(attr
);
5064 /// Begin using this colour
5065 bool wxRichTextBuffer::BeginTextColour(const wxColour
& colour
)
5068 attr
.SetFlags(wxTEXT_ATTR_TEXT_COLOUR
);
5069 attr
.SetTextColour(colour
);
5071 return BeginStyle(attr
);
5074 /// Begin using alignment
5075 bool wxRichTextBuffer::BeginAlignment(wxTextAttrAlignment alignment
)
5078 attr
.SetFlags(wxTEXT_ATTR_ALIGNMENT
);
5079 attr
.SetAlignment(alignment
);
5081 return BeginStyle(attr
);
5084 /// Begin left indent
5085 bool wxRichTextBuffer::BeginLeftIndent(int leftIndent
, int leftSubIndent
)
5088 attr
.SetFlags(wxTEXT_ATTR_LEFT_INDENT
);
5089 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5091 return BeginStyle(attr
);
5094 /// Begin right indent
5095 bool wxRichTextBuffer::BeginRightIndent(int rightIndent
)
5098 attr
.SetFlags(wxTEXT_ATTR_RIGHT_INDENT
);
5099 attr
.SetRightIndent(rightIndent
);
5101 return BeginStyle(attr
);
5104 /// Begin paragraph spacing
5105 bool wxRichTextBuffer::BeginParagraphSpacing(int before
, int after
)
5109 flags
|= wxTEXT_ATTR_PARA_SPACING_BEFORE
;
5111 flags
|= wxTEXT_ATTR_PARA_SPACING_AFTER
;
5114 attr
.SetFlags(flags
);
5115 attr
.SetParagraphSpacingBefore(before
);
5116 attr
.SetParagraphSpacingAfter(after
);
5118 return BeginStyle(attr
);
5121 /// Begin line spacing
5122 bool wxRichTextBuffer::BeginLineSpacing(int lineSpacing
)
5125 attr
.SetFlags(wxTEXT_ATTR_LINE_SPACING
);
5126 attr
.SetLineSpacing(lineSpacing
);
5128 return BeginStyle(attr
);
5131 /// Begin numbered bullet
5132 bool wxRichTextBuffer::BeginNumberedBullet(int bulletNumber
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5135 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5136 attr
.SetBulletStyle(bulletStyle
);
5137 attr
.SetBulletNumber(bulletNumber
);
5138 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5140 return BeginStyle(attr
);
5143 /// Begin symbol bullet
5144 bool wxRichTextBuffer::BeginSymbolBullet(const wxString
& symbol
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5147 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5148 attr
.SetBulletStyle(bulletStyle
);
5149 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5150 attr
.SetBulletText(symbol
);
5152 return BeginStyle(attr
);
5155 /// Begin standard bullet
5156 bool wxRichTextBuffer::BeginStandardBullet(const wxString
& bulletName
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5159 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5160 attr
.SetBulletStyle(bulletStyle
);
5161 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5162 attr
.SetBulletName(bulletName
);
5164 return BeginStyle(attr
);
5167 /// Begin named character style
5168 bool wxRichTextBuffer::BeginCharacterStyle(const wxString
& characterStyle
)
5170 if (GetStyleSheet())
5172 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterStyle
);
5175 wxTextAttr attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5176 return BeginStyle(attr
);
5182 /// Begin named paragraph style
5183 bool wxRichTextBuffer::BeginParagraphStyle(const wxString
& paragraphStyle
)
5185 if (GetStyleSheet())
5187 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(paragraphStyle
);
5190 wxTextAttr attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5191 return BeginStyle(attr
);
5197 /// Begin named list style
5198 bool wxRichTextBuffer::BeginListStyle(const wxString
& listStyle
, int level
, int number
)
5200 if (GetStyleSheet())
5202 wxRichTextListStyleDefinition
* def
= GetStyleSheet()->FindListStyle(listStyle
);
5205 wxTextAttr
attr(def
->GetCombinedStyleForLevel(level
));
5207 attr
.SetBulletNumber(number
);
5209 return BeginStyle(attr
);
5216 bool wxRichTextBuffer::BeginURL(const wxString
& url
, const wxString
& characterStyle
)
5220 if (!characterStyle
.IsEmpty() && GetStyleSheet())
5222 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterStyle
);
5225 attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5230 return BeginStyle(attr
);
5233 /// Adds a handler to the end
5234 void wxRichTextBuffer::AddHandler(wxRichTextFileHandler
*handler
)
5236 sm_handlers
.Append(handler
);
5239 /// Inserts a handler at the front
5240 void wxRichTextBuffer::InsertHandler(wxRichTextFileHandler
*handler
)
5242 sm_handlers
.Insert( handler
);
5245 /// Removes a handler
5246 bool wxRichTextBuffer::RemoveHandler(const wxString
& name
)
5248 wxRichTextFileHandler
*handler
= FindHandler(name
);
5251 sm_handlers
.DeleteObject(handler
);
5259 /// Finds a handler by filename or, if supplied, type
5260 wxRichTextFileHandler
*wxRichTextBuffer::FindHandlerFilenameOrType(const wxString
& filename
, int imageType
)
5262 if (imageType
!= wxRICHTEXT_TYPE_ANY
)
5263 return FindHandler(imageType
);
5264 else if (!filename
.IsEmpty())
5266 wxString path
, file
, ext
;
5267 wxSplitPath(filename
, & path
, & file
, & ext
);
5268 return FindHandler(ext
, imageType
);
5275 /// Finds a handler by name
5276 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(const wxString
& name
)
5278 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5281 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5282 if (handler
->GetName().Lower() == name
.Lower()) return handler
;
5284 node
= node
->GetNext();
5289 /// Finds a handler by extension and type
5290 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(const wxString
& extension
, int type
)
5292 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5295 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5296 if ( handler
->GetExtension().Lower() == extension
.Lower() &&
5297 (type
== wxRICHTEXT_TYPE_ANY
|| handler
->GetType() == type
) )
5299 node
= node
->GetNext();
5304 /// Finds a handler by type
5305 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(int type
)
5307 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5310 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5311 if (handler
->GetType() == type
) return handler
;
5312 node
= node
->GetNext();
5317 void wxRichTextBuffer::InitStandardHandlers()
5319 if (!FindHandler(wxRICHTEXT_TYPE_TEXT
))
5320 AddHandler(new wxRichTextPlainTextHandler
);
5323 void wxRichTextBuffer::CleanUpHandlers()
5325 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5328 wxRichTextFileHandler
* handler
= (wxRichTextFileHandler
*)node
->GetData();
5329 wxList::compatibility_iterator next
= node
->GetNext();
5334 sm_handlers
.Clear();
5337 wxString
wxRichTextBuffer::GetExtWildcard(bool combine
, bool save
, wxArrayInt
* types
)
5344 wxList::compatibility_iterator node
= GetHandlers().GetFirst();
5348 wxRichTextFileHandler
* handler
= (wxRichTextFileHandler
*) node
->GetData();
5349 if (handler
->IsVisible() && ((save
&& handler
->CanSave()) || !save
&& handler
->CanLoad()))
5354 wildcard
+= wxT(";");
5355 wildcard
+= wxT("*.") + handler
->GetExtension();
5360 wildcard
+= wxT("|");
5361 wildcard
+= handler
->GetName();
5362 wildcard
+= wxT(" ");
5363 wildcard
+= _("files");
5364 wildcard
+= wxT(" (*.");
5365 wildcard
+= handler
->GetExtension();
5366 wildcard
+= wxT(")|*.");
5367 wildcard
+= handler
->GetExtension();
5369 types
->Add(handler
->GetType());
5374 node
= node
->GetNext();
5378 wildcard
= wxT("(") + wildcard
+ wxT(")|") + wildcard
;
5383 bool wxRichTextBuffer::LoadFile(const wxString
& filename
, int type
)
5385 wxRichTextFileHandler
* handler
= FindHandlerFilenameOrType(filename
, type
);
5388 SetDefaultStyle(wxTextAttr());
5389 handler
->SetFlags(GetHandlerFlags());
5390 bool success
= handler
->LoadFile(this, filename
);
5391 Invalidate(wxRICHTEXT_ALL
);
5399 bool wxRichTextBuffer::SaveFile(const wxString
& filename
, int type
)
5401 wxRichTextFileHandler
* handler
= FindHandlerFilenameOrType(filename
, type
);
5404 handler
->SetFlags(GetHandlerFlags());
5405 return handler
->SaveFile(this, filename
);
5411 /// Load from a stream
5412 bool wxRichTextBuffer::LoadFile(wxInputStream
& stream
, int type
)
5414 wxRichTextFileHandler
* handler
= FindHandler(type
);
5417 SetDefaultStyle(wxTextAttr());
5418 handler
->SetFlags(GetHandlerFlags());
5419 bool success
= handler
->LoadFile(this, stream
);
5420 Invalidate(wxRICHTEXT_ALL
);
5427 /// Save to a stream
5428 bool wxRichTextBuffer::SaveFile(wxOutputStream
& stream
, int type
)
5430 wxRichTextFileHandler
* handler
= FindHandler(type
);
5433 handler
->SetFlags(GetHandlerFlags());
5434 return handler
->SaveFile(this, stream
);
5440 /// Copy the range to the clipboard
5441 bool wxRichTextBuffer::CopyToClipboard(const wxRichTextRange
& range
)
5443 bool success
= false;
5444 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5446 if (!wxTheClipboard
->IsOpened() && wxTheClipboard
->Open())
5448 wxTheClipboard
->Clear();
5450 // Add composite object
5452 wxDataObjectComposite
* compositeObject
= new wxDataObjectComposite();
5455 wxString text
= GetTextForRange(range
);
5458 text
= wxTextFile::Translate(text
, wxTextFileType_Dos
);
5461 compositeObject
->Add(new wxTextDataObject(text
), false /* not preferred */);
5464 // Add rich text buffer data object. This needs the XML handler to be present.
5466 if (FindHandler(wxRICHTEXT_TYPE_XML
))
5468 wxRichTextBuffer
* richTextBuf
= new wxRichTextBuffer
;
5469 CopyFragment(range
, *richTextBuf
);
5471 compositeObject
->Add(new wxRichTextBufferDataObject(richTextBuf
), true /* preferred */);
5474 if (wxTheClipboard
->SetData(compositeObject
))
5477 wxTheClipboard
->Close();
5486 /// Paste the clipboard content to the buffer
5487 bool wxRichTextBuffer::PasteFromClipboard(long position
)
5489 bool success
= false;
5490 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5491 if (CanPasteFromClipboard())
5493 if (wxTheClipboard
->Open())
5495 if (wxTheClipboard
->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())))
5497 wxRichTextBufferDataObject data
;
5498 wxTheClipboard
->GetData(data
);
5499 wxRichTextBuffer
* richTextBuffer
= data
.GetRichTextBuffer();
5502 InsertParagraphsWithUndo(position
+1, *richTextBuffer
, GetRichTextCtrl(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
);
5503 delete richTextBuffer
;
5506 else if (wxTheClipboard
->IsSupported(wxDF_TEXT
) || wxTheClipboard
->IsSupported(wxDF_UNICODETEXT
))
5508 wxTextDataObject data
;
5509 wxTheClipboard
->GetData(data
);
5510 wxString
text(data
.GetText());
5511 text
.Replace(_T("\r\n"), _T("\n"));
5513 InsertTextWithUndo(position
+1, text
, GetRichTextCtrl());
5517 else if (wxTheClipboard
->IsSupported(wxDF_BITMAP
))
5519 wxBitmapDataObject data
;
5520 wxTheClipboard
->GetData(data
);
5521 wxBitmap
bitmap(data
.GetBitmap());
5522 wxImage
image(bitmap
.ConvertToImage());
5524 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Image"), wxRICHTEXT_INSERT
, this, GetRichTextCtrl(), false);
5526 action
->GetNewParagraphs().AddImage(image
);
5528 if (action
->GetNewParagraphs().GetChildCount() == 1)
5529 action
->GetNewParagraphs().SetPartialParagraph(true);
5531 action
->SetPosition(position
);
5533 // Set the range we'll need to delete in Undo
5534 action
->SetRange(wxRichTextRange(position
, position
));
5536 SubmitAction(action
);
5540 wxTheClipboard
->Close();
5544 wxUnusedVar(position
);
5549 /// Can we paste from the clipboard?
5550 bool wxRichTextBuffer::CanPasteFromClipboard() const
5552 bool canPaste
= false;
5553 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5554 if (!wxTheClipboard
->IsOpened() && wxTheClipboard
->Open())
5556 if (wxTheClipboard
->IsSupported(wxDF_TEXT
) || wxTheClipboard
->IsSupported(wxDF_UNICODETEXT
) ||
5557 wxTheClipboard
->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())) ||
5558 wxTheClipboard
->IsSupported(wxDF_BITMAP
))
5562 wxTheClipboard
->Close();
5568 /// Dumps contents of buffer for debugging purposes
5569 void wxRichTextBuffer::Dump()
5573 wxStringOutputStream
stream(& text
);
5574 wxTextOutputStream
textStream(stream
);
5581 /// Add an event handler
5582 bool wxRichTextBuffer::AddEventHandler(wxEvtHandler
* handler
)
5584 m_eventHandlers
.Append(handler
);
5588 /// Remove an event handler
5589 bool wxRichTextBuffer::RemoveEventHandler(wxEvtHandler
* handler
, bool deleteHandler
)
5591 wxList::compatibility_iterator node
= m_eventHandlers
.Find(handler
);
5594 m_eventHandlers
.Erase(node
);
5604 /// Clear event handlers
5605 void wxRichTextBuffer::ClearEventHandlers()
5607 m_eventHandlers
.Clear();
5610 /// Send event to event handlers. If sendToAll is true, will send to all event handlers,
5611 /// otherwise will stop at the first successful one.
5612 bool wxRichTextBuffer::SendEvent(wxEvent
& event
, bool sendToAll
)
5614 bool success
= false;
5615 for (wxList::compatibility_iterator node
= m_eventHandlers
.GetFirst(); node
; node
= node
->GetNext())
5617 wxEvtHandler
* handler
= (wxEvtHandler
*) node
->GetData();
5618 if (handler
->ProcessEvent(event
))
5628 /// Set style sheet and notify of the change
5629 bool wxRichTextBuffer::SetStyleSheetAndNotify(wxRichTextStyleSheet
* sheet
)
5631 wxRichTextStyleSheet
* oldSheet
= GetStyleSheet();
5633 wxWindowID id
= wxID_ANY
;
5634 if (GetRichTextCtrl())
5635 id
= GetRichTextCtrl()->GetId();
5637 wxRichTextEvent
event(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING
, id
);
5638 event
.SetEventObject(GetRichTextCtrl());
5639 event
.SetOldStyleSheet(oldSheet
);
5640 event
.SetNewStyleSheet(sheet
);
5643 if (SendEvent(event
) && !event
.IsAllowed())
5645 if (sheet
!= oldSheet
)
5651 if (oldSheet
&& oldSheet
!= sheet
)
5654 SetStyleSheet(sheet
);
5656 event
.SetEventType(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED
);
5657 event
.SetOldStyleSheet(NULL
);
5660 return SendEvent(event
);
5663 /// Set renderer, deleting old one
5664 void wxRichTextBuffer::SetRenderer(wxRichTextRenderer
* renderer
)
5668 sm_renderer
= renderer
;
5671 bool wxRichTextStdRenderer::DrawStandardBullet(wxRichTextParagraph
* paragraph
, wxDC
& dc
, const wxTextAttr
& bulletAttr
, const wxRect
& rect
)
5673 if (bulletAttr
.GetTextColour().Ok())
5675 dc
.SetPen(wxPen(bulletAttr
.GetTextColour()));
5676 dc
.SetBrush(wxBrush(bulletAttr
.GetTextColour()));
5680 dc
.SetPen(*wxBLACK_PEN
);
5681 dc
.SetBrush(*wxBLACK_BRUSH
);
5685 if (bulletAttr
.HasFont())
5687 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(bulletAttr
);
5690 font
= (*wxNORMAL_FONT
);
5694 int charHeight
= dc
.GetCharHeight();
5696 int bulletWidth
= (int) (((float) charHeight
) * wxRichTextBuffer::GetBulletProportion());
5697 int bulletHeight
= bulletWidth
;
5701 // Calculate the top position of the character (as opposed to the whole line height)
5702 int y
= rect
.y
+ (rect
.height
- charHeight
);
5704 // Calculate where the bullet should be positioned
5705 y
= y
+ (charHeight
+1)/2 - (bulletHeight
+1)/2;
5707 // The margin between a bullet and text.
5708 int margin
= paragraph
->ConvertTenthsMMToPixels(dc
, wxRichTextBuffer::GetBulletRightMargin());
5710 if (bulletAttr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT
)
5711 x
= rect
.x
+ rect
.width
- bulletWidth
- margin
;
5712 else if (bulletAttr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE
)
5713 x
= x
+ (rect
.width
)/2 - bulletWidth
/2;
5715 if (bulletAttr
.GetBulletName() == wxT("standard/square"))
5717 dc
.DrawRectangle(x
, y
, bulletWidth
, bulletHeight
);
5719 else if (bulletAttr
.GetBulletName() == wxT("standard/diamond"))
5722 pts
[0].x
= x
; pts
[0].y
= y
+ bulletHeight
/2;
5723 pts
[1].x
= x
+ bulletWidth
/2; pts
[1].y
= y
;
5724 pts
[2].x
= x
+ bulletWidth
; pts
[2].y
= y
+ bulletHeight
/2;
5725 pts
[3].x
= x
+ bulletWidth
/2; pts
[3].y
= y
+ bulletHeight
;
5727 dc
.DrawPolygon(4, pts
);
5729 else if (bulletAttr
.GetBulletName() == wxT("standard/triangle"))
5732 pts
[0].x
= x
; pts
[0].y
= y
;
5733 pts
[1].x
= x
+ bulletWidth
; pts
[1].y
= y
+ bulletHeight
/2;
5734 pts
[2].x
= x
; pts
[2].y
= y
+ bulletHeight
;
5736 dc
.DrawPolygon(3, pts
);
5738 else // "standard/circle", and catch-all
5740 dc
.DrawEllipse(x
, y
, bulletWidth
, bulletHeight
);
5746 bool wxRichTextStdRenderer::DrawTextBullet(wxRichTextParagraph
* paragraph
, wxDC
& dc
, const wxTextAttr
& attr
, const wxRect
& rect
, const wxString
& text
)
5751 if ((attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL
) && !attr
.GetBulletFont().IsEmpty() && attr
.HasFont())
5753 wxTextAttr fontAttr
;
5754 fontAttr
.SetFontSize(attr
.GetFontSize());
5755 fontAttr
.SetFontStyle(attr
.GetFontStyle());
5756 fontAttr
.SetFontWeight(attr
.GetFontWeight());
5757 fontAttr
.SetFontUnderlined(attr
.GetFontUnderlined());
5758 fontAttr
.SetFontFaceName(attr
.GetBulletFont());
5759 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(fontAttr
);
5761 else if (attr
.HasFont())
5762 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(attr
);
5764 font
= (*wxNORMAL_FONT
);
5768 if (attr
.GetTextColour().Ok())
5769 dc
.SetTextForeground(attr
.GetTextColour());
5771 dc
.SetBackgroundMode(wxTRANSPARENT
);
5773 int charHeight
= dc
.GetCharHeight();
5775 dc
.GetTextExtent(text
, & tw
, & th
);
5779 // Calculate the top position of the character (as opposed to the whole line height)
5780 int y
= rect
.y
+ (rect
.height
- charHeight
);
5782 // The margin between a bullet and text.
5783 int margin
= paragraph
->ConvertTenthsMMToPixels(dc
, wxRichTextBuffer::GetBulletRightMargin());
5785 if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT
)
5786 x
= (rect
.x
+ rect
.width
) - tw
- margin
;
5787 else if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE
)
5788 x
= x
+ (rect
.width
)/2 - tw
/2;
5790 dc
.DrawText(text
, x
, y
);
5798 bool wxRichTextStdRenderer::DrawBitmapBullet(wxRichTextParagraph
* WXUNUSED(paragraph
), wxDC
& WXUNUSED(dc
), const wxTextAttr
& WXUNUSED(attr
), const wxRect
& WXUNUSED(rect
))
5800 // Currently unimplemented. The intention is to store bitmaps by name in a media store associated
5801 // with the buffer. The store will allow retrieval from memory, disk or other means.
5805 /// Enumerate the standard bullet names currently supported
5806 bool wxRichTextStdRenderer::EnumerateStandardBulletNames(wxArrayString
& bulletNames
)
5808 bulletNames
.Add(wxT("standard/circle"));
5809 bulletNames
.Add(wxT("standard/square"));
5810 bulletNames
.Add(wxT("standard/diamond"));
5811 bulletNames
.Add(wxT("standard/triangle"));
5817 * Module to initialise and clean up handlers
5820 class wxRichTextModule
: public wxModule
5822 DECLARE_DYNAMIC_CLASS(wxRichTextModule
)
5824 wxRichTextModule() {}
5827 wxRichTextBuffer::SetRenderer(new wxRichTextStdRenderer
);
5828 wxRichTextBuffer::InitStandardHandlers();
5829 wxRichTextParagraph::InitDefaultTabs();
5834 wxRichTextBuffer::CleanUpHandlers();
5835 wxRichTextDecimalToRoman(-1);
5836 wxRichTextParagraph::ClearDefaultTabs();
5837 wxRichTextCtrl::ClearAvailableFontNames();
5838 wxRichTextBuffer::SetRenderer(NULL
);
5842 IMPLEMENT_DYNAMIC_CLASS(wxRichTextModule
, wxModule
)
5845 // If the richtext lib is dynamically loaded after the app has already started
5846 // (such as from wxPython) then the built-in module system will not init this
5847 // module. Provide this function to do it manually.
5848 void wxRichTextModuleInit()
5850 wxModule
* module = new wxRichTextModule
;
5852 wxModule::RegisterModule(module);
5857 * Commands for undo/redo
5861 wxRichTextCommand::wxRichTextCommand(const wxString
& name
, wxRichTextCommandId id
, wxRichTextBuffer
* buffer
,
5862 wxRichTextCtrl
* ctrl
, bool ignoreFirstTime
): wxCommand(true, name
)
5864 /* wxRichTextAction* action = */ new wxRichTextAction(this, name
, id
, buffer
, ctrl
, ignoreFirstTime
);
5867 wxRichTextCommand::wxRichTextCommand(const wxString
& name
): wxCommand(true, name
)
5871 wxRichTextCommand::~wxRichTextCommand()
5876 void wxRichTextCommand::AddAction(wxRichTextAction
* action
)
5878 if (!m_actions
.Member(action
))
5879 m_actions
.Append(action
);
5882 bool wxRichTextCommand::Do()
5884 for (wxList::compatibility_iterator node
= m_actions
.GetFirst(); node
; node
= node
->GetNext())
5886 wxRichTextAction
* action
= (wxRichTextAction
*) node
->GetData();
5893 bool wxRichTextCommand::Undo()
5895 for (wxList::compatibility_iterator node
= m_actions
.GetLast(); node
; node
= node
->GetPrevious())
5897 wxRichTextAction
* action
= (wxRichTextAction
*) node
->GetData();
5904 void wxRichTextCommand::ClearActions()
5906 WX_CLEAR_LIST(wxList
, m_actions
);
5914 wxRichTextAction::wxRichTextAction(wxRichTextCommand
* cmd
, const wxString
& name
, wxRichTextCommandId id
, wxRichTextBuffer
* buffer
,
5915 wxRichTextCtrl
* ctrl
, bool ignoreFirstTime
)
5918 m_ignoreThis
= ignoreFirstTime
;
5923 m_newParagraphs
.SetDefaultStyle(buffer
->GetDefaultStyle());
5924 m_newParagraphs
.SetBasicStyle(buffer
->GetBasicStyle());
5926 cmd
->AddAction(this);
5929 wxRichTextAction::~wxRichTextAction()
5933 bool wxRichTextAction::Do()
5935 m_buffer
->Modify(true);
5939 case wxRICHTEXT_INSERT
:
5941 // Store a list of line start character and y positions so we can figure out which area
5942 // we need to refresh
5943 wxArrayInt optimizationLineCharPositions
;
5944 wxArrayInt optimizationLineYPositions
;
5946 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
5947 // NOTE: we're assuming that the buffer is laid out correctly at this point.
5948 // If we had several actions, which only invalidate and leave layout until the
5949 // paint handler is called, then this might not be true. So we may need to switch
5950 // optimisation on only when we're simply adding text and not simultaneously
5951 // deleting a selection, for example. Or, we make sure the buffer is laid out correctly
5952 // first, but of course this means we'll be doing it twice.
5953 if (!m_buffer
->GetDirty() && m_ctrl
) // can only do optimisation if the buffer is already laid out correctly
5955 wxSize clientSize
= m_ctrl
->GetClientSize();
5956 wxPoint firstVisiblePt
= m_ctrl
->GetFirstVisiblePoint();
5957 int lastY
= firstVisiblePt
.y
+ clientSize
.y
;
5959 wxRichTextParagraph
* para
= m_buffer
->GetParagraphAtPosition(GetPosition());
5960 wxRichTextObjectList::compatibility_iterator node
= m_buffer
->GetChildren().Find(para
);
5963 wxRichTextParagraph
* child
= (wxRichTextParagraph
*) node
->GetData();
5964 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
5967 wxRichTextLine
* line
= node2
->GetData();
5968 wxPoint pt
= line
->GetAbsolutePosition();
5969 wxRichTextRange range
= line
->GetAbsoluteRange();
5973 node2
= wxRichTextLineList::compatibility_iterator();
5974 node
= wxRichTextObjectList::compatibility_iterator();
5976 else if (range
.GetStart() > GetPosition() && pt
.y
>= firstVisiblePt
.y
)
5978 optimizationLineCharPositions
.Add(range
.GetStart());
5979 optimizationLineYPositions
.Add(pt
.y
);
5983 node2
= node2
->GetNext();
5987 node
= node
->GetNext();
5992 m_buffer
->InsertFragment(GetPosition(), m_newParagraphs
);
5993 m_buffer
->UpdateRanges();
5994 m_buffer
->Invalidate(GetRange());
5996 long newCaretPosition
= GetPosition() + m_newParagraphs
.GetRange().GetLength();
5998 // Character position to caret position
5999 newCaretPosition
--;
6001 // Don't take into account the last newline
6002 if (m_newParagraphs
.GetPartialParagraph())
6003 newCaretPosition
--;
6005 if (m_newParagraphs
.GetChildren().GetCount() > 1)
6007 wxRichTextObject
* p
= (wxRichTextObject
*) m_newParagraphs
.GetChildren().GetLast()->GetData();
6008 if (p
->GetRange().GetLength() == 1)
6009 newCaretPosition
--;
6012 newCaretPosition
= wxMin(newCaretPosition
, (m_buffer
->GetRange().GetEnd()-1));
6014 if (optimizationLineCharPositions
.GetCount() > 0)
6015 UpdateAppearance(newCaretPosition
, true /* send update event */, & optimizationLineCharPositions
, & optimizationLineYPositions
);
6017 UpdateAppearance(newCaretPosition
, true /* send update event */);
6019 wxRichTextEvent
cmdEvent(
6020 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED
,
6021 m_ctrl
? m_ctrl
->GetId() : -1);
6022 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6023 cmdEvent
.SetRange(GetRange());
6024 cmdEvent
.SetPosition(GetRange().GetStart());
6026 m_buffer
->SendEvent(cmdEvent
);
6030 case wxRICHTEXT_DELETE
:
6032 m_buffer
->DeleteRange(GetRange());
6033 m_buffer
->UpdateRanges();
6034 m_buffer
->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6036 UpdateAppearance(GetRange().GetStart()-1, true /* send update event */);
6038 wxRichTextEvent
cmdEvent(
6039 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED
,
6040 m_ctrl
? m_ctrl
->GetId() : -1);
6041 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6042 cmdEvent
.SetRange(GetRange());
6043 cmdEvent
.SetPosition(GetRange().GetStart());
6045 m_buffer
->SendEvent(cmdEvent
);
6049 case wxRICHTEXT_CHANGE_STYLE
:
6051 ApplyParagraphs(GetNewParagraphs());
6052 m_buffer
->Invalidate(GetRange());
6054 UpdateAppearance(GetPosition());
6056 wxRichTextEvent
cmdEvent(
6057 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED
,
6058 m_ctrl
? m_ctrl
->GetId() : -1);
6059 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6060 cmdEvent
.SetRange(GetRange());
6061 cmdEvent
.SetPosition(GetRange().GetStart());
6063 m_buffer
->SendEvent(cmdEvent
);
6074 bool wxRichTextAction::Undo()
6076 m_buffer
->Modify(true);
6080 case wxRICHTEXT_INSERT
:
6082 m_buffer
->DeleteRange(GetRange());
6083 m_buffer
->UpdateRanges();
6084 m_buffer
->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6086 long newCaretPosition
= GetPosition() - 1;
6088 UpdateAppearance(newCaretPosition
, true /* send update event */);
6090 wxRichTextEvent
cmdEvent(
6091 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED
,
6092 m_ctrl
? m_ctrl
->GetId() : -1);
6093 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6094 cmdEvent
.SetRange(GetRange());
6095 cmdEvent
.SetPosition(GetRange().GetStart());
6097 m_buffer
->SendEvent(cmdEvent
);
6101 case wxRICHTEXT_DELETE
:
6103 m_buffer
->InsertFragment(GetRange().GetStart(), m_oldParagraphs
);
6104 m_buffer
->UpdateRanges();
6105 m_buffer
->Invalidate(GetRange());
6107 UpdateAppearance(GetPosition(), true /* send update event */);
6109 wxRichTextEvent
cmdEvent(
6110 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED
,
6111 m_ctrl
? m_ctrl
->GetId() : -1);
6112 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6113 cmdEvent
.SetRange(GetRange());
6114 cmdEvent
.SetPosition(GetRange().GetStart());
6116 m_buffer
->SendEvent(cmdEvent
);
6120 case wxRICHTEXT_CHANGE_STYLE
:
6122 ApplyParagraphs(GetOldParagraphs());
6123 m_buffer
->Invalidate(GetRange());
6125 UpdateAppearance(GetPosition());
6127 wxRichTextEvent
cmdEvent(
6128 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED
,
6129 m_ctrl
? m_ctrl
->GetId() : -1);
6130 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6131 cmdEvent
.SetRange(GetRange());
6132 cmdEvent
.SetPosition(GetRange().GetStart());
6134 m_buffer
->SendEvent(cmdEvent
);
6145 /// Update the control appearance
6146 void wxRichTextAction::UpdateAppearance(long caretPosition
, bool sendUpdateEvent
, wxArrayInt
* optimizationLineCharPositions
, wxArrayInt
* optimizationLineYPositions
)
6150 m_ctrl
->SetCaretPosition(caretPosition
);
6151 if (!m_ctrl
->IsFrozen())
6153 m_ctrl
->LayoutContent();
6154 m_ctrl
->PositionCaret();
6156 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6157 // Find refresh rectangle if we are in a position to optimise refresh
6158 if (m_cmdId
== wxRICHTEXT_INSERT
&& optimizationLineCharPositions
&& optimizationLineCharPositions
->GetCount() > 0)
6162 wxSize clientSize
= m_ctrl
->GetClientSize();
6163 wxPoint firstVisiblePt
= m_ctrl
->GetFirstVisiblePoint();
6165 // Start/end positions
6167 int lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6169 bool foundStart
= false;
6170 bool foundEnd
= false;
6172 // position offset - how many characters were inserted
6173 int positionOffset
= GetRange().GetLength();
6175 // find the first line which is being drawn at the same position as it was
6176 // before. Since we're talking about a simple insertion, we can assume
6177 // that the rest of the window does not need to be redrawn.
6179 wxRichTextParagraph
* para
= m_buffer
->GetParagraphAtPosition(GetPosition());
6180 wxRichTextObjectList::compatibility_iterator node
= m_buffer
->GetChildren().Find(para
);
6183 wxRichTextParagraph
* child
= (wxRichTextParagraph
*) node
->GetData();
6184 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
6187 wxRichTextLine
* line
= node2
->GetData();
6188 wxPoint pt
= line
->GetAbsolutePosition();
6189 wxRichTextRange range
= line
->GetAbsoluteRange();
6191 // we want to find the first line that is in the same position
6192 // as before. This will mean we're at the end of the changed text.
6194 if (pt
.y
> lastY
) // going past the end of the window, no more info
6196 node2
= wxRichTextLineList::compatibility_iterator();
6197 node
= wxRichTextObjectList::compatibility_iterator();
6203 firstY
= pt
.y
- firstVisiblePt
.y
;
6207 // search for this line being at the same position as before
6208 for (i
= 0; i
< optimizationLineCharPositions
->GetCount(); i
++)
6210 if (((*optimizationLineCharPositions
)[i
] + positionOffset
== range
.GetStart()) &&
6211 ((*optimizationLineYPositions
)[i
] == pt
.y
))
6213 // Stop, we're now the same as we were
6215 lastY
= pt
.y
- firstVisiblePt
.y
;
6217 node2
= wxRichTextLineList::compatibility_iterator();
6218 node
= wxRichTextObjectList::compatibility_iterator();
6226 node2
= node2
->GetNext();
6230 node
= node
->GetNext();
6234 firstY
= firstVisiblePt
.y
;
6236 lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6238 wxRect
rect(firstVisiblePt
.x
, firstY
, firstVisiblePt
.x
+ clientSize
.x
, lastY
- firstY
);
6239 m_ctrl
->RefreshRect(rect
);
6241 // TODO: we need to make sure that lines are only drawn if in the update region. The rect
6242 // passed to Draw is currently used in different ways (to pass the position the content should
6243 // be drawn at as well as the relevant region).
6247 m_ctrl
->Refresh(false);
6249 if (sendUpdateEvent
)
6250 wxTextCtrl::SendTextUpdatedEvent(m_ctrl
);
6255 /// Replace the buffer paragraphs with the new ones.
6256 void wxRichTextAction::ApplyParagraphs(const wxRichTextParagraphLayoutBox
& fragment
)
6258 wxRichTextObjectList::compatibility_iterator node
= fragment
.GetChildren().GetFirst();
6261 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
6262 wxASSERT (para
!= NULL
);
6264 // We'll replace the existing paragraph by finding the paragraph at this position,
6265 // delete its node data, and setting a copy as the new node data.
6266 // TODO: make more efficient by simply swapping old and new paragraph objects.
6268 wxRichTextParagraph
* existingPara
= m_buffer
->GetParagraphAtPosition(para
->GetRange().GetStart());
6271 wxRichTextObjectList::compatibility_iterator bufferParaNode
= m_buffer
->GetChildren().Find(existingPara
);
6274 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(*para
);
6275 newPara
->SetParent(m_buffer
);
6277 bufferParaNode
->SetData(newPara
);
6279 delete existingPara
;
6283 node
= node
->GetNext();
6290 * This stores beginning and end positions for a range of data.
6293 /// Limit this range to be within 'range'
6294 bool wxRichTextRange::LimitTo(const wxRichTextRange
& range
)
6296 if (m_start
< range
.m_start
)
6297 m_start
= range
.m_start
;
6299 if (m_end
> range
.m_end
)
6300 m_end
= range
.m_end
;
6306 * wxRichTextImage implementation
6307 * This object represents an image.
6310 IMPLEMENT_DYNAMIC_CLASS(wxRichTextImage
, wxRichTextObject
)
6312 wxRichTextImage::wxRichTextImage(const wxImage
& image
, wxRichTextObject
* parent
, wxTextAttr
* charStyle
):
6313 wxRichTextObject(parent
)
6317 SetAttributes(*charStyle
);
6320 wxRichTextImage::wxRichTextImage(const wxRichTextImageBlock
& imageBlock
, wxRichTextObject
* parent
, wxTextAttr
* charStyle
):
6321 wxRichTextObject(parent
)
6323 m_imageBlock
= imageBlock
;
6324 m_imageBlock
.Load(m_image
);
6326 SetAttributes(*charStyle
);
6329 /// Load wxImage from the block
6330 bool wxRichTextImage::LoadFromBlock()
6332 m_imageBlock
.Load(m_image
);
6333 return m_imageBlock
.Ok();
6336 /// Make block from the wxImage
6337 bool wxRichTextImage::MakeBlock()
6339 if (m_imageBlock
.GetImageType() == wxBITMAP_TYPE_ANY
|| m_imageBlock
.GetImageType() == -1)
6340 m_imageBlock
.SetImageType(wxBITMAP_TYPE_PNG
);
6342 m_imageBlock
.MakeImageBlock(m_image
, m_imageBlock
.GetImageType());
6343 return m_imageBlock
.Ok();
6348 bool wxRichTextImage::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int WXUNUSED(descent
), int WXUNUSED(style
))
6350 if (!m_image
.Ok() && m_imageBlock
.Ok())
6356 if (m_image
.Ok() && !m_bitmap
.Ok())
6357 m_bitmap
= wxBitmap(m_image
);
6359 int y
= rect
.y
+ (rect
.height
- m_image
.GetHeight());
6362 dc
.DrawBitmap(m_bitmap
, rect
.x
, y
, true);
6364 if (selectionRange
.Contains(range
.GetStart()))
6366 dc
.SetBrush(*wxBLACK_BRUSH
);
6367 dc
.SetPen(*wxBLACK_PEN
);
6368 dc
.SetLogicalFunction(wxINVERT
);
6369 dc
.DrawRectangle(rect
);
6370 dc
.SetLogicalFunction(wxCOPY
);
6376 /// Lay the item out
6377 bool wxRichTextImage::Layout(wxDC
& WXUNUSED(dc
), const wxRect
& rect
, int WXUNUSED(style
))
6384 SetCachedSize(wxSize(m_image
.GetWidth(), m_image
.GetHeight()));
6385 SetPosition(rect
.GetPosition());
6391 /// Get/set the object size for the given range. Returns false if the range
6392 /// is invalid for this object.
6393 bool wxRichTextImage::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& WXUNUSED(descent
), wxDC
& WXUNUSED(dc
), int WXUNUSED(flags
), wxPoint
WXUNUSED(position
)) const
6395 if (!range
.IsWithin(GetRange()))
6401 size
.x
= m_image
.GetWidth();
6402 size
.y
= m_image
.GetHeight();
6408 void wxRichTextImage::Copy(const wxRichTextImage
& obj
)
6410 wxRichTextObject::Copy(obj
);
6412 m_image
= obj
.m_image
;
6413 m_imageBlock
= obj
.m_imageBlock
;
6421 /// Compare two attribute objects
6422 bool wxTextAttrEq(const wxTextAttr
& attr1
, const wxTextAttr
& attr2
)
6424 return (attr1
== attr2
);
6427 // Partial equality test taking flags into account
6428 bool wxTextAttrEqPartial(const wxTextAttr
& attr1
, const wxTextAttr
& attr2
, int flags
)
6430 return attr1
.EqPartial(attr2
, flags
);
6434 bool wxRichTextTabsEq(const wxArrayInt
& tabs1
, const wxArrayInt
& tabs2
)
6436 if (tabs1
.GetCount() != tabs2
.GetCount())
6440 for (i
= 0; i
< tabs1
.GetCount(); i
++)
6442 if (tabs1
[i
] != tabs2
[i
])
6448 bool wxRichTextApplyStyle(wxTextAttr
& destStyle
, const wxTextAttr
& style
, wxTextAttr
* compareWith
)
6450 return destStyle
.Apply(style
, compareWith
);
6453 // Remove attributes
6454 bool wxRichTextRemoveStyle(wxTextAttr
& destStyle
, const wxTextAttr
& style
)
6456 return wxTextAttr::RemoveStyle(destStyle
, style
);
6459 /// Combine two bitlists, specifying the bits of interest with separate flags.
6460 bool wxRichTextCombineBitlists(int& valueA
, int valueB
, int& flagsA
, int flagsB
)
6462 return wxTextAttr::CombineBitlists(valueA
, valueB
, flagsA
, flagsB
);
6465 /// Compare two bitlists
6466 bool wxRichTextBitlistsEqPartial(int valueA
, int valueB
, int flags
)
6468 return wxTextAttr::BitlistsEqPartial(valueA
, valueB
, flags
);
6471 /// Split into paragraph and character styles
6472 bool wxRichTextSplitParaCharStyles(const wxTextAttr
& style
, wxTextAttr
& parStyle
, wxTextAttr
& charStyle
)
6474 return wxTextAttr::SplitParaCharStyles(style
, parStyle
, charStyle
);
6477 /// Convert a decimal to Roman numerals
6478 wxString
wxRichTextDecimalToRoman(long n
)
6480 static wxArrayInt decimalNumbers
;
6481 static wxArrayString romanNumbers
;
6486 decimalNumbers
.Clear();
6487 romanNumbers
.Clear();
6488 return wxEmptyString
;
6491 if (decimalNumbers
.GetCount() == 0)
6493 #define wxRichTextAddDecRom(n, r) decimalNumbers.Add(n); romanNumbers.Add(r);
6495 wxRichTextAddDecRom(1000, wxT("M"));
6496 wxRichTextAddDecRom(900, wxT("CM"));
6497 wxRichTextAddDecRom(500, wxT("D"));
6498 wxRichTextAddDecRom(400, wxT("CD"));
6499 wxRichTextAddDecRom(100, wxT("C"));
6500 wxRichTextAddDecRom(90, wxT("XC"));
6501 wxRichTextAddDecRom(50, wxT("L"));
6502 wxRichTextAddDecRom(40, wxT("XL"));
6503 wxRichTextAddDecRom(10, wxT("X"));
6504 wxRichTextAddDecRom(9, wxT("IX"));
6505 wxRichTextAddDecRom(5, wxT("V"));
6506 wxRichTextAddDecRom(4, wxT("IV"));
6507 wxRichTextAddDecRom(1, wxT("I"));
6513 while (n
> 0 && i
< 13)
6515 if (n
>= decimalNumbers
[i
])
6517 n
-= decimalNumbers
[i
];
6518 roman
+= romanNumbers
[i
];
6525 if (roman
.IsEmpty())
6531 * wxRichTextFileHandler
6532 * Base class for file handlers
6535 IMPLEMENT_CLASS(wxRichTextFileHandler
, wxObject
)
6537 #if wxUSE_FFILE && wxUSE_STREAMS
6538 bool wxRichTextFileHandler::LoadFile(wxRichTextBuffer
*buffer
, const wxString
& filename
)
6540 wxFFileInputStream
stream(filename
);
6542 return LoadFile(buffer
, stream
);
6547 bool wxRichTextFileHandler::SaveFile(wxRichTextBuffer
*buffer
, const wxString
& filename
)
6549 wxFFileOutputStream
stream(filename
);
6551 return SaveFile(buffer
, stream
);
6555 #endif // wxUSE_FFILE && wxUSE_STREAMS
6557 /// Can we handle this filename (if using files)? By default, checks the extension.
6558 bool wxRichTextFileHandler::CanHandle(const wxString
& filename
) const
6560 wxString path
, file
, ext
;
6561 wxSplitPath(filename
, & path
, & file
, & ext
);
6563 return (ext
.Lower() == GetExtension());
6567 * wxRichTextTextHandler
6568 * Plain text handler
6571 IMPLEMENT_CLASS(wxRichTextPlainTextHandler
, wxRichTextFileHandler
)
6574 bool wxRichTextPlainTextHandler::DoLoadFile(wxRichTextBuffer
*buffer
, wxInputStream
& stream
)
6582 while (!stream
.Eof())
6584 int ch
= stream
.GetC();
6588 if (ch
== 10 && lastCh
!= 13)
6591 if (ch
> 0 && ch
!= 10)
6598 buffer
->ResetAndClearCommands();
6600 buffer
->AddParagraphs(str
);
6601 buffer
->UpdateRanges();
6606 bool wxRichTextPlainTextHandler::DoSaveFile(wxRichTextBuffer
*buffer
, wxOutputStream
& stream
)
6611 wxString text
= buffer
->GetText();
6613 wxString newLine
= wxRichTextLineBreakChar
;
6614 text
.Replace(newLine
, wxT("\n"));
6616 wxCharBuffer buf
= text
.ToAscii();
6618 stream
.Write((const char*) buf
, text
.length());
6621 #endif // wxUSE_STREAMS
6624 * Stores information about an image, in binary in-memory form
6627 wxRichTextImageBlock::wxRichTextImageBlock()
6632 wxRichTextImageBlock::wxRichTextImageBlock(const wxRichTextImageBlock
& block
):wxObject()
6638 wxRichTextImageBlock::~wxRichTextImageBlock()
6647 void wxRichTextImageBlock::Init()
6654 void wxRichTextImageBlock::Clear()
6663 // Load the original image into a memory block.
6664 // If the image is not a JPEG, we must convert it into a JPEG
6665 // to conserve space.
6666 // If it's not a JPEG we can make use of 'image', already scaled, so we don't have to
6667 // load the image a 2nd time.
6669 bool wxRichTextImageBlock::MakeImageBlock(const wxString
& filename
, int imageType
, wxImage
& image
, bool convertToJPEG
)
6671 m_imageType
= imageType
;
6673 wxString
filenameToRead(filename
);
6674 bool removeFile
= false;
6676 if (imageType
== -1)
6677 return false; // Could not determine image type
6679 if ((imageType
!= wxBITMAP_TYPE_JPEG
) && convertToJPEG
)
6682 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
6686 wxUnusedVar(success
);
6688 image
.SaveFile(tempFile
, wxBITMAP_TYPE_JPEG
);
6689 filenameToRead
= tempFile
;
6692 m_imageType
= wxBITMAP_TYPE_JPEG
;
6695 if (!file
.Open(filenameToRead
))
6698 m_dataSize
= (size_t) file
.Length();
6703 m_data
= ReadBlock(filenameToRead
, m_dataSize
);
6706 wxRemoveFile(filenameToRead
);
6708 return (m_data
!= NULL
);
6711 // Make an image block from the wxImage in the given
6713 bool wxRichTextImageBlock::MakeImageBlock(wxImage
& image
, int imageType
, int quality
)
6715 m_imageType
= imageType
;
6716 image
.SetOption(wxT("quality"), quality
);
6718 if (imageType
== -1)
6719 return false; // Could not determine image type
6722 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
6725 wxUnusedVar(success
);
6727 if (!image
.SaveFile(tempFile
, m_imageType
))
6729 if (wxFileExists(tempFile
))
6730 wxRemoveFile(tempFile
);
6735 if (!file
.Open(tempFile
))
6738 m_dataSize
= (size_t) file
.Length();
6743 m_data
= ReadBlock(tempFile
, m_dataSize
);
6745 wxRemoveFile(tempFile
);
6747 return (m_data
!= NULL
);
6752 bool wxRichTextImageBlock::Write(const wxString
& filename
)
6754 return WriteBlock(filename
, m_data
, m_dataSize
);
6757 void wxRichTextImageBlock::Copy(const wxRichTextImageBlock
& block
)
6759 m_imageType
= block
.m_imageType
;
6765 m_dataSize
= block
.m_dataSize
;
6766 if (m_dataSize
== 0)
6769 m_data
= new unsigned char[m_dataSize
];
6771 for (i
= 0; i
< m_dataSize
; i
++)
6772 m_data
[i
] = block
.m_data
[i
];
6776 void wxRichTextImageBlock::operator=(const wxRichTextImageBlock
& block
)
6781 // Load a wxImage from the block
6782 bool wxRichTextImageBlock::Load(wxImage
& image
)
6787 // Read in the image.
6789 wxMemoryInputStream
mstream(m_data
, m_dataSize
);
6790 bool success
= image
.LoadFile(mstream
, GetImageType());
6793 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
6796 if (!WriteBlock(tempFile
, m_data
, m_dataSize
))
6800 success
= image
.LoadFile(tempFile
, GetImageType());
6801 wxRemoveFile(tempFile
);
6807 // Write data in hex to a stream
6808 bool wxRichTextImageBlock::WriteHex(wxOutputStream
& stream
)
6810 const int bufSize
= 512;
6811 char buf
[bufSize
+1];
6813 int left
= m_dataSize
;
6818 if (left
*2 > bufSize
)
6820 n
= bufSize
; left
-= (bufSize
/2);
6824 n
= left
*2; left
= 0;
6828 for (i
= 0; i
< (n
/2); i
++)
6830 wxDecToHex(m_data
[j
], b
, b
+1);
6835 stream
.Write((const char*) buf
, n
);
6840 // Read data in hex from a stream
6841 bool wxRichTextImageBlock::ReadHex(wxInputStream
& stream
, int length
, int imageType
)
6843 int dataSize
= length
/2;
6849 m_data
= new unsigned char[dataSize
];
6851 for (i
= 0; i
< dataSize
; i
++)
6853 str
[0] = (char)stream
.GetC();
6854 str
[1] = (char)stream
.GetC();
6856 m_data
[i
] = (unsigned char)wxHexToDec(str
);
6859 m_dataSize
= dataSize
;
6860 m_imageType
= imageType
;
6865 // Allocate and read from stream as a block of memory
6866 unsigned char* wxRichTextImageBlock::ReadBlock(wxInputStream
& stream
, size_t size
)
6868 unsigned char* block
= new unsigned char[size
];
6872 stream
.Read(block
, size
);
6877 unsigned char* wxRichTextImageBlock::ReadBlock(const wxString
& filename
, size_t size
)
6879 wxFileInputStream
stream(filename
);
6883 return ReadBlock(stream
, size
);
6886 // Write memory block to stream
6887 bool wxRichTextImageBlock::WriteBlock(wxOutputStream
& stream
, unsigned char* block
, size_t size
)
6889 stream
.Write((void*) block
, size
);
6890 return stream
.IsOk();
6894 // Write memory block to file
6895 bool wxRichTextImageBlock::WriteBlock(const wxString
& filename
, unsigned char* block
, size_t size
)
6897 wxFileOutputStream
outStream(filename
);
6898 if (!outStream
.Ok())
6901 return WriteBlock(outStream
, block
, size
);
6904 // Gets the extension for the block's type
6905 wxString
wxRichTextImageBlock::GetExtension() const
6907 wxImageHandler
* handler
= wxImage::FindHandler(GetImageType());
6909 return handler
->GetExtension();
6911 return wxEmptyString
;
6917 * The data object for a wxRichTextBuffer
6920 const wxChar
*wxRichTextBufferDataObject::ms_richTextBufferFormatId
= wxT("wxShape");
6922 wxRichTextBufferDataObject::wxRichTextBufferDataObject(wxRichTextBuffer
* richTextBuffer
)
6924 m_richTextBuffer
= richTextBuffer
;
6926 // this string should uniquely identify our format, but is otherwise
6928 m_formatRichTextBuffer
.SetId(GetRichTextBufferFormatId());
6930 SetFormat(m_formatRichTextBuffer
);
6933 wxRichTextBufferDataObject::~wxRichTextBufferDataObject()
6935 delete m_richTextBuffer
;
6938 // after a call to this function, the richTextBuffer is owned by the caller and it
6939 // is responsible for deleting it!
6940 wxRichTextBuffer
* wxRichTextBufferDataObject::GetRichTextBuffer()
6942 wxRichTextBuffer
* richTextBuffer
= m_richTextBuffer
;
6943 m_richTextBuffer
= NULL
;
6945 return richTextBuffer
;
6948 wxDataFormat
wxRichTextBufferDataObject::GetPreferredFormat(Direction
WXUNUSED(dir
)) const
6950 return m_formatRichTextBuffer
;
6953 size_t wxRichTextBufferDataObject::GetDataSize() const
6955 if (!m_richTextBuffer
)
6961 wxStringOutputStream
stream(& bufXML
);
6962 if (!m_richTextBuffer
->SaveFile(stream
, wxRICHTEXT_TYPE_XML
))
6964 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
6970 wxCharBuffer buffer
= bufXML
.mb_str(wxConvUTF8
);
6971 return strlen(buffer
) + 1;
6973 return bufXML
.Length()+1;
6977 bool wxRichTextBufferDataObject::GetDataHere(void *pBuf
) const
6979 if (!pBuf
|| !m_richTextBuffer
)
6985 wxStringOutputStream
stream(& bufXML
);
6986 if (!m_richTextBuffer
->SaveFile(stream
, wxRICHTEXT_TYPE_XML
))
6988 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
6994 wxCharBuffer buffer
= bufXML
.mb_str(wxConvUTF8
);
6995 size_t len
= strlen(buffer
);
6996 memcpy((char*) pBuf
, (const char*) buffer
, len
);
6997 ((char*) pBuf
)[len
] = 0;
6999 size_t len
= bufXML
.Length();
7000 memcpy((char*) pBuf
, (const char*) bufXML
.c_str(), len
);
7001 ((char*) pBuf
)[len
] = 0;
7007 bool wxRichTextBufferDataObject::SetData(size_t WXUNUSED(len
), const void *buf
)
7009 delete m_richTextBuffer
;
7010 m_richTextBuffer
= NULL
;
7012 wxString
bufXML((const char*) buf
, wxConvUTF8
);
7014 m_richTextBuffer
= new wxRichTextBuffer
;
7016 wxStringInputStream
stream(bufXML
);
7017 if (!m_richTextBuffer
->LoadFile(stream
, wxRICHTEXT_TYPE_XML
))
7019 wxLogError(wxT("Could not read the buffer from an XML stream.\nYou may have forgotten to add the XML file handler."));
7021 delete m_richTextBuffer
;
7022 m_richTextBuffer
= NULL
;
7034 * wxRichTextFontTable
7035 * Manages quick access to a pool of fonts for rendering rich text
7038 WX_DECLARE_EXPORTED_STRING_HASH_MAP(wxFont
, wxRichTextFontTableHashMap
);
7040 class wxRichTextFontTableData
: public wxObjectRefData
7043 wxRichTextFontTableData() {}
7045 wxFont
FindFont(const wxTextAttr
& fontSpec
);
7047 wxRichTextFontTableHashMap m_hashMap
;
7050 wxFont
wxRichTextFontTableData::FindFont(const wxTextAttr
& fontSpec
)
7052 wxString
facename(fontSpec
.GetFontFaceName());
7053 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()));
7054 wxRichTextFontTableHashMap::iterator entry
= m_hashMap
.find(spec
);
7056 if ( entry
== m_hashMap
.end() )
7058 wxFont
font(fontSpec
.GetFontSize(), wxDEFAULT
, fontSpec
.GetFontStyle(), fontSpec
.GetFontWeight(), fontSpec
.GetFontUnderlined(), facename
.c_str());
7059 m_hashMap
[spec
] = font
;
7064 return entry
->second
;
7068 IMPLEMENT_DYNAMIC_CLASS(wxRichTextFontTable
, wxObject
)
7070 wxRichTextFontTable::wxRichTextFontTable()
7072 m_refData
= new wxRichTextFontTableData
;
7073 m_refData
->IncRef();
7076 wxRichTextFontTable::wxRichTextFontTable(const wxRichTextFontTable
& table
)
7081 wxRichTextFontTable::~wxRichTextFontTable()
7086 bool wxRichTextFontTable::operator == (const wxRichTextFontTable
& table
) const
7088 return (m_refData
== table
.m_refData
);
7091 void wxRichTextFontTable::operator= (const wxRichTextFontTable
& table
)
7096 wxFont
wxRichTextFontTable::FindFont(const wxTextAttr
& fontSpec
)
7098 wxRichTextFontTableData
* data
= (wxRichTextFontTableData
*) m_refData
;
7100 return data
->FindFont(fontSpec
);
7105 void wxRichTextFontTable::Clear()
7107 wxRichTextFontTableData
* data
= (wxRichTextFontTableData
*) m_refData
;
7109 data
->m_hashMap
.clear();