1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/richtext/richtextbuffer.cpp
3 // Purpose: Buffer for wxRichTextCtrl
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // For compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
21 #include "wx/richtext/richtextbuffer.h"
27 #include "wx/dataobj.h"
28 #include "wx/module.h"
31 #include "wx/settings.h"
32 #include "wx/filename.h"
33 #include "wx/clipbrd.h"
34 #include "wx/wfstream.h"
35 #include "wx/mstream.h"
36 #include "wx/sstream.h"
37 #include "wx/textfile.h"
38 #include "wx/hashmap.h"
40 #include "wx/richtext/richtextctrl.h"
41 #include "wx/richtext/richtextstyles.h"
43 #include "wx/listimpl.cpp"
45 WX_DEFINE_LIST(wxRichTextObjectList
)
46 WX_DEFINE_LIST(wxRichTextLineList
)
48 // Switch off if the platform doesn't like it for some reason
49 #define wxRICHTEXT_USE_OPTIMIZED_DRAWING 1
51 const wxChar wxRichTextLineBreakChar
= (wxChar
) 29;
53 // Helpers for efficiency
55 inline void wxCheckSetFont(wxDC
& dc
, const wxFont
& font
)
57 const wxFont
& font1
= dc
.GetFont();
58 if (font1
.IsOk() && font
.IsOk())
60 if (font1
.GetPointSize() == font
.GetPointSize() &&
61 font1
.GetFamily() == font
.GetFamily() &&
62 font1
.GetStyle() == font
.GetStyle() &&
63 font1
.GetWeight() == font
.GetWeight() &&
64 font1
.GetFaceName() == font
.GetFaceName())
70 inline void wxCheckSetPen(wxDC
& dc
, const wxPen
& pen
)
72 const wxPen
& pen1
= dc
.GetPen();
73 if (pen1
.IsOk() && pen
.IsOk())
75 if (pen1
.GetWidth() == pen
.GetWidth() &&
76 pen1
.GetStyle() == pen
.GetStyle() &&
77 pen1
.GetColour() == pen
.GetColour())
83 inline void wxCheckSetBrush(wxDC
& dc
, const wxBrush
& brush
)
85 const wxBrush
& brush1
= dc
.GetBrush();
86 if (brush1
.IsOk() && brush
.IsOk())
88 if (brush1
.GetStyle() == brush
.GetStyle() &&
89 brush1
.GetColour() == brush
.GetColour())
97 * This is the base for drawable objects.
100 IMPLEMENT_CLASS(wxRichTextObject
, wxObject
)
102 wxRichTextObject::wxRichTextObject(wxRichTextObject
* parent
)
114 wxRichTextObject::~wxRichTextObject()
118 void wxRichTextObject::Dereference()
126 void wxRichTextObject::Copy(const wxRichTextObject
& obj
)
130 m_dirty
= obj
.m_dirty
;
131 m_range
= obj
.m_range
;
132 m_attributes
= obj
.m_attributes
;
133 m_descent
= obj
.m_descent
;
136 void wxRichTextObject::SetMargins(int margin
)
138 m_leftMargin
= m_rightMargin
= m_topMargin
= m_bottomMargin
= margin
;
141 void wxRichTextObject::SetMargins(int leftMargin
, int rightMargin
, int topMargin
, int bottomMargin
)
143 m_leftMargin
= leftMargin
;
144 m_rightMargin
= rightMargin
;
145 m_topMargin
= topMargin
;
146 m_bottomMargin
= bottomMargin
;
149 // Convert units in tenths of a millimetre to device units
150 int wxRichTextObject::ConvertTenthsMMToPixels(wxDC
& dc
, int units
)
152 int p
= ConvertTenthsMMToPixels(dc
.GetPPI().x
, units
);
155 wxRichTextBuffer
* buffer
= GetBuffer();
157 p
= (int) ((double)p
/ buffer
->GetScale());
161 // Convert units in tenths of a millimetre to device units
162 int wxRichTextObject::ConvertTenthsMMToPixels(int ppi
, int units
)
164 // There are ppi pixels in 254.1 "1/10 mm"
166 double pixels
= ((double) units
* (double)ppi
) / 254.1;
171 /// Dump to output stream for debugging
172 void wxRichTextObject::Dump(wxTextOutputStream
& stream
)
174 stream
<< GetClassInfo()->GetClassName() << wxT("\n");
175 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");
176 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");
179 /// Gets the containing buffer
180 wxRichTextBuffer
* wxRichTextObject::GetBuffer() const
182 const wxRichTextObject
* obj
= this;
183 while (obj
&& !obj
->IsKindOf(CLASSINFO(wxRichTextBuffer
)))
184 obj
= obj
->GetParent();
185 return wxDynamicCast(obj
, wxRichTextBuffer
);
189 * wxRichTextCompositeObject
190 * This is the base for drawable objects.
193 IMPLEMENT_CLASS(wxRichTextCompositeObject
, wxRichTextObject
)
195 wxRichTextCompositeObject::wxRichTextCompositeObject(wxRichTextObject
* parent
):
196 wxRichTextObject(parent
)
200 wxRichTextCompositeObject::~wxRichTextCompositeObject()
205 /// Get the nth child
206 wxRichTextObject
* wxRichTextCompositeObject::GetChild(size_t n
) const
208 wxASSERT ( n
< m_children
.GetCount() );
210 return m_children
.Item(n
)->GetData();
213 /// Append a child, returning the position
214 size_t wxRichTextCompositeObject::AppendChild(wxRichTextObject
* child
)
216 m_children
.Append(child
);
217 child
->SetParent(this);
218 return m_children
.GetCount() - 1;
221 /// Insert the child in front of the given object, or at the beginning
222 bool wxRichTextCompositeObject::InsertChild(wxRichTextObject
* child
, wxRichTextObject
* inFrontOf
)
226 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(inFrontOf
);
227 m_children
.Insert(node
, child
);
230 m_children
.Insert(child
);
231 child
->SetParent(this);
237 bool wxRichTextCompositeObject::RemoveChild(wxRichTextObject
* child
, bool deleteChild
)
239 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(child
);
242 wxRichTextObject
* obj
= node
->GetData();
243 m_children
.Erase(node
);
252 /// Delete all children
253 bool wxRichTextCompositeObject::DeleteChildren()
255 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
258 wxRichTextObjectList::compatibility_iterator oldNode
= node
;
260 wxRichTextObject
* child
= node
->GetData();
261 child
->Dereference(); // Only delete if reference count is zero
263 node
= node
->GetNext();
264 m_children
.Erase(oldNode
);
270 /// Get the child count
271 size_t wxRichTextCompositeObject::GetChildCount() const
273 return m_children
.GetCount();
277 void wxRichTextCompositeObject::Copy(const wxRichTextCompositeObject
& obj
)
279 wxRichTextObject::Copy(obj
);
283 wxRichTextObjectList::compatibility_iterator node
= obj
.m_children
.GetFirst();
286 wxRichTextObject
* child
= node
->GetData();
287 wxRichTextObject
* newChild
= child
->Clone();
288 newChild
->SetParent(this);
289 m_children
.Append(newChild
);
291 node
= node
->GetNext();
295 /// Hit-testing: returns a flag indicating hit test details, plus
296 /// information about position
297 int wxRichTextCompositeObject::HitTest(wxDC
& dc
, const wxPoint
& pt
, long& textPosition
)
299 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
302 wxRichTextObject
* child
= node
->GetData();
304 int ret
= child
->HitTest(dc
, pt
, textPosition
);
305 if (ret
!= wxRICHTEXT_HITTEST_NONE
)
308 node
= node
->GetNext();
311 return wxRICHTEXT_HITTEST_NONE
;
314 /// Finds the absolute position and row height for the given character position
315 bool wxRichTextCompositeObject::FindPosition(wxDC
& dc
, long index
, wxPoint
& pt
, int* height
, bool forceLineStart
)
317 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
320 wxRichTextObject
* child
= node
->GetData();
322 if (child
->FindPosition(dc
, index
, pt
, height
, forceLineStart
))
325 node
= node
->GetNext();
332 void wxRichTextCompositeObject::CalculateRange(long start
, long& end
)
334 long current
= start
;
335 long lastEnd
= current
;
337 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
340 wxRichTextObject
* child
= node
->GetData();
343 child
->CalculateRange(current
, childEnd
);
346 current
= childEnd
+ 1;
348 node
= node
->GetNext();
353 // An object with no children has zero length
354 if (m_children
.GetCount() == 0)
357 m_range
.SetRange(start
, end
);
360 /// Delete range from layout.
361 bool wxRichTextCompositeObject::DeleteRange(const wxRichTextRange
& range
)
363 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
367 wxRichTextObject
* obj
= (wxRichTextObject
*) node
->GetData();
368 wxRichTextObjectList::compatibility_iterator next
= node
->GetNext();
370 // Delete the range in each paragraph
372 // When a chunk has been deleted, internally the content does not
373 // now match the ranges.
374 // However, so long as deletion is not done on the same object twice this is OK.
375 // If you may delete content from the same object twice, recalculate
376 // the ranges inbetween DeleteRange calls by calling CalculateRanges, and
377 // adjust the range you're deleting accordingly.
379 if (!obj
->GetRange().IsOutside(range
))
381 obj
->DeleteRange(range
);
383 // Delete an empty object, or paragraph within this range.
384 if (obj
->IsEmpty() ||
385 (range
.GetStart() <= obj
->GetRange().GetStart() && range
.GetEnd() >= obj
->GetRange().GetEnd()))
387 // An empty paragraph has length 1, so won't be deleted unless the
388 // whole range is deleted.
389 RemoveChild(obj
, true);
399 /// Get any text in this object for the given range
400 wxString
wxRichTextCompositeObject::GetTextForRange(const wxRichTextRange
& range
) const
403 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
406 wxRichTextObject
* child
= node
->GetData();
407 wxRichTextRange childRange
= range
;
408 if (!child
->GetRange().IsOutside(range
))
410 childRange
.LimitTo(child
->GetRange());
412 wxString childText
= child
->GetTextForRange(childRange
);
416 node
= node
->GetNext();
422 /// Recursively merge all pieces that can be merged.
423 bool wxRichTextCompositeObject::Defragment()
425 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
428 wxRichTextObject
* child
= node
->GetData();
429 wxRichTextCompositeObject
* composite
= wxDynamicCast(child
, wxRichTextCompositeObject
);
431 composite
->Defragment();
435 wxRichTextObject
* nextChild
= node
->GetNext()->GetData();
436 if (child
->CanMerge(nextChild
) && child
->Merge(nextChild
))
438 nextChild
->Dereference();
439 m_children
.Erase(node
->GetNext());
441 // Don't set node -- we'll see if we can merge again with the next
445 node
= node
->GetNext();
448 node
= node
->GetNext();
454 /// Dump to output stream for debugging
455 void wxRichTextCompositeObject::Dump(wxTextOutputStream
& stream
)
457 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
460 wxRichTextObject
* child
= node
->GetData();
462 node
= node
->GetNext();
469 * This defines a 2D space to lay out objects
472 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBox
, wxRichTextCompositeObject
)
474 wxRichTextBox::wxRichTextBox(wxRichTextObject
* parent
):
475 wxRichTextCompositeObject(parent
)
480 bool wxRichTextBox::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& WXUNUSED(rect
), int descent
, int style
)
482 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
485 wxRichTextObject
* child
= node
->GetData();
487 wxRect childRect
= wxRect(child
->GetPosition(), child
->GetCachedSize());
488 child
->Draw(dc
, range
, selectionRange
, childRect
, descent
, style
);
490 node
= node
->GetNext();
496 bool wxRichTextBox::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
498 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
501 wxRichTextObject
* child
= node
->GetData();
502 child
->Layout(dc
, rect
, style
);
504 node
= node
->GetNext();
510 /// Get/set the size for the given range. Assume only has one child.
511 bool wxRichTextBox::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
) const
513 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
516 wxRichTextObject
* child
= node
->GetData();
517 return child
->GetRangeSize(range
, size
, descent
, dc
, flags
, position
);
524 void wxRichTextBox::Copy(const wxRichTextBox
& obj
)
526 wxRichTextCompositeObject::Copy(obj
);
531 * wxRichTextParagraphLayoutBox
532 * This box knows how to lay out paragraphs.
535 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraphLayoutBox
, wxRichTextBox
)
537 wxRichTextParagraphLayoutBox::wxRichTextParagraphLayoutBox(wxRichTextObject
* parent
):
538 wxRichTextBox(parent
)
543 /// Initialize the object.
544 void wxRichTextParagraphLayoutBox::Init()
548 // For now, assume is the only box and has no initial size.
549 m_range
= wxRichTextRange(0, -1);
551 m_invalidRange
.SetRange(-1, -1);
556 m_partialParagraph
= false;
560 bool wxRichTextParagraphLayoutBox::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int descent
, int style
)
562 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
565 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
566 wxASSERT (child
!= NULL
);
568 if (child
&& !child
->GetRange().IsOutside(range
))
570 wxRect
childRect(child
->GetPosition(), child
->GetCachedSize());
572 if (((style
& wxRICHTEXT_DRAW_IGNORE_CACHE
) == 0) && childRect
.GetTop() > rect
.GetBottom())
577 else if (((style
& wxRICHTEXT_DRAW_IGNORE_CACHE
) == 0) && childRect
.GetBottom() < rect
.GetTop())
582 child
->Draw(dc
, range
, selectionRange
, childRect
, descent
, style
);
585 node
= node
->GetNext();
591 bool wxRichTextParagraphLayoutBox::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
593 wxRect availableSpace
;
594 bool formatRect
= (style
& wxRICHTEXT_LAYOUT_SPECIFIED_RECT
) == wxRICHTEXT_LAYOUT_SPECIFIED_RECT
;
596 // If only laying out a specific area, the passed rect has a different meaning:
597 // the visible part of the buffer. This is used in wxRichTextCtrl::OnSize,
598 // so that during a size, only the visible part will be relaid out, or
599 // it would take too long causing flicker. As an approximation, we assume that
600 // everything up to the start of the visible area is laid out correctly.
603 availableSpace
= wxRect(0 + m_leftMargin
,
605 rect
.width
- m_leftMargin
- m_rightMargin
,
608 // Invalidate the part of the buffer from the first visible line
609 // to the end. If other parts of the buffer are currently invalid,
610 // then they too will be taken into account if they are above
611 // the visible point.
613 wxRichTextLine
* line
= GetLineAtYPosition(rect
.y
);
615 startPos
= line
->GetAbsoluteRange().GetStart();
617 Invalidate(wxRichTextRange(startPos
, GetRange().GetEnd()));
620 availableSpace
= wxRect(rect
.x
+ m_leftMargin
,
621 rect
.y
+ m_topMargin
,
622 rect
.width
- m_leftMargin
- m_rightMargin
,
623 rect
.height
- m_topMargin
- m_bottomMargin
);
627 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
629 bool layoutAll
= true;
631 // Get invalid range, rounding to paragraph start/end.
632 wxRichTextRange invalidRange
= GetInvalidRange(true);
634 if (invalidRange
== wxRICHTEXT_NONE
&& !formatRect
)
637 if (invalidRange
== wxRICHTEXT_ALL
)
639 else // If we know what range is affected, start laying out from that point on.
640 if (invalidRange
.GetStart() >= GetRange().GetStart())
642 wxRichTextParagraph
* firstParagraph
= GetParagraphAtPosition(invalidRange
.GetStart());
645 wxRichTextObjectList::compatibility_iterator firstNode
= m_children
.Find(firstParagraph
);
646 wxRichTextObjectList::compatibility_iterator previousNode
;
648 previousNode
= firstNode
->GetPrevious();
653 wxRichTextParagraph
* previousParagraph
= wxDynamicCast(previousNode
->GetData(), wxRichTextParagraph
);
654 availableSpace
.y
= previousParagraph
->GetPosition().y
+ previousParagraph
->GetCachedSize().y
;
657 // Now we're going to start iterating from the first affected paragraph.
665 // A way to force speedy rest-of-buffer layout (the 'else' below)
666 bool forceQuickLayout
= false;
670 // Assume this box only contains paragraphs
672 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
673 wxCHECK_MSG( child
, false, _T("Unknown object in layout") );
675 // TODO: what if the child hasn't been laid out (e.g. involved in Undo) but still has 'old' lines
676 if ( !forceQuickLayout
&&
678 child
->GetLines().IsEmpty() ||
679 !child
->GetRange().IsOutside(invalidRange
)) )
681 child
->Layout(dc
, availableSpace
, style
);
683 // Layout must set the cached size
684 availableSpace
.y
+= child
->GetCachedSize().y
;
685 maxWidth
= wxMax(maxWidth
, child
->GetCachedSize().x
);
687 // If we're just formatting the visible part of the buffer,
688 // and we're now past the bottom of the window, start quick
690 if (formatRect
&& child
->GetPosition().y
> rect
.GetBottom())
691 forceQuickLayout
= true;
695 // We're outside the immediately affected range, so now let's just
696 // move everything up or down. This assumes that all the children have previously
697 // been laid out and have wrapped line lists associated with them.
698 // TODO: check all paragraphs before the affected range.
700 int inc
= availableSpace
.y
- child
->GetPosition().y
;
704 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
707 if (child
->GetLines().GetCount() == 0)
708 child
->Layout(dc
, availableSpace
, style
);
710 child
->SetPosition(wxPoint(child
->GetPosition().x
, child
->GetPosition().y
+ inc
));
712 availableSpace
.y
+= child
->GetCachedSize().y
;
713 maxWidth
= wxMax(maxWidth
, child
->GetCachedSize().x
);
716 node
= node
->GetNext();
721 node
= node
->GetNext();
724 SetCachedSize(wxSize(maxWidth
, availableSpace
.y
));
727 m_invalidRange
= wxRICHTEXT_NONE
;
733 void wxRichTextParagraphLayoutBox::Copy(const wxRichTextParagraphLayoutBox
& obj
)
735 wxRichTextBox::Copy(obj
);
737 m_partialParagraph
= obj
.m_partialParagraph
;
738 m_defaultAttributes
= obj
.m_defaultAttributes
;
741 /// Get/set the size for the given range.
742 bool wxRichTextParagraphLayoutBox::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
) const
746 wxRichTextObjectList::compatibility_iterator startPara
= wxRichTextObjectList::compatibility_iterator();
747 wxRichTextObjectList::compatibility_iterator endPara
= wxRichTextObjectList::compatibility_iterator();
749 // First find the first paragraph whose starting position is within the range.
750 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
753 // child is a paragraph
754 wxRichTextObject
* child
= node
->GetData();
755 const wxRichTextRange
& r
= child
->GetRange();
757 if (r
.GetStart() <= range
.GetStart() && r
.GetEnd() >= range
.GetStart())
763 node
= node
->GetNext();
766 // Next find the last paragraph containing part of the range
767 node
= m_children
.GetFirst();
770 // child is a paragraph
771 wxRichTextObject
* child
= node
->GetData();
772 const wxRichTextRange
& r
= child
->GetRange();
774 if (r
.GetStart() <= range
.GetEnd() && r
.GetEnd() >= range
.GetEnd())
780 node
= node
->GetNext();
783 if (!startPara
|| !endPara
)
786 // Now we can add up the sizes
787 for (node
= startPara
; node
; node
= node
->GetNext())
789 // child is a paragraph
790 wxRichTextObject
* child
= node
->GetData();
791 const wxRichTextRange
& childRange
= child
->GetRange();
792 wxRichTextRange rangeToFind
= range
;
793 rangeToFind
.LimitTo(childRange
);
797 int childDescent
= 0;
798 child
->GetRangeSize(rangeToFind
, childSize
, childDescent
, dc
, flags
, position
);
800 descent
= wxMax(childDescent
, descent
);
802 sz
.x
= wxMax(sz
.x
, childSize
.x
);
814 /// Get the paragraph at the given position
815 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphAtPosition(long pos
, bool caretPosition
) const
820 // First find the first paragraph whose starting position is within the range.
821 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
824 // child is a paragraph
825 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
826 wxASSERT (child
!= NULL
);
828 // Return first child in buffer if position is -1
832 if (child
->GetRange().Contains(pos
))
835 node
= node
->GetNext();
840 /// Get the line at the given position
841 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineAtPosition(long pos
, bool caretPosition
) const
846 // First find the first paragraph whose starting position is within the range.
847 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
850 // child is a paragraph
851 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
852 wxASSERT (child
!= NULL
);
854 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
857 wxRichTextLine
* line
= node2
->GetData();
859 wxRichTextRange range
= line
->GetAbsoluteRange();
861 if (range
.Contains(pos
) ||
863 // If the position is end-of-paragraph, then return the last line of
865 (range
.GetEnd() == child
->GetRange().GetEnd()-1) && (pos
== child
->GetRange().GetEnd()))
868 node2
= node2
->GetNext();
871 node
= node
->GetNext();
874 int lineCount
= GetLineCount();
876 return GetLineForVisibleLineNumber(lineCount
-1);
881 /// Get the line at the given y pixel position, or the last line.
882 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineAtYPosition(int y
) const
884 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
887 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
888 wxASSERT (child
!= NULL
);
890 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
893 wxRichTextLine
* line
= node2
->GetData();
895 wxRect
rect(line
->GetRect());
897 if (y
<= rect
.GetBottom())
900 node2
= node2
->GetNext();
903 node
= node
->GetNext();
907 int lineCount
= GetLineCount();
909 return GetLineForVisibleLineNumber(lineCount
-1);
914 /// Get the number of visible lines
915 int wxRichTextParagraphLayoutBox::GetLineCount() const
919 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
922 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
923 wxASSERT (child
!= NULL
);
925 count
+= child
->GetLines().GetCount();
926 node
= node
->GetNext();
932 /// Get the paragraph for a given line
933 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphForLine(wxRichTextLine
* line
) const
935 return GetParagraphAtPosition(line
->GetAbsoluteRange().GetStart());
938 /// Get the line size at the given position
939 wxSize
wxRichTextParagraphLayoutBox::GetLineSizeAtPosition(long pos
, bool caretPosition
) const
941 wxRichTextLine
* line
= GetLineAtPosition(pos
, caretPosition
);
944 return line
->GetSize();
951 /// Convenience function to add a paragraph of text
952 wxRichTextRange
wxRichTextParagraphLayoutBox::AddParagraph(const wxString
& text
, wxTextAttr
* paraStyle
)
954 // Don't use the base style, just the default style, and the base style will
955 // be combined at display time.
956 // Divide into paragraph and character styles.
958 wxTextAttr defaultCharStyle
;
959 wxTextAttr defaultParaStyle
;
961 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
962 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
963 wxTextAttr
* cStyle
= & defaultCharStyle
;
965 wxRichTextParagraph
* para
= new wxRichTextParagraph(text
, this, pStyle
, cStyle
);
972 return para
->GetRange();
975 /// Adds multiple paragraphs, based on newlines.
976 wxRichTextRange
wxRichTextParagraphLayoutBox::AddParagraphs(const wxString
& text
, wxTextAttr
* paraStyle
)
978 // Don't use the base style, just the default style, and the base style will
979 // be combined at display time.
980 // Divide into paragraph and character styles.
982 wxTextAttr defaultCharStyle
;
983 wxTextAttr defaultParaStyle
;
984 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
986 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
987 wxTextAttr
* cStyle
= & defaultCharStyle
;
989 wxRichTextParagraph
* firstPara
= NULL
;
990 wxRichTextParagraph
* lastPara
= NULL
;
992 wxRichTextRange
range(-1, -1);
995 size_t len
= text
.length();
997 wxRichTextParagraph
* para
= new wxRichTextParagraph(wxEmptyString
, this, pStyle
, cStyle
);
1006 wxChar ch
= text
[i
];
1007 if (ch
== wxT('\n') || ch
== wxT('\r'))
1009 wxRichTextPlainText
* plainText
= (wxRichTextPlainText
*) para
->GetChildren().GetFirst()->GetData();
1010 plainText
->SetText(line
);
1012 para
= new wxRichTextParagraph(wxEmptyString
, this, pStyle
, cStyle
);
1017 line
= wxEmptyString
;
1027 wxRichTextPlainText
* plainText
= (wxRichTextPlainText
*) para
->GetChildren().GetFirst()->GetData();
1028 plainText
->SetText(line
);
1035 return wxRichTextRange(firstPara
->GetRange().GetStart(), lastPara
->GetRange().GetEnd());
1038 /// Convenience function to add an image
1039 wxRichTextRange
wxRichTextParagraphLayoutBox::AddImage(const wxImage
& image
, wxTextAttr
* paraStyle
)
1041 // Don't use the base style, just the default style, and the base style will
1042 // be combined at display time.
1043 // Divide into paragraph and character styles.
1045 wxTextAttr defaultCharStyle
;
1046 wxTextAttr defaultParaStyle
;
1047 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle
, defaultCharStyle
);
1049 wxTextAttr
* pStyle
= paraStyle
? paraStyle
: (wxTextAttr
*) & defaultParaStyle
;
1050 wxTextAttr
* cStyle
= & defaultCharStyle
;
1052 wxRichTextParagraph
* para
= new wxRichTextParagraph(this, pStyle
);
1054 para
->AppendChild(new wxRichTextImage(image
, this, cStyle
));
1059 return para
->GetRange();
1063 /// Insert fragment into this box at the given position. If partialParagraph is true,
1064 /// it is assumed that the last (or only) paragraph is just a piece of data with no paragraph
1067 bool wxRichTextParagraphLayoutBox::InsertFragment(long position
, wxRichTextParagraphLayoutBox
& fragment
)
1071 // First, find the first paragraph whose starting position is within the range.
1072 wxRichTextParagraph
* para
= GetParagraphAtPosition(position
);
1075 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(para
);
1077 // Now split at this position, returning the object to insert the new
1078 // ones in front of.
1079 wxRichTextObject
* nextObject
= para
->SplitAt(position
);
1081 // Special case: partial paragraph, just one paragraph. Might be a small amount of
1082 // text, for example, so let's optimize.
1084 if (fragment
.GetPartialParagraph() && fragment
.GetChildren().GetCount() == 1)
1086 // Add the first para to this para...
1087 wxRichTextObjectList::compatibility_iterator firstParaNode
= fragment
.GetChildren().GetFirst();
1091 // Iterate through the fragment paragraph inserting the content into this paragraph.
1092 wxRichTextParagraph
* firstPara
= wxDynamicCast(firstParaNode
->GetData(), wxRichTextParagraph
);
1093 wxASSERT (firstPara
!= NULL
);
1095 // Apply the new paragraph attributes to the existing paragraph
1096 wxTextAttr
attr(para
->GetAttributes());
1097 wxRichTextApplyStyle(attr
, firstPara
->GetAttributes());
1098 para
->SetAttributes(attr
);
1100 wxRichTextObjectList::compatibility_iterator objectNode
= firstPara
->GetChildren().GetFirst();
1103 wxRichTextObject
* newObj
= objectNode
->GetData()->Clone();
1108 para
->AppendChild(newObj
);
1112 // Insert before nextObject
1113 para
->InsertChild(newObj
, nextObject
);
1116 objectNode
= objectNode
->GetNext();
1123 // Procedure for inserting a fragment consisting of a number of
1126 // 1. Remove and save the content that's after the insertion point, for adding
1127 // back once we've added the fragment.
1128 // 2. Add the content from the first fragment paragraph to the current
1130 // 3. Add remaining fragment paragraphs after the current paragraph.
1131 // 4. Add back the saved content from the first paragraph. If partialParagraph
1132 // is true, add it to the last paragraph added and not a new one.
1134 // 1. Remove and save objects after split point.
1135 wxList savedObjects
;
1137 para
->MoveToList(nextObject
, savedObjects
);
1139 // 2. Add the content from the 1st fragment paragraph.
1140 wxRichTextObjectList::compatibility_iterator firstParaNode
= fragment
.GetChildren().GetFirst();
1144 wxRichTextParagraph
* firstPara
= wxDynamicCast(firstParaNode
->GetData(), wxRichTextParagraph
);
1145 wxASSERT(firstPara
!= NULL
);
1147 wxRichTextObjectList::compatibility_iterator objectNode
= firstPara
->GetChildren().GetFirst();
1150 wxRichTextObject
* newObj
= objectNode
->GetData()->Clone();
1153 para
->AppendChild(newObj
);
1155 objectNode
= objectNode
->GetNext();
1158 // 3. Add remaining fragment paragraphs after the current paragraph.
1159 wxRichTextObjectList::compatibility_iterator nextParagraphNode
= node
->GetNext();
1160 wxRichTextObject
* nextParagraph
= NULL
;
1161 if (nextParagraphNode
)
1162 nextParagraph
= nextParagraphNode
->GetData();
1164 wxRichTextObjectList::compatibility_iterator i
= fragment
.GetChildren().GetFirst()->GetNext();
1165 wxRichTextParagraph
* finalPara
= para
;
1167 // If there was only one paragraph, we need to insert a new one.
1170 finalPara
= new wxRichTextParagraph
;
1172 // TODO: These attributes should come from the subsequent paragraph
1173 // when originally deleted, since the subsequent para takes on
1174 // the previous para's attributes.
1175 finalPara
->SetAttributes(firstPara
->GetAttributes());
1178 InsertChild(finalPara
, nextParagraph
);
1180 AppendChild(finalPara
);
1184 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1185 wxASSERT( para
!= NULL
);
1187 finalPara
= (wxRichTextParagraph
*) para
->Clone();
1190 InsertChild(finalPara
, nextParagraph
);
1192 AppendChild(finalPara
);
1197 // 4. Add back the remaining content.
1200 finalPara
->MoveFromList(savedObjects
);
1202 // Ensure there's at least one object
1203 if (finalPara
->GetChildCount() == 0)
1205 wxRichTextPlainText
* text
= new wxRichTextPlainText(wxEmptyString
);
1207 finalPara
->AppendChild(text
);
1217 wxRichTextObjectList::compatibility_iterator i
= fragment
.GetChildren().GetFirst();
1220 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1221 wxASSERT( para
!= NULL
);
1223 AppendChild(para
->Clone());
1232 /// Make a copy of the fragment corresponding to the given range, putting it in 'fragment'.
1233 /// If there was an incomplete paragraph at the end, partialParagraph is set to true.
1234 bool wxRichTextParagraphLayoutBox::CopyFragment(const wxRichTextRange
& range
, wxRichTextParagraphLayoutBox
& fragment
)
1236 wxRichTextObjectList::compatibility_iterator i
= GetChildren().GetFirst();
1239 wxRichTextParagraph
* para
= wxDynamicCast(i
->GetData(), wxRichTextParagraph
);
1240 wxASSERT( para
!= NULL
);
1242 if (!para
->GetRange().IsOutside(range
))
1244 fragment
.AppendChild(para
->Clone());
1249 // Now top and tail the first and last paragraphs in our new fragment (which might be the same).
1250 if (!fragment
.IsEmpty())
1252 wxRichTextRange
topTailRange(range
);
1254 wxRichTextParagraph
* firstPara
= wxDynamicCast(fragment
.GetChildren().GetFirst()->GetData(), wxRichTextParagraph
);
1255 wxASSERT( firstPara
!= NULL
);
1257 // Chop off the start of the paragraph
1258 if (topTailRange
.GetStart() > firstPara
->GetRange().GetStart())
1260 wxRichTextRange
r(firstPara
->GetRange().GetStart(), topTailRange
.GetStart()-1);
1261 firstPara
->DeleteRange(r
);
1263 // Make sure the numbering is correct
1265 fragment
.CalculateRange(firstPara
->GetRange().GetStart(), end
);
1267 // Now, we've deleted some positions, so adjust the range
1269 topTailRange
.SetEnd(topTailRange
.GetEnd() - r
.GetLength());
1272 wxRichTextParagraph
* lastPara
= wxDynamicCast(fragment
.GetChildren().GetLast()->GetData(), wxRichTextParagraph
);
1273 wxASSERT( lastPara
!= NULL
);
1275 if (topTailRange
.GetEnd() < (lastPara
->GetRange().GetEnd()-1))
1277 wxRichTextRange
r(topTailRange
.GetEnd()+1, lastPara
->GetRange().GetEnd()-1); /* -1 since actual text ends 1 position before end of para marker */
1278 lastPara
->DeleteRange(r
);
1280 // Make sure the numbering is correct
1282 fragment
.CalculateRange(firstPara
->GetRange().GetStart(), end
);
1284 // We only have part of a paragraph at the end
1285 fragment
.SetPartialParagraph(true);
1289 if (topTailRange
.GetEnd() == (lastPara
->GetRange().GetEnd() - 1))
1290 // We have a partial paragraph (don't save last new paragraph marker)
1291 fragment
.SetPartialParagraph(true);
1293 // We have a complete paragraph
1294 fragment
.SetPartialParagraph(false);
1301 /// Given a position, get the number of the visible line (potentially many to a paragraph),
1302 /// starting from zero at the start of the buffer.
1303 long wxRichTextParagraphLayoutBox::GetVisibleLineNumber(long pos
, bool caretPosition
, bool startOfLine
) const
1310 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1313 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1314 wxASSERT( child
!= NULL
);
1316 if (child
->GetRange().Contains(pos
))
1318 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
1321 wxRichTextLine
* line
= node2
->GetData();
1322 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
1324 if (lineRange
.Contains(pos
))
1326 // If the caret is displayed at the end of the previous wrapped line,
1327 // we want to return the line it's _displayed_ at (not the actual line
1328 // containing the position).
1329 if (lineRange
.GetStart() == pos
&& !startOfLine
&& child
->GetRange().GetStart() != pos
)
1330 return lineCount
- 1;
1337 node2
= node2
->GetNext();
1339 // If we didn't find it in the lines, it must be
1340 // the last position of the paragraph. So return the last line.
1344 lineCount
+= child
->GetLines().GetCount();
1346 node
= node
->GetNext();
1353 /// Given a line number, get the corresponding wxRichTextLine object.
1354 wxRichTextLine
* wxRichTextParagraphLayoutBox::GetLineForVisibleLineNumber(long lineNumber
) const
1358 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1361 wxRichTextParagraph
* child
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1362 wxASSERT(child
!= NULL
);
1364 if (lineNumber
< (int) (child
->GetLines().GetCount() + lineCount
))
1366 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
1369 wxRichTextLine
* line
= node2
->GetData();
1371 if (lineCount
== lineNumber
)
1376 node2
= node2
->GetNext();
1380 lineCount
+= child
->GetLines().GetCount();
1382 node
= node
->GetNext();
1389 /// Delete range from layout.
1390 bool wxRichTextParagraphLayoutBox::DeleteRange(const wxRichTextRange
& range
)
1392 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1396 wxRichTextParagraph
* obj
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1397 wxASSERT (obj
!= NULL
);
1399 wxRichTextObjectList::compatibility_iterator next
= node
->GetNext();
1401 // Delete the range in each paragraph
1403 if (!obj
->GetRange().IsOutside(range
))
1405 // Deletes the content of this object within the given range
1406 obj
->DeleteRange(range
);
1408 // If the whole paragraph is within the range to delete,
1409 // delete the whole thing.
1410 if (range
.GetStart() <= obj
->GetRange().GetStart() && range
.GetEnd() >= obj
->GetRange().GetEnd())
1412 // Delete the whole object
1413 RemoveChild(obj
, true);
1415 // If the range includes the paragraph end, we need to join this
1416 // and the next paragraph.
1417 else if (range
.Contains(obj
->GetRange().GetEnd()))
1419 // We need to move the objects from the next paragraph
1420 // to this paragraph
1424 wxRichTextParagraph
* nextParagraph
= wxDynamicCast(next
->GetData(), wxRichTextParagraph
);
1425 next
= next
->GetNext();
1428 // Delete the stuff we need to delete
1429 nextParagraph
->DeleteRange(range
);
1431 // Move the objects to the previous para
1432 wxRichTextObjectList::compatibility_iterator node1
= nextParagraph
->GetChildren().GetFirst();
1436 wxRichTextObject
* obj1
= node1
->GetData();
1438 // If the object is empty, optimise it out
1439 if (obj1
->IsEmpty())
1445 obj
->AppendChild(obj1
);
1448 wxRichTextObjectList::compatibility_iterator next1
= node1
->GetNext();
1449 nextParagraph
->GetChildren().Erase(node1
);
1454 // Delete the paragraph
1455 RemoveChild(nextParagraph
, true);
1469 /// Get any text in this object for the given range
1470 wxString
wxRichTextParagraphLayoutBox::GetTextForRange(const wxRichTextRange
& range
) const
1474 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1477 wxRichTextObject
* child
= node
->GetData();
1478 if (!child
->GetRange().IsOutside(range
))
1480 wxRichTextRange childRange
= range
;
1481 childRange
.LimitTo(child
->GetRange());
1483 wxString childText
= child
->GetTextForRange(childRange
);
1487 if ((childRange
.GetEnd() == child
->GetRange().GetEnd()) && node
->GetNext())
1492 node
= node
->GetNext();
1498 /// Get all the text
1499 wxString
wxRichTextParagraphLayoutBox::GetText() const
1501 return GetTextForRange(GetRange());
1504 /// Get the paragraph by number
1505 wxRichTextParagraph
* wxRichTextParagraphLayoutBox::GetParagraphAtLine(long paragraphNumber
) const
1507 if ((size_t) paragraphNumber
>= GetChildCount())
1510 return (wxRichTextParagraph
*) GetChild((size_t) paragraphNumber
);
1513 /// Get the length of the paragraph
1514 int wxRichTextParagraphLayoutBox::GetParagraphLength(long paragraphNumber
) const
1516 wxRichTextParagraph
* para
= GetParagraphAtLine(paragraphNumber
);
1518 return para
->GetRange().GetLength() - 1; // don't include newline
1523 /// Get the text of the paragraph
1524 wxString
wxRichTextParagraphLayoutBox::GetParagraphText(long paragraphNumber
) const
1526 wxRichTextParagraph
* para
= GetParagraphAtLine(paragraphNumber
);
1528 return para
->GetTextForRange(para
->GetRange());
1530 return wxEmptyString
;
1533 /// Convert zero-based line column and paragraph number to a position.
1534 long wxRichTextParagraphLayoutBox::XYToPosition(long x
, long y
) const
1536 wxRichTextParagraph
* para
= GetParagraphAtLine(y
);
1539 return para
->GetRange().GetStart() + x
;
1545 /// Convert zero-based position to line column and paragraph number
1546 bool wxRichTextParagraphLayoutBox::PositionToXY(long pos
, long* x
, long* y
) const
1548 wxRichTextParagraph
* para
= GetParagraphAtPosition(pos
);
1552 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1555 wxRichTextObject
* child
= node
->GetData();
1559 node
= node
->GetNext();
1563 *x
= pos
- para
->GetRange().GetStart();
1571 /// Get the leaf object in a paragraph at this position.
1572 /// Given a line number, get the corresponding wxRichTextLine object.
1573 wxRichTextObject
* wxRichTextParagraphLayoutBox::GetLeafObjectAtPosition(long position
) const
1575 wxRichTextParagraph
* para
= GetParagraphAtPosition(position
);
1578 wxRichTextObjectList::compatibility_iterator node
= para
->GetChildren().GetFirst();
1582 wxRichTextObject
* child
= node
->GetData();
1583 if (child
->GetRange().Contains(position
))
1586 node
= node
->GetNext();
1588 if (position
== para
->GetRange().GetEnd() && para
->GetChildCount() > 0)
1589 return para
->GetChildren().GetLast()->GetData();
1594 /// Set character or paragraph text attributes: apply character styles only to immediate text nodes
1595 bool wxRichTextParagraphLayoutBox::SetStyle(const wxRichTextRange
& range
, const wxTextAttr
& style
, int flags
)
1597 bool characterStyle
= false;
1598 bool paragraphStyle
= false;
1600 if (style
.IsCharacterStyle())
1601 characterStyle
= true;
1602 if (style
.IsParagraphStyle())
1603 paragraphStyle
= true;
1605 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
1606 bool applyMinimal
= ((flags
& wxRICHTEXT_SETSTYLE_OPTIMIZE
) != 0);
1607 bool parasOnly
= ((flags
& wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY
) != 0);
1608 bool charactersOnly
= ((flags
& wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY
) != 0);
1609 bool resetExistingStyle
= ((flags
& wxRICHTEXT_SETSTYLE_RESET
) != 0);
1610 bool removeStyle
= ((flags
& wxRICHTEXT_SETSTYLE_REMOVE
) != 0);
1612 // Apply paragraph style first, if any
1613 wxTextAttr
wholeStyle(style
);
1615 if (!removeStyle
&& wholeStyle
.HasParagraphStyleName() && GetStyleSheet())
1617 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(wholeStyle
.GetParagraphStyleName());
1619 wxRichTextApplyStyle(wholeStyle
, def
->GetStyleMergedWithBase(GetStyleSheet()));
1622 // Limit the attributes to be set to the content to only character attributes.
1623 wxTextAttr
characterAttributes(wholeStyle
);
1624 characterAttributes
.SetFlags(characterAttributes
.GetFlags() & (wxTEXT_ATTR_CHARACTER
));
1626 if (!removeStyle
&& characterAttributes
.HasCharacterStyleName() && GetStyleSheet())
1628 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterAttributes
.GetCharacterStyleName());
1630 wxRichTextApplyStyle(characterAttributes
, def
->GetStyleMergedWithBase(GetStyleSheet()));
1633 // If we are associated with a control, make undoable; otherwise, apply immediately
1636 bool haveControl
= (GetRichTextCtrl() != NULL
);
1638 wxRichTextAction
* action
= NULL
;
1640 if (haveControl
&& withUndo
)
1642 action
= new wxRichTextAction(NULL
, _("Change Style"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
1643 action
->SetRange(range
);
1644 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
1647 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
1650 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
1651 wxASSERT (para
!= NULL
);
1653 if (para
&& para
->GetChildCount() > 0)
1655 // Stop searching if we're beyond the range of interest
1656 if (para
->GetRange().GetStart() > range
.GetEnd())
1659 if (!para
->GetRange().IsOutside(range
))
1661 // We'll be using a copy of the paragraph to make style changes,
1662 // not updating the buffer directly.
1663 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
1665 if (haveControl
&& withUndo
)
1667 newPara
= new wxRichTextParagraph(*para
);
1668 action
->GetNewParagraphs().AppendChild(newPara
);
1670 // Also store the old ones for Undo
1671 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
1676 // If we're specifying paragraphs only, then we really mean character formatting
1677 // to be included in the paragraph style
1678 if ((paragraphStyle
|| parasOnly
) && !charactersOnly
)
1682 // Removes the given style from the paragraph
1683 wxRichTextRemoveStyle(newPara
->GetAttributes(), style
);
1685 else if (resetExistingStyle
)
1686 newPara
->GetAttributes() = wholeStyle
;
1691 // Only apply attributes that will make a difference to the combined
1692 // style as seen on the display
1693 wxTextAttr
combinedAttr(para
->GetCombinedAttributes());
1694 wxRichTextApplyStyle(newPara
->GetAttributes(), wholeStyle
, & combinedAttr
);
1697 wxRichTextApplyStyle(newPara
->GetAttributes(), wholeStyle
);
1701 // When applying paragraph styles dynamically, don't change the text objects' attributes
1702 // since they will computed as needed. Only apply the character styling if it's _only_
1703 // character styling. This policy is subject to change and might be put under user control.
1705 // Hm. we might well be applying a mix of paragraph and character styles, in which
1706 // case we _do_ want to apply character styles regardless of what para styles are set.
1707 // But if we're applying a paragraph style, which has some character attributes, but
1708 // we only want the paragraphs to hold this character style, then we _don't_ want to
1709 // apply the character style. So we need to be able to choose.
1711 // if (!paragraphStyle && characterStyle && range.GetStart() != newPara->GetRange().GetEnd())
1712 if (!parasOnly
&& characterStyle
&& range
.GetStart() != newPara
->GetRange().GetEnd())
1714 wxRichTextRange
childRange(range
);
1715 childRange
.LimitTo(newPara
->GetRange());
1717 // Find the starting position and if necessary split it so
1718 // we can start applying a different style.
1719 // TODO: check that the style actually changes or is different
1720 // from style outside of range
1721 wxRichTextObject
* firstObject
wxDUMMY_INITIALIZE(NULL
);
1722 wxRichTextObject
* lastObject
wxDUMMY_INITIALIZE(NULL
);
1724 if (childRange
.GetStart() == newPara
->GetRange().GetStart())
1725 firstObject
= newPara
->GetChildren().GetFirst()->GetData();
1727 firstObject
= newPara
->SplitAt(range
.GetStart());
1729 // Increment by 1 because we're apply the style one _after_ the split point
1730 long splitPoint
= childRange
.GetEnd();
1731 if (splitPoint
!= newPara
->GetRange().GetEnd())
1735 if (splitPoint
== newPara
->GetRange().GetEnd() || splitPoint
== (newPara
->GetRange().GetEnd() - 1))
1736 lastObject
= newPara
->GetChildren().GetLast()->GetData();
1738 // lastObject is set as a side-effect of splitting. It's
1739 // returned as the object before the new object.
1740 (void) newPara
->SplitAt(splitPoint
, & lastObject
);
1742 wxASSERT(firstObject
!= NULL
);
1743 wxASSERT(lastObject
!= NULL
);
1745 if (!firstObject
|| !lastObject
)
1748 wxRichTextObjectList::compatibility_iterator firstNode
= newPara
->GetChildren().Find(firstObject
);
1749 wxRichTextObjectList::compatibility_iterator lastNode
= newPara
->GetChildren().Find(lastObject
);
1751 wxASSERT(firstNode
);
1754 wxRichTextObjectList::compatibility_iterator node2
= firstNode
;
1758 wxRichTextObject
* child
= node2
->GetData();
1762 // Removes the given style from the paragraph
1763 wxRichTextRemoveStyle(child
->GetAttributes(), style
);
1765 else if (resetExistingStyle
)
1766 child
->GetAttributes() = characterAttributes
;
1771 // Only apply attributes that will make a difference to the combined
1772 // style as seen on the display
1773 wxTextAttr
combinedAttr(newPara
->GetCombinedAttributes(child
->GetAttributes()));
1774 wxRichTextApplyStyle(child
->GetAttributes(), characterAttributes
, & combinedAttr
);
1777 wxRichTextApplyStyle(child
->GetAttributes(), characterAttributes
);
1780 if (node2
== lastNode
)
1783 node2
= node2
->GetNext();
1789 node
= node
->GetNext();
1792 // Do action, or delay it until end of batch.
1793 if (haveControl
&& withUndo
)
1794 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
1799 /// Get the text attributes for this position.
1800 bool wxRichTextParagraphLayoutBox::GetStyle(long position
, wxTextAttr
& style
)
1802 return DoGetStyle(position
, style
, true);
1805 bool wxRichTextParagraphLayoutBox::GetUncombinedStyle(long position
, wxTextAttr
& style
)
1807 return DoGetStyle(position
, style
, false);
1810 /// Implementation helper for GetStyle. If combineStyles is true, combine base, paragraph and
1811 /// context attributes.
1812 bool wxRichTextParagraphLayoutBox::DoGetStyle(long position
, wxTextAttr
& style
, bool combineStyles
)
1814 wxRichTextObject
* obj
wxDUMMY_INITIALIZE(NULL
);
1816 if (style
.IsParagraphStyle())
1818 obj
= GetParagraphAtPosition(position
);
1823 // Start with the base style
1824 style
= GetAttributes();
1826 // Apply the paragraph style
1827 wxRichTextApplyStyle(style
, obj
->GetAttributes());
1830 style
= obj
->GetAttributes();
1837 obj
= GetLeafObjectAtPosition(position
);
1842 wxRichTextParagraph
* para
= wxDynamicCast(obj
->GetParent(), wxRichTextParagraph
);
1843 style
= para
? para
->GetCombinedAttributes(obj
->GetAttributes()) : obj
->GetAttributes();
1846 style
= obj
->GetAttributes();
1854 static bool wxHasStyle(long flags
, long style
)
1856 return (flags
& style
) != 0;
1859 /// Combines 'style' with 'currentStyle' for the purpose of summarising the attributes of a range of
1861 bool wxRichTextParagraphLayoutBox::CollectStyle(wxTextAttr
& currentStyle
, const wxTextAttr
& style
, long& multipleStyleAttributes
, int& multipleTextEffectAttributes
)
1863 if (style
.HasFont())
1865 if (style
.HasFontSize() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_SIZE
))
1867 if (currentStyle
.HasFontSize())
1869 if (currentStyle
.GetFontSize() != style
.GetFontSize())
1871 // Clash of style - mark as such
1872 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_SIZE
;
1873 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_SIZE
);
1878 currentStyle
.SetFontSize(style
.GetFontSize());
1882 if (style
.HasFontItalic() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_ITALIC
))
1884 if (currentStyle
.HasFontItalic())
1886 if (currentStyle
.GetFontStyle() != style
.GetFontStyle())
1888 // Clash of style - mark as such
1889 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_ITALIC
;
1890 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_ITALIC
);
1895 currentStyle
.SetFontStyle(style
.GetFontStyle());
1899 if (style
.HasFontWeight() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_WEIGHT
))
1901 if (currentStyle
.HasFontWeight())
1903 if (currentStyle
.GetFontWeight() != style
.GetFontWeight())
1905 // Clash of style - mark as such
1906 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_WEIGHT
;
1907 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_WEIGHT
);
1912 currentStyle
.SetFontWeight(style
.GetFontWeight());
1916 if (style
.HasFontFaceName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_FACE
))
1918 if (currentStyle
.HasFontFaceName())
1920 wxString
faceName1(currentStyle
.GetFontFaceName());
1921 wxString
faceName2(style
.GetFontFaceName());
1923 if (faceName1
!= faceName2
)
1925 // Clash of style - mark as such
1926 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_FACE
;
1927 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_FACE
);
1932 currentStyle
.SetFontFaceName(style
.GetFontFaceName());
1936 if (style
.HasFontUnderlined() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_FONT_UNDERLINE
))
1938 if (currentStyle
.HasFontUnderlined())
1940 if (currentStyle
.GetFontUnderlined() != style
.GetFontUnderlined())
1942 // Clash of style - mark as such
1943 multipleStyleAttributes
|= wxTEXT_ATTR_FONT_UNDERLINE
;
1944 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_FONT_UNDERLINE
);
1949 currentStyle
.SetFontUnderlined(style
.GetFontUnderlined());
1954 if (style
.HasTextColour() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_TEXT_COLOUR
))
1956 if (currentStyle
.HasTextColour())
1958 if (currentStyle
.GetTextColour() != style
.GetTextColour())
1960 // Clash of style - mark as such
1961 multipleStyleAttributes
|= wxTEXT_ATTR_TEXT_COLOUR
;
1962 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_TEXT_COLOUR
);
1966 currentStyle
.SetTextColour(style
.GetTextColour());
1969 if (style
.HasBackgroundColour() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BACKGROUND_COLOUR
))
1971 if (currentStyle
.HasBackgroundColour())
1973 if (currentStyle
.GetBackgroundColour() != style
.GetBackgroundColour())
1975 // Clash of style - mark as such
1976 multipleStyleAttributes
|= wxTEXT_ATTR_BACKGROUND_COLOUR
;
1977 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BACKGROUND_COLOUR
);
1981 currentStyle
.SetBackgroundColour(style
.GetBackgroundColour());
1984 if (style
.HasAlignment() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_ALIGNMENT
))
1986 if (currentStyle
.HasAlignment())
1988 if (currentStyle
.GetAlignment() != style
.GetAlignment())
1990 // Clash of style - mark as such
1991 multipleStyleAttributes
|= wxTEXT_ATTR_ALIGNMENT
;
1992 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_ALIGNMENT
);
1996 currentStyle
.SetAlignment(style
.GetAlignment());
1999 if (style
.HasTabs() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_TABS
))
2001 if (currentStyle
.HasTabs())
2003 if (!wxRichTextTabsEq(currentStyle
.GetTabs(), style
.GetTabs()))
2005 // Clash of style - mark as such
2006 multipleStyleAttributes
|= wxTEXT_ATTR_TABS
;
2007 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_TABS
);
2011 currentStyle
.SetTabs(style
.GetTabs());
2014 if (style
.HasLeftIndent() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_LEFT_INDENT
))
2016 if (currentStyle
.HasLeftIndent())
2018 if (currentStyle
.GetLeftIndent() != style
.GetLeftIndent() || currentStyle
.GetLeftSubIndent() != style
.GetLeftSubIndent())
2020 // Clash of style - mark as such
2021 multipleStyleAttributes
|= wxTEXT_ATTR_LEFT_INDENT
;
2022 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LEFT_INDENT
);
2026 currentStyle
.SetLeftIndent(style
.GetLeftIndent(), style
.GetLeftSubIndent());
2029 if (style
.HasRightIndent() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_RIGHT_INDENT
))
2031 if (currentStyle
.HasRightIndent())
2033 if (currentStyle
.GetRightIndent() != style
.GetRightIndent())
2035 // Clash of style - mark as such
2036 multipleStyleAttributes
|= wxTEXT_ATTR_RIGHT_INDENT
;
2037 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_RIGHT_INDENT
);
2041 currentStyle
.SetRightIndent(style
.GetRightIndent());
2044 if (style
.HasParagraphSpacingAfter() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_PARA_SPACING_AFTER
))
2046 if (currentStyle
.HasParagraphSpacingAfter())
2048 if (currentStyle
.GetParagraphSpacingAfter() != style
.GetParagraphSpacingAfter())
2050 // Clash of style - mark as such
2051 multipleStyleAttributes
|= wxTEXT_ATTR_PARA_SPACING_AFTER
;
2052 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARA_SPACING_AFTER
);
2056 currentStyle
.SetParagraphSpacingAfter(style
.GetParagraphSpacingAfter());
2059 if (style
.HasParagraphSpacingBefore() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_PARA_SPACING_BEFORE
))
2061 if (currentStyle
.HasParagraphSpacingBefore())
2063 if (currentStyle
.GetParagraphSpacingBefore() != style
.GetParagraphSpacingBefore())
2065 // Clash of style - mark as such
2066 multipleStyleAttributes
|= wxTEXT_ATTR_PARA_SPACING_BEFORE
;
2067 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARA_SPACING_BEFORE
);
2071 currentStyle
.SetParagraphSpacingBefore(style
.GetParagraphSpacingBefore());
2074 if (style
.HasLineSpacing() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_LINE_SPACING
))
2076 if (currentStyle
.HasLineSpacing())
2078 if (currentStyle
.GetLineSpacing() != style
.GetLineSpacing())
2080 // Clash of style - mark as such
2081 multipleStyleAttributes
|= wxTEXT_ATTR_LINE_SPACING
;
2082 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LINE_SPACING
);
2086 currentStyle
.SetLineSpacing(style
.GetLineSpacing());
2089 if (style
.HasCharacterStyleName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_CHARACTER_STYLE_NAME
))
2091 if (currentStyle
.HasCharacterStyleName())
2093 if (currentStyle
.GetCharacterStyleName() != style
.GetCharacterStyleName())
2095 // Clash of style - mark as such
2096 multipleStyleAttributes
|= wxTEXT_ATTR_CHARACTER_STYLE_NAME
;
2097 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_CHARACTER_STYLE_NAME
);
2101 currentStyle
.SetCharacterStyleName(style
.GetCharacterStyleName());
2104 if (style
.HasParagraphStyleName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
))
2106 if (currentStyle
.HasParagraphStyleName())
2108 if (currentStyle
.GetParagraphStyleName() != style
.GetParagraphStyleName())
2110 // Clash of style - mark as such
2111 multipleStyleAttributes
|= wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
;
2112 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_PARAGRAPH_STYLE_NAME
);
2116 currentStyle
.SetParagraphStyleName(style
.GetParagraphStyleName());
2119 if (style
.HasListStyleName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_LIST_STYLE_NAME
))
2121 if (currentStyle
.HasListStyleName())
2123 if (currentStyle
.GetListStyleName() != style
.GetListStyleName())
2125 // Clash of style - mark as such
2126 multipleStyleAttributes
|= wxTEXT_ATTR_LIST_STYLE_NAME
;
2127 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_LIST_STYLE_NAME
);
2131 currentStyle
.SetListStyleName(style
.GetListStyleName());
2134 if (style
.HasBulletStyle() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_STYLE
))
2136 if (currentStyle
.HasBulletStyle())
2138 if (currentStyle
.GetBulletStyle() != style
.GetBulletStyle())
2140 // Clash of style - mark as such
2141 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_STYLE
;
2142 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_STYLE
);
2146 currentStyle
.SetBulletStyle(style
.GetBulletStyle());
2149 if (style
.HasBulletNumber() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_NUMBER
))
2151 if (currentStyle
.HasBulletNumber())
2153 if (currentStyle
.GetBulletNumber() != style
.GetBulletNumber())
2155 // Clash of style - mark as such
2156 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_NUMBER
;
2157 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_NUMBER
);
2161 currentStyle
.SetBulletNumber(style
.GetBulletNumber());
2164 if (style
.HasBulletText() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_TEXT
))
2166 if (currentStyle
.HasBulletText())
2168 if (currentStyle
.GetBulletText() != style
.GetBulletText())
2170 // Clash of style - mark as such
2171 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_TEXT
;
2172 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_TEXT
);
2177 currentStyle
.SetBulletText(style
.GetBulletText());
2178 currentStyle
.SetBulletFont(style
.GetBulletFont());
2182 if (style
.HasBulletName() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_BULLET_NAME
))
2184 if (currentStyle
.HasBulletName())
2186 if (currentStyle
.GetBulletName() != style
.GetBulletName())
2188 // Clash of style - mark as such
2189 multipleStyleAttributes
|= wxTEXT_ATTR_BULLET_NAME
;
2190 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_BULLET_NAME
);
2195 currentStyle
.SetBulletName(style
.GetBulletName());
2199 if (style
.HasURL() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_URL
))
2201 if (currentStyle
.HasURL())
2203 if (currentStyle
.GetURL() != style
.GetURL())
2205 // Clash of style - mark as such
2206 multipleStyleAttributes
|= wxTEXT_ATTR_URL
;
2207 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_URL
);
2212 currentStyle
.SetURL(style
.GetURL());
2216 if (style
.HasTextEffects() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_EFFECTS
))
2218 if (currentStyle
.HasTextEffects())
2220 // We need to find the bits in the new style that are different:
2221 // just look at those bits that are specified by the new style.
2223 int currentRelevantTextEffects
= currentStyle
.GetTextEffects() & style
.GetTextEffectFlags();
2224 int newRelevantTextEffects
= style
.GetTextEffects() & style
.GetTextEffectFlags();
2226 if (currentRelevantTextEffects
!= newRelevantTextEffects
)
2228 // Find the text effects that were different, using XOR
2229 int differentEffects
= currentRelevantTextEffects
^ newRelevantTextEffects
;
2231 // Clash of style - mark as such
2232 multipleTextEffectAttributes
|= differentEffects
;
2233 currentStyle
.SetTextEffectFlags(currentStyle
.GetTextEffectFlags() & ~differentEffects
);
2238 currentStyle
.SetTextEffects(style
.GetTextEffects());
2239 currentStyle
.SetTextEffectFlags(style
.GetTextEffectFlags());
2243 if (style
.HasOutlineLevel() && !wxHasStyle(multipleStyleAttributes
, wxTEXT_ATTR_OUTLINE_LEVEL
))
2245 if (currentStyle
.HasOutlineLevel())
2247 if (currentStyle
.GetOutlineLevel() != style
.GetOutlineLevel())
2249 // Clash of style - mark as such
2250 multipleStyleAttributes
|= wxTEXT_ATTR_OUTLINE_LEVEL
;
2251 currentStyle
.SetFlags(currentStyle
.GetFlags() & ~wxTEXT_ATTR_OUTLINE_LEVEL
);
2255 currentStyle
.SetOutlineLevel(style
.GetOutlineLevel());
2261 /// Get the combined style for a range - if any attribute is different within the range,
2262 /// that attribute is not present within the flags.
2263 /// *** Note that this is not recursive, and so assumes that content inside a paragraph is not itself
2265 bool wxRichTextParagraphLayoutBox::GetStyleForRange(const wxRichTextRange
& range
, wxTextAttr
& style
)
2267 style
= wxTextAttr();
2269 // The attributes that aren't valid because of multiple styles within the range
2270 long multipleStyleAttributes
= 0;
2271 int multipleTextEffectAttributes
= 0;
2273 wxRichTextObjectList::compatibility_iterator node
= GetChildren().GetFirst();
2276 wxRichTextParagraph
* para
= (wxRichTextParagraph
*) node
->GetData();
2277 if (!(para
->GetRange().GetStart() > range
.GetEnd() || para
->GetRange().GetEnd() < range
.GetStart()))
2279 if (para
->GetChildren().GetCount() == 0)
2281 wxTextAttr paraStyle
= para
->GetCombinedAttributes();
2283 CollectStyle(style
, paraStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
);
2287 wxRichTextRange
paraRange(para
->GetRange());
2288 paraRange
.LimitTo(range
);
2290 // First collect paragraph attributes only
2291 wxTextAttr paraStyle
= para
->GetCombinedAttributes();
2292 paraStyle
.SetFlags(paraStyle
.GetFlags() & wxTEXT_ATTR_PARAGRAPH
);
2293 CollectStyle(style
, paraStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
);
2295 wxRichTextObjectList::compatibility_iterator childNode
= para
->GetChildren().GetFirst();
2299 wxRichTextObject
* child
= childNode
->GetData();
2300 if (!(child
->GetRange().GetStart() > range
.GetEnd() || child
->GetRange().GetEnd() < range
.GetStart()))
2302 wxTextAttr childStyle
= para
->GetCombinedAttributes(child
->GetAttributes());
2304 // Now collect character attributes only
2305 childStyle
.SetFlags(childStyle
.GetFlags() & wxTEXT_ATTR_CHARACTER
);
2307 CollectStyle(style
, childStyle
, multipleStyleAttributes
, multipleTextEffectAttributes
);
2310 childNode
= childNode
->GetNext();
2314 node
= node
->GetNext();
2319 /// Set default style
2320 bool wxRichTextParagraphLayoutBox::SetDefaultStyle(const wxTextAttr
& style
)
2322 m_defaultAttributes
= style
;
2326 /// Test if this whole range has character attributes of the specified kind. If any
2327 /// of the attributes are different within the range, the test fails. You
2328 /// can use this to implement, for example, bold button updating. style must have
2329 /// flags indicating which attributes are of interest.
2330 bool wxRichTextParagraphLayoutBox::HasCharacterAttributes(const wxRichTextRange
& range
, const wxTextAttr
& style
) const
2333 int matchingCount
= 0;
2335 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2338 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2339 wxASSERT (para
!= NULL
);
2343 // Stop searching if we're beyond the range of interest
2344 if (para
->GetRange().GetStart() > range
.GetEnd())
2345 return foundCount
== matchingCount
;
2347 if (!para
->GetRange().IsOutside(range
))
2349 wxRichTextObjectList::compatibility_iterator node2
= para
->GetChildren().GetFirst();
2353 wxRichTextObject
* child
= node2
->GetData();
2354 if (!child
->GetRange().IsOutside(range
) && child
->IsKindOf(CLASSINFO(wxRichTextPlainText
)))
2357 wxTextAttr textAttr
= para
->GetCombinedAttributes(child
->GetAttributes());
2359 if (wxTextAttrEqPartial(textAttr
, style
, style
.GetFlags()))
2363 node2
= node2
->GetNext();
2368 node
= node
->GetNext();
2371 return foundCount
== matchingCount
;
2374 /// Test if this whole range has paragraph attributes of the specified kind. If any
2375 /// of the attributes are different within the range, the test fails. You
2376 /// can use this to implement, for example, centering button updating. style must have
2377 /// flags indicating which attributes are of interest.
2378 bool wxRichTextParagraphLayoutBox::HasParagraphAttributes(const wxRichTextRange
& range
, const wxTextAttr
& style
) const
2381 int matchingCount
= 0;
2383 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2386 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2387 wxASSERT (para
!= NULL
);
2391 // Stop searching if we're beyond the range of interest
2392 if (para
->GetRange().GetStart() > range
.GetEnd())
2393 return foundCount
== matchingCount
;
2395 if (!para
->GetRange().IsOutside(range
))
2397 wxTextAttr textAttr
= GetAttributes();
2398 // Apply the paragraph style
2399 wxRichTextApplyStyle(textAttr
, para
->GetAttributes());
2402 if (wxTextAttrEqPartial(textAttr
, style
, style
.GetFlags()))
2407 node
= node
->GetNext();
2409 return foundCount
== matchingCount
;
2412 void wxRichTextParagraphLayoutBox::Clear()
2417 void wxRichTextParagraphLayoutBox::Reset()
2421 AddParagraph(wxEmptyString
);
2423 Invalidate(wxRICHTEXT_ALL
);
2426 /// Invalidate the buffer. With no argument, invalidates whole buffer.
2427 void wxRichTextParagraphLayoutBox::Invalidate(const wxRichTextRange
& invalidRange
)
2431 if (invalidRange
== wxRICHTEXT_ALL
)
2433 m_invalidRange
= wxRICHTEXT_ALL
;
2437 // Already invalidating everything
2438 if (m_invalidRange
== wxRICHTEXT_ALL
)
2441 if ((invalidRange
.GetStart() < m_invalidRange
.GetStart()) || m_invalidRange
.GetStart() == -1)
2442 m_invalidRange
.SetStart(invalidRange
.GetStart());
2443 if (invalidRange
.GetEnd() > m_invalidRange
.GetEnd())
2444 m_invalidRange
.SetEnd(invalidRange
.GetEnd());
2447 /// Get invalid range, rounding to entire paragraphs if argument is true.
2448 wxRichTextRange
wxRichTextParagraphLayoutBox::GetInvalidRange(bool wholeParagraphs
) const
2450 if (m_invalidRange
== wxRICHTEXT_ALL
|| m_invalidRange
== wxRICHTEXT_NONE
)
2451 return m_invalidRange
;
2453 wxRichTextRange range
= m_invalidRange
;
2455 if (wholeParagraphs
)
2457 wxRichTextParagraph
* para1
= GetParagraphAtPosition(range
.GetStart());
2458 wxRichTextParagraph
* para2
= GetParagraphAtPosition(range
.GetEnd());
2460 range
.SetStart(para1
->GetRange().GetStart());
2462 range
.SetEnd(para2
->GetRange().GetEnd());
2467 /// Apply the style sheet to the buffer, for example if the styles have changed.
2468 bool wxRichTextParagraphLayoutBox::ApplyStyleSheet(wxRichTextStyleSheet
* styleSheet
)
2470 wxASSERT(styleSheet
!= NULL
);
2476 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2479 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2480 wxASSERT (para
!= NULL
);
2484 // Combine paragraph and list styles. If there is a list style in the original attributes,
2485 // the current indentation overrides anything else and is used to find the item indentation.
2486 // Also, for applying paragraph styles, consider having 2 modes: (1) we merge with what we have,
2487 // thereby taking into account all user changes, (2) reset the style completely (except for indentation/list
2488 // exception as above).
2489 // Problem: when changing from one list style to another, there's a danger that the level info will get lost.
2490 // So when changing a list style interactively, could retrieve level based on current style, then
2491 // set appropriate indent and apply new style.
2493 if (!para
->GetAttributes().GetParagraphStyleName().IsEmpty() && !para
->GetAttributes().GetListStyleName().IsEmpty())
2495 int currentIndent
= para
->GetAttributes().GetLeftIndent();
2497 wxRichTextParagraphStyleDefinition
* paraDef
= styleSheet
->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
2498 wxRichTextListStyleDefinition
* listDef
= styleSheet
->FindListStyle(para
->GetAttributes().GetListStyleName());
2499 if (paraDef
&& !listDef
)
2501 para
->GetAttributes() = paraDef
->GetStyleMergedWithBase(styleSheet
);
2504 else if (listDef
&& !paraDef
)
2506 // Set overall style defined for the list style definition
2507 para
->GetAttributes() = listDef
->GetStyleMergedWithBase(styleSheet
);
2509 // Apply the style for this level
2510 wxRichTextApplyStyle(para
->GetAttributes(), * listDef
->GetLevelAttributes(listDef
->FindLevelForIndent(currentIndent
)));
2513 else if (listDef
&& paraDef
)
2515 // Combines overall list style, style for level, and paragraph style
2516 para
->GetAttributes() = listDef
->CombineWithParagraphStyle(currentIndent
, paraDef
->GetStyleMergedWithBase(styleSheet
));
2520 else if (para
->GetAttributes().GetParagraphStyleName().IsEmpty() && !para
->GetAttributes().GetListStyleName().IsEmpty())
2522 int currentIndent
= para
->GetAttributes().GetLeftIndent();
2524 wxRichTextListStyleDefinition
* listDef
= styleSheet
->FindListStyle(para
->GetAttributes().GetListStyleName());
2526 // Overall list definition style
2527 para
->GetAttributes() = listDef
->GetStyleMergedWithBase(styleSheet
);
2529 // Style for this level
2530 wxRichTextApplyStyle(para
->GetAttributes(), * listDef
->GetLevelAttributes(listDef
->FindLevelForIndent(currentIndent
)));
2534 else if (!para
->GetAttributes().GetParagraphStyleName().IsEmpty() && para
->GetAttributes().GetListStyleName().IsEmpty())
2536 wxRichTextParagraphStyleDefinition
* def
= styleSheet
->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
2539 para
->GetAttributes() = def
->GetStyleMergedWithBase(styleSheet
);
2545 node
= node
->GetNext();
2547 return foundCount
!= 0;
2551 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2553 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2555 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
2556 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2557 bool specifyLevel
= ((flags
& wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL
) != 0);
2558 bool renumber
= ((flags
& wxRICHTEXT_SETSTYLE_RENUMBER
) != 0);
2560 // Current number, if numbering
2563 wxASSERT (!specifyLevel
|| (specifyLevel
&& (specifiedLevel
>= 0)));
2565 // If we are associated with a control, make undoable; otherwise, apply immediately
2568 bool haveControl
= (GetRichTextCtrl() != NULL
);
2570 wxRichTextAction
* action
= NULL
;
2572 if (haveControl
&& withUndo
)
2574 action
= new wxRichTextAction(NULL
, _("Change List Style"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2575 action
->SetRange(range
);
2576 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2579 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2582 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2583 wxASSERT (para
!= NULL
);
2585 if (para
&& para
->GetChildCount() > 0)
2587 // Stop searching if we're beyond the range of interest
2588 if (para
->GetRange().GetStart() > range
.GetEnd())
2591 if (!para
->GetRange().IsOutside(range
))
2593 // We'll be using a copy of the paragraph to make style changes,
2594 // not updating the buffer directly.
2595 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
2597 if (haveControl
&& withUndo
)
2599 newPara
= new wxRichTextParagraph(*para
);
2600 action
->GetNewParagraphs().AppendChild(newPara
);
2602 // Also store the old ones for Undo
2603 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
2610 int thisIndent
= newPara
->GetAttributes().GetLeftIndent();
2611 int thisLevel
= specifyLevel
? specifiedLevel
: def
->FindLevelForIndent(thisIndent
);
2613 // How is numbering going to work?
2614 // If we are renumbering, or numbering for the first time, we need to keep
2615 // track of the number for each level. But we might be simply applying a different
2617 // In Word, applying a style to several paragraphs, even if at different levels,
2618 // reverts the level back to the same one. So we could do the same here.
2619 // Renumbering will need to be done when we promote/demote a paragraph.
2621 // Apply the overall list style, and item style for this level
2622 wxTextAttr
listStyle(def
->GetCombinedStyleForLevel(thisLevel
, styleSheet
));
2623 wxRichTextApplyStyle(newPara
->GetAttributes(), listStyle
);
2625 // Now we need to do numbering
2628 newPara
->GetAttributes().SetBulletNumber(n
);
2633 else if (!newPara
->GetAttributes().GetListStyleName().IsEmpty())
2635 // if def is NULL, remove list style, applying any associated paragraph style
2636 // to restore the attributes
2638 newPara
->GetAttributes().SetListStyleName(wxEmptyString
);
2639 newPara
->GetAttributes().SetLeftIndent(0, 0);
2640 newPara
->GetAttributes().SetBulletText(wxEmptyString
);
2642 // Eliminate the main list-related attributes
2643 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
);
2645 if (styleSheet
&& !newPara
->GetAttributes().GetParagraphStyleName().IsEmpty())
2647 wxRichTextParagraphStyleDefinition
* def
= styleSheet
->FindParagraphStyle(newPara
->GetAttributes().GetParagraphStyleName());
2650 newPara
->GetAttributes() = def
->GetStyleMergedWithBase(styleSheet
);
2657 node
= node
->GetNext();
2660 // Do action, or delay it until end of batch.
2661 if (haveControl
&& withUndo
)
2662 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
2667 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int startFrom
, int specifiedLevel
)
2669 if (GetStyleSheet())
2671 wxRichTextListStyleDefinition
* def
= GetStyleSheet()->FindListStyle(defName
);
2673 return SetListStyle(range
, def
, flags
, startFrom
, specifiedLevel
);
2678 /// Clear list for given range
2679 bool wxRichTextParagraphLayoutBox::ClearListStyle(const wxRichTextRange
& range
, int flags
)
2681 return SetListStyle(range
, NULL
, flags
);
2684 /// Number/renumber any list elements in the given range
2685 bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2687 return DoNumberList(range
, range
, 0, def
, flags
, startFrom
, specifiedLevel
);
2690 /// Number/renumber any list elements in the given range. Also do promotion or demotion of items, if specified
2691 bool wxRichTextParagraphLayoutBox::DoNumberList(const wxRichTextRange
& range
, const wxRichTextRange
& promotionRange
, int promoteBy
,
2692 wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
2694 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2696 bool withUndo
= ((flags
& wxRICHTEXT_SETSTYLE_WITH_UNDO
) != 0);
2697 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2699 bool specifyLevel
= ((flags
& wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL
) != 0);
2702 bool renumber
= ((flags
& wxRICHTEXT_SETSTYLE_RENUMBER
) != 0);
2704 // Max number of levels
2705 const int maxLevels
= 10;
2707 // The level we're looking at now
2708 int currentLevel
= -1;
2710 // The item number for each level
2711 int levels
[maxLevels
];
2714 // Reset all numbering
2715 for (i
= 0; i
< maxLevels
; i
++)
2717 if (startFrom
!= -1)
2718 levels
[i
] = startFrom
-1;
2719 else if (renumber
) // start again
2722 levels
[i
] = -1; // start from the number we found, if any
2725 wxASSERT(!specifyLevel
|| (specifyLevel
&& (specifiedLevel
>= 0)));
2727 // If we are associated with a control, make undoable; otherwise, apply immediately
2730 bool haveControl
= (GetRichTextCtrl() != NULL
);
2732 wxRichTextAction
* action
= NULL
;
2734 if (haveControl
&& withUndo
)
2736 action
= new wxRichTextAction(NULL
, _("Renumber List"), wxRICHTEXT_CHANGE_STYLE
, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2737 action
->SetRange(range
);
2738 action
->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2741 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
2744 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
2745 wxASSERT (para
!= NULL
);
2747 if (para
&& para
->GetChildCount() > 0)
2749 // Stop searching if we're beyond the range of interest
2750 if (para
->GetRange().GetStart() > range
.GetEnd())
2753 if (!para
->GetRange().IsOutside(range
))
2755 // We'll be using a copy of the paragraph to make style changes,
2756 // not updating the buffer directly.
2757 wxRichTextParagraph
* newPara
wxDUMMY_INITIALIZE(NULL
);
2759 if (haveControl
&& withUndo
)
2761 newPara
= new wxRichTextParagraph(*para
);
2762 action
->GetNewParagraphs().AppendChild(newPara
);
2764 // Also store the old ones for Undo
2765 action
->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para
));
2770 wxRichTextListStyleDefinition
* defToUse
= def
;
2773 if (styleSheet
&& !newPara
->GetAttributes().GetListStyleName().IsEmpty())
2774 defToUse
= styleSheet
->FindListStyle(newPara
->GetAttributes().GetListStyleName());
2779 int thisIndent
= newPara
->GetAttributes().GetLeftIndent();
2780 int thisLevel
= defToUse
->FindLevelForIndent(thisIndent
);
2782 // If we've specified a level to apply to all, change the level.
2783 if (specifiedLevel
!= -1)
2784 thisLevel
= specifiedLevel
;
2786 // Do promotion if specified
2787 if ((promoteBy
!= 0) && !para
->GetRange().IsOutside(promotionRange
))
2789 thisLevel
= thisLevel
- promoteBy
;
2796 // Apply the overall list style, and item style for this level
2797 wxTextAttr
listStyle(defToUse
->GetCombinedStyleForLevel(thisLevel
, styleSheet
));
2798 wxRichTextApplyStyle(newPara
->GetAttributes(), listStyle
);
2800 // OK, we've (re)applied the style, now let's get the numbering right.
2802 if (currentLevel
== -1)
2803 currentLevel
= thisLevel
;
2805 // Same level as before, do nothing except increment level's number afterwards
2806 if (currentLevel
== thisLevel
)
2809 // A deeper level: start renumbering all levels after current level
2810 else if (thisLevel
> currentLevel
)
2812 for (i
= currentLevel
+1; i
<= thisLevel
; i
++)
2816 currentLevel
= thisLevel
;
2818 else if (thisLevel
< currentLevel
)
2820 currentLevel
= thisLevel
;
2823 // Use the current numbering if -1 and we have a bullet number already
2824 if (levels
[currentLevel
] == -1)
2826 if (newPara
->GetAttributes().HasBulletNumber())
2827 levels
[currentLevel
] = newPara
->GetAttributes().GetBulletNumber();
2829 levels
[currentLevel
] = 1;
2833 levels
[currentLevel
] ++;
2836 newPara
->GetAttributes().SetBulletNumber(levels
[currentLevel
]);
2838 // Create the bullet text if an outline list
2839 if (listStyle
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
)
2842 for (i
= 0; i
<= currentLevel
; i
++)
2844 if (!text
.IsEmpty())
2846 text
+= wxString::Format(wxT("%d"), levels
[i
]);
2848 newPara
->GetAttributes().SetBulletText(text
);
2854 node
= node
->GetNext();
2857 // Do action, or delay it until end of batch.
2858 if (haveControl
&& withUndo
)
2859 GetRichTextCtrl()->GetBuffer().SubmitAction(action
);
2864 bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int startFrom
, int specifiedLevel
)
2866 if (GetStyleSheet())
2868 wxRichTextListStyleDefinition
* def
= NULL
;
2869 if (!defName
.IsEmpty())
2870 def
= GetStyleSheet()->FindListStyle(defName
);
2871 return NumberList(range
, def
, flags
, startFrom
, specifiedLevel
);
2876 /// Promote the list items within the given range. promoteBy can be a positive or negative number, e.g. 1 or -1
2877 bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy
, const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int specifiedLevel
)
2880 // One strategy is to first work out the range within which renumbering must occur. Then could pass these two ranges
2881 // to NumberList with a flag indicating promotion is required within one of the ranges.
2882 // Find first and last paragraphs in range. Then for first, calculate new indentation and look back until we find
2883 // a paragraph that either has no list style, or has one that is different or whose indentation is less.
2884 // We start renumbering from the para after that different para we found. We specify that the numbering of that
2885 // list position will start from 1.
2886 // Similarly, we look after the last para in the promote range for an indentation that is less (or no list style).
2887 // We can end the renumbering at this point.
2889 // For now, only renumber within the promotion range.
2891 return DoNumberList(range
, range
, promoteBy
, def
, flags
, 1, specifiedLevel
);
2894 bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy
, const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int specifiedLevel
)
2896 if (GetStyleSheet())
2898 wxRichTextListStyleDefinition
* def
= NULL
;
2899 if (!defName
.IsEmpty())
2900 def
= GetStyleSheet()->FindListStyle(defName
);
2901 return PromoteList(promoteBy
, range
, def
, flags
, specifiedLevel
);
2906 /// Fills in the attributes for numbering a paragraph after previousParagraph. It also finds the
2907 /// position of the paragraph that it had to start looking from.
2908 bool wxRichTextParagraphLayoutBox::FindNextParagraphNumber(wxRichTextParagraph
* previousParagraph
, wxTextAttr
& attr
) const
2910 if (!previousParagraph
->GetAttributes().HasFlag(wxTEXT_ATTR_BULLET_STYLE
) || previousParagraph
->GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE
)
2913 wxRichTextStyleSheet
* styleSheet
= GetStyleSheet();
2914 if (styleSheet
&& !previousParagraph
->GetAttributes().GetListStyleName().IsEmpty())
2916 wxRichTextListStyleDefinition
* def
= styleSheet
->FindListStyle(previousParagraph
->GetAttributes().GetListStyleName());
2919 // int thisIndent = previousParagraph->GetAttributes().GetLeftIndent();
2920 // int thisLevel = def->FindLevelForIndent(thisIndent);
2922 bool isOutline
= (previousParagraph
->GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
) != 0;
2924 attr
.SetFlags(previousParagraph
->GetAttributes().GetFlags() & (wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_BULLET_NUMBER
|wxTEXT_ATTR_BULLET_TEXT
|wxTEXT_ATTR_BULLET_NAME
));
2925 if (previousParagraph
->GetAttributes().HasBulletName())
2926 attr
.SetBulletName(previousParagraph
->GetAttributes().GetBulletName());
2927 attr
.SetBulletStyle(previousParagraph
->GetAttributes().GetBulletStyle());
2928 attr
.SetListStyleName(previousParagraph
->GetAttributes().GetListStyleName());
2930 int nextNumber
= previousParagraph
->GetAttributes().GetBulletNumber() + 1;
2931 attr
.SetBulletNumber(nextNumber
);
2935 wxString text
= previousParagraph
->GetAttributes().GetBulletText();
2936 if (!text
.IsEmpty())
2938 int pos
= text
.Find(wxT('.'), true);
2939 if (pos
!= wxNOT_FOUND
)
2941 text
= text
.Mid(0, text
.Length() - pos
- 1);
2944 text
= wxEmptyString
;
2945 if (!text
.IsEmpty())
2947 text
+= wxString::Format(wxT("%d"), nextNumber
);
2948 attr
.SetBulletText(text
);
2962 * wxRichTextParagraph
2963 * This object represents a single paragraph (or in a straight text editor, a line).
2966 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraph
, wxRichTextBox
)
2968 wxArrayInt
wxRichTextParagraph::sm_defaultTabs
;
2970 wxRichTextParagraph::wxRichTextParagraph(wxRichTextObject
* parent
, wxTextAttr
* style
):
2971 wxRichTextBox(parent
)
2974 SetAttributes(*style
);
2977 wxRichTextParagraph::wxRichTextParagraph(const wxString
& text
, wxRichTextObject
* parent
, wxTextAttr
* paraStyle
, wxTextAttr
* charStyle
):
2978 wxRichTextBox(parent
)
2981 SetAttributes(*paraStyle
);
2983 AppendChild(new wxRichTextPlainText(text
, this, charStyle
));
2986 wxRichTextParagraph::~wxRichTextParagraph()
2992 bool wxRichTextParagraph::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& WXUNUSED(rect
), int WXUNUSED(descent
), int style
)
2994 wxTextAttr attr
= GetCombinedAttributes();
2996 // Draw the bullet, if any
2997 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
2999 if (attr
.GetLeftSubIndent() != 0)
3001 int spaceBeforePara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingBefore());
3002 int leftIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftIndent());
3004 wxTextAttr
bulletAttr(GetCombinedAttributes());
3006 // Combine with the font of the first piece of content, if one is specified
3007 if (GetChildren().GetCount() > 0)
3009 wxRichTextObject
* firstObj
= (wxRichTextObject
*) GetChildren().GetFirst()->GetData();
3010 if (firstObj
->GetAttributes().HasFont())
3012 wxRichTextApplyStyle(bulletAttr
, firstObj
->GetAttributes());
3016 // Get line height from first line, if any
3017 wxRichTextLine
* line
= m_cachedLines
.GetFirst() ? (wxRichTextLine
* ) m_cachedLines
.GetFirst()->GetData() : (wxRichTextLine
*) NULL
;
3020 int lineHeight
wxDUMMY_INITIALIZE(0);
3023 lineHeight
= line
->GetSize().y
;
3024 linePos
= line
->GetPosition() + GetPosition();
3029 if (bulletAttr
.HasFont() && GetBuffer())
3030 font
= GetBuffer()->GetFontTable().FindFont(bulletAttr
);
3032 font
= (*wxNORMAL_FONT
);
3034 wxCheckSetFont(dc
, font
);
3036 lineHeight
= dc
.GetCharHeight();
3037 linePos
= GetPosition();
3038 linePos
.y
+= spaceBeforePara
;
3041 wxRect
bulletRect(GetPosition().x
+ leftIndent
, linePos
.y
, linePos
.x
- (GetPosition().x
+ leftIndent
), lineHeight
);
3043 if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP
)
3045 if (wxRichTextBuffer::GetRenderer())
3046 wxRichTextBuffer::GetRenderer()->DrawBitmapBullet(this, dc
, bulletAttr
, bulletRect
);
3048 else if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_STANDARD
)
3050 if (wxRichTextBuffer::GetRenderer())
3051 wxRichTextBuffer::GetRenderer()->DrawStandardBullet(this, dc
, bulletAttr
, bulletRect
);
3055 wxString bulletText
= GetBulletText();
3057 if (!bulletText
.empty() && wxRichTextBuffer::GetRenderer())
3058 wxRichTextBuffer::GetRenderer()->DrawTextBullet(this, dc
, bulletAttr
, bulletRect
, bulletText
);
3063 // Draw the range for each line, one object at a time.
3065 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3068 wxRichTextLine
* line
= node
->GetData();
3069 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3071 int maxDescent
= line
->GetDescent();
3073 // Lines are specified relative to the paragraph
3075 wxPoint linePosition
= line
->GetPosition() + GetPosition();
3076 wxPoint objectPosition
= linePosition
;
3078 // Loop through objects until we get to the one within range
3079 wxRichTextObjectList::compatibility_iterator node2
= m_children
.GetFirst();
3082 wxRichTextObject
* child
= node2
->GetData();
3084 if (!child
->GetRange().IsOutside(lineRange
) && !lineRange
.IsOutside(range
))
3086 // Draw this part of the line at the correct position
3087 wxRichTextRange
objectRange(child
->GetRange());
3088 objectRange
.LimitTo(lineRange
);
3092 child
->GetRangeSize(objectRange
, objectSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, objectPosition
);
3094 // Use the child object's width, but the whole line's height
3095 wxRect
childRect(objectPosition
, wxSize(objectSize
.x
, line
->GetSize().y
));
3096 child
->Draw(dc
, objectRange
, selectionRange
, childRect
, maxDescent
, style
);
3098 objectPosition
.x
+= objectSize
.x
;
3100 else if (child
->GetRange().GetStart() > lineRange
.GetEnd())
3101 // Can break out of inner loop now since we've passed this line's range
3104 node2
= node2
->GetNext();
3107 node
= node
->GetNext();
3113 /// Lay the item out
3114 bool wxRichTextParagraph::Layout(wxDC
& dc
, const wxRect
& rect
, int style
)
3116 wxTextAttr attr
= GetCombinedAttributes();
3120 // Increase the size of the paragraph due to spacing
3121 int spaceBeforePara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingBefore());
3122 int spaceAfterPara
= ConvertTenthsMMToPixels(dc
, attr
.GetParagraphSpacingAfter());
3123 int leftIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftIndent());
3124 int leftSubIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetLeftSubIndent());
3125 int rightIndent
= ConvertTenthsMMToPixels(dc
, attr
.GetRightIndent());
3127 int lineSpacing
= 0;
3129 // Let's assume line spacing of 10 is normal, 15 is 1.5, 20 is 2, etc.
3130 if (attr
.GetLineSpacing() != 10 && GetBuffer())
3132 wxFont
font(GetBuffer()->GetFontTable().FindFont(attr
));
3133 wxCheckSetFont(dc
, font
);
3134 lineSpacing
= (ConvertTenthsMMToPixels(dc
, dc
.GetCharHeight()) * attr
.GetLineSpacing())/10;
3137 // Available space for text on each line differs.
3138 int availableTextSpaceFirstLine
= rect
.GetWidth() - leftIndent
- rightIndent
;
3140 // Bullets start the text at the same position as subsequent lines
3141 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3142 availableTextSpaceFirstLine
-= leftSubIndent
;
3144 int availableTextSpaceSubsequentLines
= rect
.GetWidth() - leftIndent
- rightIndent
- leftSubIndent
;
3146 // Start position for each line relative to the paragraph
3147 int startPositionFirstLine
= leftIndent
;
3148 int startPositionSubsequentLines
= leftIndent
+ leftSubIndent
;
3150 // If we have a bullet in this paragraph, the start position for the first line's text
3151 // is actually leftIndent + leftSubIndent.
3152 if (attr
.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE
)
3153 startPositionFirstLine
= startPositionSubsequentLines
;
3155 long lastEndPos
= GetRange().GetStart()-1;
3156 long lastCompletedEndPos
= lastEndPos
;
3158 int currentWidth
= 0;
3159 SetPosition(rect
.GetPosition());
3161 wxPoint
currentPosition(0, spaceBeforePara
); // We will calculate lines relative to paragraph
3168 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3171 wxRichTextObject
* child
= node
->GetData();
3173 child
->SetCachedSize(wxDefaultSize
);
3174 child
->Layout(dc
, rect
, style
);
3176 node
= node
->GetNext();
3181 // We may need to go back to a previous child, in which case create the new line,
3182 // find the child corresponding to the start position of the string, and
3185 node
= m_children
.GetFirst();
3188 wxRichTextObject
* child
= node
->GetData();
3190 // If this is e.g. a composite text box, it will need to be laid out itself.
3191 // But if just a text fragment or image, for example, this will
3192 // do nothing. NB: won't we need to set the position after layout?
3193 // since for example if position is dependent on vertical line size, we
3194 // can't tell the position until the size is determined. So possibly introduce
3195 // another layout phase.
3197 // Available width depends on whether we're on the first or subsequent lines
3198 int availableSpaceForText
= (lineCount
== 0 ? availableTextSpaceFirstLine
: availableTextSpaceSubsequentLines
);
3200 currentPosition
.x
= (lineCount
== 0 ? startPositionFirstLine
: startPositionSubsequentLines
);
3202 // We may only be looking at part of a child, if we searched back for wrapping
3203 // and found a suitable point some way into the child. So get the size for the fragment
3206 long nextBreakPos
= GetFirstLineBreakPosition(lastEndPos
+1);
3207 long lastPosToUse
= child
->GetRange().GetEnd();
3208 bool lineBreakInThisObject
= (nextBreakPos
> -1 && nextBreakPos
<= child
->GetRange().GetEnd());
3210 if (lineBreakInThisObject
)
3211 lastPosToUse
= nextBreakPos
;
3214 int childDescent
= 0;
3216 if ((nextBreakPos
== -1) && (lastEndPos
== child
->GetRange().GetStart() - 1)) // i.e. we want to get the whole thing
3218 childSize
= child
->GetCachedSize();
3219 childDescent
= child
->GetDescent();
3222 GetRangeSize(wxRichTextRange(lastEndPos
+1, lastPosToUse
), childSize
, childDescent
, dc
, wxRICHTEXT_UNFORMATTED
, rect
.GetPosition());
3225 // 1) There was a line break BEFORE the natural break
3226 // 2) There was a line break AFTER the natural break
3227 // 3) The child still fits (carry on)
3229 if ((lineBreakInThisObject
&& (childSize
.x
+ currentWidth
<= availableSpaceForText
)) ||
3230 (childSize
.x
+ currentWidth
> availableSpaceForText
))
3232 long wrapPosition
= 0;
3234 // Find a place to wrap. This may walk back to previous children,
3235 // for example if a word spans several objects.
3236 if (!FindWrapPosition(wxRichTextRange(lastCompletedEndPos
+1, child
->GetRange().GetEnd()), dc
, availableSpaceForText
, wrapPosition
))
3238 // If the function failed, just cut it off at the end of this child.
3239 wrapPosition
= child
->GetRange().GetEnd();
3242 // FindWrapPosition can still return a value that will put us in an endless wrapping loop
3243 if (wrapPosition
<= lastCompletedEndPos
)
3244 wrapPosition
= wxMax(lastCompletedEndPos
+1,child
->GetRange().GetEnd());
3246 // wxLogDebug(wxT("Split at %ld"), wrapPosition);
3248 // Let's find the actual size of the current line now
3250 wxRichTextRange
actualRange(lastCompletedEndPos
+1, wrapPosition
);
3251 GetRangeSize(actualRange
, actualSize
, childDescent
, dc
, wxRICHTEXT_UNFORMATTED
);
3252 currentWidth
= actualSize
.x
;
3253 lineHeight
= wxMax(lineHeight
, actualSize
.y
);
3254 maxDescent
= wxMax(childDescent
, maxDescent
);
3257 wxRichTextLine
* line
= AllocateLine(lineCount
);
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()));
3261 line
->SetPosition(currentPosition
);
3262 line
->SetSize(wxSize(currentWidth
, lineHeight
));
3263 line
->SetDescent(maxDescent
);
3265 // Now move down a line. TODO: add margins, spacing
3266 currentPosition
.y
+= lineHeight
;
3267 currentPosition
.y
+= lineSpacing
;
3270 maxWidth
= wxMax(maxWidth
, currentWidth
);
3274 // TODO: account for zero-length objects, such as fields
3275 wxASSERT(wrapPosition
> lastCompletedEndPos
);
3277 lastEndPos
= wrapPosition
;
3278 lastCompletedEndPos
= lastEndPos
;
3282 // May need to set the node back to a previous one, due to searching back in wrapping
3283 wxRichTextObject
* childAfterWrapPosition
= FindObjectAtPosition(wrapPosition
+1);
3284 if (childAfterWrapPosition
)
3285 node
= m_children
.Find(childAfterWrapPosition
);
3287 node
= node
->GetNext();
3291 // We still fit, so don't add a line, and keep going
3292 currentWidth
+= childSize
.x
;
3293 lineHeight
= wxMax(lineHeight
, childSize
.y
);
3294 maxDescent
= wxMax(childDescent
, maxDescent
);
3296 maxWidth
= wxMax(maxWidth
, currentWidth
);
3297 lastEndPos
= child
->GetRange().GetEnd();
3299 node
= node
->GetNext();
3303 // Add the last line - it's the current pos -> last para pos
3304 // Substract -1 because the last position is always the end-paragraph position.
3305 if (lastCompletedEndPos
<= GetRange().GetEnd()-1)
3307 currentPosition
.x
= (lineCount
== 0 ? startPositionFirstLine
: startPositionSubsequentLines
);
3309 wxRichTextLine
* line
= AllocateLine(lineCount
);
3311 wxRichTextRange
actualRange(lastCompletedEndPos
+1, GetRange().GetEnd()-1);
3313 // Set relative range so we won't have to change line ranges when paragraphs are moved
3314 line
->SetRange(wxRichTextRange(actualRange
.GetStart() - GetRange().GetStart(), actualRange
.GetEnd() - GetRange().GetStart()));
3316 line
->SetPosition(currentPosition
);
3318 if (lineHeight
== 0 && GetBuffer())
3320 wxFont
font(GetBuffer()->GetFontTable().FindFont(attr
));
3321 wxCheckSetFont(dc
, font
);
3322 lineHeight
= dc
.GetCharHeight();
3324 if (maxDescent
== 0)
3327 dc
.GetTextExtent(wxT("X"), & w
, &h
, & maxDescent
);
3330 line
->SetSize(wxSize(currentWidth
, lineHeight
));
3331 line
->SetDescent(maxDescent
);
3332 currentPosition
.y
+= lineHeight
;
3333 currentPosition
.y
+= lineSpacing
;
3337 // Remove remaining unused line objects, if any
3338 ClearUnusedLines(lineCount
);
3340 // Apply styles to wrapped lines
3341 ApplyParagraphStyle(attr
, rect
);
3343 SetCachedSize(wxSize(maxWidth
, currentPosition
.y
+ spaceBeforePara
+ spaceAfterPara
));
3350 /// Apply paragraph styles, such as centering, to wrapped lines
3351 void wxRichTextParagraph::ApplyParagraphStyle(const wxTextAttr
& attr
, const wxRect
& rect
)
3353 if (!attr
.HasAlignment())
3356 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3359 wxRichTextLine
* line
= node
->GetData();
3361 wxPoint pos
= line
->GetPosition();
3362 wxSize size
= line
->GetSize();
3364 // centering, right-justification
3365 if (attr
.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_CENTRE
)
3367 pos
.x
= (rect
.GetWidth() - size
.x
)/2 + pos
.x
;
3368 line
->SetPosition(pos
);
3370 else if (attr
.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_RIGHT
)
3372 pos
.x
= pos
.x
+ rect
.GetWidth() - size
.x
;
3373 line
->SetPosition(pos
);
3376 node
= node
->GetNext();
3380 /// Insert text at the given position
3381 bool wxRichTextParagraph::InsertText(long pos
, const wxString
& text
)
3383 wxRichTextObject
* childToUse
= NULL
;
3384 wxRichTextObjectList::compatibility_iterator nodeToUse
= wxRichTextObjectList::compatibility_iterator();
3386 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3389 wxRichTextObject
* child
= node
->GetData();
3390 if (child
->GetRange().Contains(pos
) && child
->GetRange().GetLength() > 0)
3397 node
= node
->GetNext();
3402 wxRichTextPlainText
* textObject
= wxDynamicCast(childToUse
, wxRichTextPlainText
);
3405 int posInString
= pos
- textObject
->GetRange().GetStart();
3407 wxString newText
= textObject
->GetText().Mid(0, posInString
) +
3408 text
+ textObject
->GetText().Mid(posInString
);
3409 textObject
->SetText(newText
);
3411 int textLength
= text
.length();
3413 textObject
->SetRange(wxRichTextRange(textObject
->GetRange().GetStart(),
3414 textObject
->GetRange().GetEnd() + textLength
));
3416 // Increment the end range of subsequent fragments in this paragraph.
3417 // We'll set the paragraph range itself at a higher level.
3419 wxRichTextObjectList::compatibility_iterator node
= nodeToUse
->GetNext();
3422 wxRichTextObject
* child
= node
->GetData();
3423 child
->SetRange(wxRichTextRange(textObject
->GetRange().GetStart() + textLength
,
3424 textObject
->GetRange().GetEnd() + textLength
));
3426 node
= node
->GetNext();
3433 // TODO: if not a text object, insert at closest position, e.g. in front of it
3439 // Don't pass parent initially to suppress auto-setting of parent range.
3440 // We'll do that at a higher level.
3441 wxRichTextPlainText
* textObject
= new wxRichTextPlainText(text
, this);
3443 AppendChild(textObject
);
3450 void wxRichTextParagraph::Copy(const wxRichTextParagraph
& obj
)
3452 wxRichTextBox::Copy(obj
);
3455 /// Clear the cached lines
3456 void wxRichTextParagraph::ClearLines()
3458 WX_CLEAR_LIST(wxRichTextLineList
, m_cachedLines
);
3461 /// Get/set the object size for the given range. Returns false if the range
3462 /// is invalid for this object.
3463 bool wxRichTextParagraph::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int flags
, wxPoint position
) const
3465 if (!range
.IsWithin(GetRange()))
3468 if (flags
& wxRICHTEXT_UNFORMATTED
)
3470 // Just use unformatted data, assume no line breaks
3471 // TODO: take into account line breaks
3475 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3478 wxRichTextObject
* child
= node
->GetData();
3479 if (!child
->GetRange().IsOutside(range
))
3483 wxRichTextRange rangeToUse
= range
;
3484 rangeToUse
.LimitTo(child
->GetRange());
3485 int childDescent
= 0;
3487 if (child
->GetRangeSize(rangeToUse
, childSize
, childDescent
, dc
, flags
, wxPoint(position
.x
+ sz
.x
, position
.y
)))
3489 sz
.y
= wxMax(sz
.y
, childSize
.y
);
3490 sz
.x
+= childSize
.x
;
3491 descent
= wxMax(descent
, childDescent
);
3495 node
= node
->GetNext();
3501 // Use formatted data, with line breaks
3504 // We're going to loop through each line, and then for each line,
3505 // call GetRangeSize for the fragment that comprises that line.
3506 // Only we have to do that multiple times within the line, because
3507 // the line may be broken into pieces. For now ignore line break commands
3508 // (so we can assume that getting the unformatted size for a fragment
3509 // within a line is the actual size)
3511 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3514 wxRichTextLine
* line
= node
->GetData();
3515 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3516 if (!lineRange
.IsOutside(range
))
3520 wxRichTextObjectList::compatibility_iterator node2
= m_children
.GetFirst();
3523 wxRichTextObject
* child
= node2
->GetData();
3525 if (!child
->GetRange().IsOutside(lineRange
))
3527 wxRichTextRange rangeToUse
= lineRange
;
3528 rangeToUse
.LimitTo(child
->GetRange());
3531 int childDescent
= 0;
3532 if (child
->GetRangeSize(rangeToUse
, childSize
, childDescent
, dc
, flags
, wxPoint(position
.x
+ sz
.x
, position
.y
)))
3534 lineSize
.y
= wxMax(lineSize
.y
, childSize
.y
);
3535 lineSize
.x
+= childSize
.x
;
3537 descent
= wxMax(descent
, childDescent
);
3540 node2
= node2
->GetNext();
3543 // Increase size by a line (TODO: paragraph spacing)
3545 sz
.x
= wxMax(sz
.x
, lineSize
.x
);
3547 node
= node
->GetNext();
3554 /// Finds the absolute position and row height for the given character position
3555 bool wxRichTextParagraph::FindPosition(wxDC
& dc
, long index
, wxPoint
& pt
, int* height
, bool forceLineStart
)
3559 wxRichTextLine
* line
= ((wxRichTextParagraphLayoutBox
*)GetParent())->GetLineAtPosition(0);
3561 *height
= line
->GetSize().y
;
3563 *height
= dc
.GetCharHeight();
3565 // -1 means 'the start of the buffer'.
3568 pt
= pt
+ line
->GetPosition();
3573 // The final position in a paragraph is taken to mean the position
3574 // at the start of the next paragraph.
3575 if (index
== GetRange().GetEnd())
3577 wxRichTextParagraphLayoutBox
* parent
= wxDynamicCast(GetParent(), wxRichTextParagraphLayoutBox
);
3578 wxASSERT( parent
!= NULL
);
3580 // Find the height at the next paragraph, if any
3581 wxRichTextLine
* line
= parent
->GetLineAtPosition(index
+ 1);
3584 *height
= line
->GetSize().y
;
3585 pt
= line
->GetAbsolutePosition();
3589 *height
= dc
.GetCharHeight();
3590 int indent
= ConvertTenthsMMToPixels(dc
, m_attributes
.GetLeftIndent());
3591 pt
= wxPoint(indent
, GetCachedSize().y
);
3597 if (index
< GetRange().GetStart() || index
> GetRange().GetEnd())
3600 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3603 wxRichTextLine
* line
= node
->GetData();
3604 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3605 if (index
>= lineRange
.GetStart() && index
<= lineRange
.GetEnd())
3607 // If this is the last point in the line, and we're forcing the
3608 // returned value to be the start of the next line, do the required
3610 if (index
== lineRange
.GetEnd() && forceLineStart
)
3612 if (node
->GetNext())
3614 wxRichTextLine
* nextLine
= node
->GetNext()->GetData();
3615 *height
= nextLine
->GetSize().y
;
3616 pt
= nextLine
->GetAbsolutePosition();
3621 pt
.y
= line
->GetPosition().y
+ GetPosition().y
;
3623 wxRichTextRange
r(lineRange
.GetStart(), index
);
3627 // We find the size of the line up to this point,
3628 // then we can add this size to the line start position and
3629 // paragraph start position to find the actual position.
3631 if (GetRangeSize(r
, rangeSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, line
->GetPosition()+ GetPosition()))
3633 pt
.x
= line
->GetPosition().x
+ GetPosition().x
+ rangeSize
.x
;
3634 *height
= line
->GetSize().y
;
3641 node
= node
->GetNext();
3647 /// Hit-testing: returns a flag indicating hit test details, plus
3648 /// information about position
3649 int wxRichTextParagraph::HitTest(wxDC
& dc
, const wxPoint
& pt
, long& textPosition
)
3651 wxPoint paraPos
= GetPosition();
3653 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetFirst();
3656 wxRichTextLine
* line
= node
->GetData();
3657 wxPoint linePos
= paraPos
+ line
->GetPosition();
3658 wxSize lineSize
= line
->GetSize();
3659 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3661 if (pt
.y
>= linePos
.y
&& pt
.y
<= linePos
.y
+ lineSize
.y
)
3663 if (pt
.x
< linePos
.x
)
3665 textPosition
= lineRange
.GetStart();
3666 return wxRICHTEXT_HITTEST_BEFORE
|wxRICHTEXT_HITTEST_OUTSIDE
;
3668 else if (pt
.x
>= (linePos
.x
+ lineSize
.x
))
3670 textPosition
= lineRange
.GetEnd();
3671 return wxRICHTEXT_HITTEST_AFTER
|wxRICHTEXT_HITTEST_OUTSIDE
;
3676 int lastX
= linePos
.x
;
3677 for (i
= lineRange
.GetStart(); i
<= lineRange
.GetEnd(); i
++)
3682 wxRichTextRange
rangeToUse(lineRange
.GetStart(), i
);
3684 GetRangeSize(rangeToUse
, childSize
, descent
, dc
, wxRICHTEXT_UNFORMATTED
, linePos
);
3686 int nextX
= childSize
.x
+ linePos
.x
;
3688 if (pt
.x
>= lastX
&& pt
.x
<= nextX
)
3692 // So now we know it's between i-1 and i.
3693 // Let's see if we can be more precise about
3694 // which side of the position it's on.
3696 int midPoint
= (nextX
- lastX
)/2 + lastX
;
3697 if (pt
.x
>= midPoint
)
3698 return wxRICHTEXT_HITTEST_AFTER
;
3700 return wxRICHTEXT_HITTEST_BEFORE
;
3710 node
= node
->GetNext();
3713 return wxRICHTEXT_HITTEST_NONE
;
3716 /// Split an object at this position if necessary, and return
3717 /// the previous object, or NULL if inserting at beginning.
3718 wxRichTextObject
* wxRichTextParagraph::SplitAt(long pos
, wxRichTextObject
** previousObject
)
3720 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3723 wxRichTextObject
* child
= node
->GetData();
3725 if (pos
== child
->GetRange().GetStart())
3729 if (node
->GetPrevious())
3730 *previousObject
= node
->GetPrevious()->GetData();
3732 *previousObject
= NULL
;
3738 if (child
->GetRange().Contains(pos
))
3740 // This should create a new object, transferring part of
3741 // the content to the old object and the rest to the new object.
3742 wxRichTextObject
* newObject
= child
->DoSplit(pos
);
3744 // If we couldn't split this object, just insert in front of it.
3747 // Maybe this is an empty string, try the next one
3752 // Insert the new object after 'child'
3753 if (node
->GetNext())
3754 m_children
.Insert(node
->GetNext(), newObject
);
3756 m_children
.Append(newObject
);
3757 newObject
->SetParent(this);
3760 *previousObject
= child
;
3766 node
= node
->GetNext();
3769 *previousObject
= NULL
;
3773 /// Move content to a list from obj on
3774 void wxRichTextParagraph::MoveToList(wxRichTextObject
* obj
, wxList
& list
)
3776 wxRichTextObjectList::compatibility_iterator node
= m_children
.Find(obj
);
3779 wxRichTextObject
* child
= node
->GetData();
3782 wxRichTextObjectList::compatibility_iterator oldNode
= node
;
3784 node
= node
->GetNext();
3786 m_children
.DeleteNode(oldNode
);
3790 /// Add content back from list
3791 void wxRichTextParagraph::MoveFromList(wxList
& list
)
3793 for (wxList::compatibility_iterator node
= list
.GetFirst(); node
; node
= node
->GetNext())
3795 AppendChild((wxRichTextObject
*) node
->GetData());
3800 void wxRichTextParagraph::CalculateRange(long start
, long& end
)
3802 wxRichTextCompositeObject::CalculateRange(start
, end
);
3804 // Add one for end of paragraph
3807 m_range
.SetRange(start
, end
);
3810 /// Find the object at the given position
3811 wxRichTextObject
* wxRichTextParagraph::FindObjectAtPosition(long position
)
3813 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3816 wxRichTextObject
* obj
= node
->GetData();
3817 if (obj
->GetRange().Contains(position
))
3820 node
= node
->GetNext();
3825 /// Get the plain text searching from the start or end of the range.
3826 /// The resulting string may be shorter than the range given.
3827 bool wxRichTextParagraph::GetContiguousPlainText(wxString
& text
, const wxRichTextRange
& range
, bool fromStart
)
3829 text
= wxEmptyString
;
3833 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
3836 wxRichTextObject
* obj
= node
->GetData();
3837 if (!obj
->GetRange().IsOutside(range
))
3839 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
3842 text
+= textObj
->GetTextForRange(range
);
3848 node
= node
->GetNext();
3853 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetLast();
3856 wxRichTextObject
* obj
= node
->GetData();
3857 if (!obj
->GetRange().IsOutside(range
))
3859 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
3862 text
= textObj
->GetTextForRange(range
) + text
;
3868 node
= node
->GetPrevious();
3875 /// Find a suitable wrap position.
3876 bool wxRichTextParagraph::FindWrapPosition(const wxRichTextRange
& range
, wxDC
& dc
, int availableSpace
, long& wrapPosition
)
3878 // Find the first position where the line exceeds the available space.
3880 long breakPosition
= range
.GetEnd();
3882 // Binary chop for speed
3883 long minPos
= range
.GetStart();
3884 long maxPos
= range
.GetEnd();
3887 if (minPos
== maxPos
)
3890 GetRangeSize(wxRichTextRange(range
.GetStart(), minPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
3892 if (sz
.x
> availableSpace
)
3893 breakPosition
= minPos
- 1;
3896 else if ((maxPos
- minPos
) == 1)
3899 GetRangeSize(wxRichTextRange(range
.GetStart(), minPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
3901 if (sz
.x
> availableSpace
)
3902 breakPosition
= minPos
- 1;
3905 GetRangeSize(wxRichTextRange(range
.GetStart(), maxPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
3906 if (sz
.x
> availableSpace
)
3907 breakPosition
= maxPos
-1;
3913 long nextPos
= minPos
+ ((maxPos
- minPos
) / 2);
3916 GetRangeSize(wxRichTextRange(range
.GetStart(), nextPos
), sz
, descent
, dc
, wxRICHTEXT_UNFORMATTED
);
3918 if (sz
.x
> availableSpace
)
3929 // Now we know the last position on the line.
3930 // Let's try to find a word break.
3933 if (GetContiguousPlainText(plainText
, wxRichTextRange(range
.GetStart(), breakPosition
), false))
3935 int newLinePos
= plainText
.Find(wxRichTextLineBreakChar
);
3936 if (newLinePos
!= wxNOT_FOUND
)
3938 breakPosition
= wxMax(0, range
.GetStart() + newLinePos
);
3942 int spacePos
= plainText
.Find(wxT(' '), true);
3943 int tabPos
= plainText
.Find(wxT('\t'), true);
3944 int pos
= wxMax(spacePos
, tabPos
);
3945 if (pos
!= wxNOT_FOUND
)
3947 int positionsFromEndOfString
= plainText
.length() - pos
- 1;
3948 breakPosition
= breakPosition
- positionsFromEndOfString
;
3953 wrapPosition
= breakPosition
;
3958 /// Get the bullet text for this paragraph.
3959 wxString
wxRichTextParagraph::GetBulletText()
3961 if (GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE
||
3962 (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP
))
3963 return wxEmptyString
;
3965 int number
= GetAttributes().GetBulletNumber();
3968 if ((GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ARABIC
) || (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
))
3970 text
.Printf(wxT("%d"), number
);
3972 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER
)
3974 // TODO: Unicode, and also check if number > 26
3975 text
.Printf(wxT("%c"), (wxChar
) (number
+64));
3977 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER
)
3979 // TODO: Unicode, and also check if number > 26
3980 text
.Printf(wxT("%c"), (wxChar
) (number
+96));
3982 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER
)
3984 text
= wxRichTextDecimalToRoman(number
);
3986 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER
)
3988 text
= wxRichTextDecimalToRoman(number
);
3991 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL
)
3993 text
= GetAttributes().GetBulletText();
3996 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE
)
3998 // The outline style relies on the text being computed statically,
3999 // since it depends on other levels points (e.g. 1.2.1.1). So normally the bullet text
4000 // should be stored in the attributes; if not, just use the number for this
4001 // level, as previously computed.
4002 if (!GetAttributes().GetBulletText().IsEmpty())
4003 text
= GetAttributes().GetBulletText();
4006 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PARENTHESES
)
4008 text
= wxT("(") + text
+ wxT(")");
4010 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS
)
4012 text
= text
+ wxT(")");
4015 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PERIOD
)
4023 /// Allocate or reuse a line object
4024 wxRichTextLine
* wxRichTextParagraph::AllocateLine(int pos
)
4026 if (pos
< (int) m_cachedLines
.GetCount())
4028 wxRichTextLine
* line
= m_cachedLines
.Item(pos
)->GetData();
4034 wxRichTextLine
* line
= new wxRichTextLine(this);
4035 m_cachedLines
.Append(line
);
4040 /// Clear remaining unused line objects, if any
4041 bool wxRichTextParagraph::ClearUnusedLines(int lineCount
)
4043 int cachedLineCount
= m_cachedLines
.GetCount();
4044 if ((int) cachedLineCount
> lineCount
)
4046 for (int i
= 0; i
< (int) (cachedLineCount
- lineCount
); i
++)
4048 wxRichTextLineList::compatibility_iterator node
= m_cachedLines
.GetLast();
4049 wxRichTextLine
* line
= node
->GetData();
4050 m_cachedLines
.Erase(node
);
4057 /// Get combined attributes of the base style, paragraph style and character style. We use this to dynamically
4058 /// retrieve the actual style.
4059 wxTextAttr
wxRichTextParagraph::GetCombinedAttributes(const wxTextAttr
& contentStyle
) const
4062 wxRichTextBuffer
* buf
= wxDynamicCast(GetParent(), wxRichTextBuffer
);
4065 attr
= buf
->GetBasicStyle();
4066 wxRichTextApplyStyle(attr
, GetAttributes());
4069 attr
= GetAttributes();
4071 wxRichTextApplyStyle(attr
, contentStyle
);
4075 /// Get combined attributes of the base style and paragraph style.
4076 wxTextAttr
wxRichTextParagraph::GetCombinedAttributes() const
4079 wxRichTextBuffer
* buf
= wxDynamicCast(GetParent(), wxRichTextBuffer
);
4082 attr
= buf
->GetBasicStyle();
4083 wxRichTextApplyStyle(attr
, GetAttributes());
4086 attr
= GetAttributes();
4091 /// Create default tabstop array
4092 void wxRichTextParagraph::InitDefaultTabs()
4094 // create a default tab list at 10 mm each.
4095 for (int i
= 0; i
< 20; ++i
)
4097 sm_defaultTabs
.Add(i
*100);
4101 /// Clear default tabstop array
4102 void wxRichTextParagraph::ClearDefaultTabs()
4104 sm_defaultTabs
.Clear();
4107 /// Get the first position from pos that has a line break character.
4108 long wxRichTextParagraph::GetFirstLineBreakPosition(long pos
)
4110 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetFirst();
4113 wxRichTextObject
* obj
= node
->GetData();
4114 if (pos
>= obj
->GetRange().GetStart() && pos
<= obj
->GetRange().GetEnd())
4116 wxRichTextPlainText
* textObj
= wxDynamicCast(obj
, wxRichTextPlainText
);
4119 long breakPos
= textObj
->GetFirstLineBreakPosition(pos
);
4124 node
= node
->GetNext();
4131 * This object represents a line in a paragraph, and stores
4132 * offsets from the start of the paragraph representing the
4133 * start and end positions of the line.
4136 wxRichTextLine::wxRichTextLine(wxRichTextParagraph
* parent
)
4142 void wxRichTextLine::Init(wxRichTextParagraph
* parent
)
4145 m_range
.SetRange(-1, -1);
4146 m_pos
= wxPoint(0, 0);
4147 m_size
= wxSize(0, 0);
4152 void wxRichTextLine::Copy(const wxRichTextLine
& obj
)
4154 m_range
= obj
.m_range
;
4157 /// Get the absolute object position
4158 wxPoint
wxRichTextLine::GetAbsolutePosition() const
4160 return m_parent
->GetPosition() + m_pos
;
4163 /// Get the absolute range
4164 wxRichTextRange
wxRichTextLine::GetAbsoluteRange() const
4166 wxRichTextRange
range(m_range
.GetStart() + m_parent
->GetRange().GetStart(), 0);
4167 range
.SetEnd(range
.GetStart() + m_range
.GetLength()-1);
4172 * wxRichTextPlainText
4173 * This object represents a single piece of text.
4176 IMPLEMENT_DYNAMIC_CLASS(wxRichTextPlainText
, wxRichTextObject
)
4178 wxRichTextPlainText::wxRichTextPlainText(const wxString
& text
, wxRichTextObject
* parent
, wxTextAttr
* style
):
4179 wxRichTextObject(parent
)
4182 SetAttributes(*style
);
4187 #define USE_KERNING_FIX 1
4189 // If insufficient tabs are defined, this is the tab width used
4190 #define WIDTH_FOR_DEFAULT_TABS 50
4193 bool wxRichTextPlainText::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int descent
, int WXUNUSED(style
))
4195 wxRichTextParagraph
* para
= wxDynamicCast(GetParent(), wxRichTextParagraph
);
4196 wxASSERT (para
!= NULL
);
4198 wxTextAttr
textAttr(para
? para
->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4200 int offset
= GetRange().GetStart();
4202 // Replace line break characters with spaces
4203 wxString str
= m_text
;
4204 wxString toRemove
= wxRichTextLineBreakChar
;
4205 str
.Replace(toRemove
, wxT(" "));
4207 long len
= range
.GetLength();
4208 wxString stringChunk
= str
.Mid(range
.GetStart() - offset
, (size_t) len
);
4209 if (textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
4210 stringChunk
.MakeUpper();
4212 int charHeight
= dc
.GetCharHeight();
4215 int y
= rect
.y
+ (rect
.height
- charHeight
- (descent
- m_descent
));
4217 // Test for the optimized situations where all is selected, or none
4220 wxFont
font(GetBuffer()->GetFontTable().FindFont(textAttr
));
4221 wxCheckSetFont(dc
, font
);
4223 // (a) All selected.
4224 if (selectionRange
.GetStart() <= range
.GetStart() && selectionRange
.GetEnd() >= range
.GetEnd())
4226 DrawTabbedString(dc
, textAttr
, rect
, stringChunk
, x
, y
, true);
4228 // (b) None selected.
4229 else if (selectionRange
.GetEnd() < range
.GetStart() || selectionRange
.GetStart() > range
.GetEnd())
4231 // Draw all unselected
4232 DrawTabbedString(dc
, textAttr
, rect
, stringChunk
, x
, y
, false);
4236 // (c) Part selected, part not
4237 // Let's draw unselected chunk, selected chunk, then unselected chunk.
4239 dc
.SetBackgroundMode(wxTRANSPARENT
);
4241 // 1. Initial unselected chunk, if any, up until start of selection.
4242 if (selectionRange
.GetStart() > range
.GetStart() && selectionRange
.GetStart() <= range
.GetEnd())
4244 int r1
= range
.GetStart();
4245 int s1
= selectionRange
.GetStart()-1;
4246 int fragmentLen
= s1
- r1
+ 1;
4247 if (fragmentLen
< 0)
4248 wxLogDebug(wxT("Mid(%d, %d"), (int)(r1
- offset
), (int)fragmentLen
);
4249 wxString stringFragment
= str
.Mid(r1
- offset
, fragmentLen
);
4251 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, false);
4254 if (stringChunk
.Find(wxT("\t")) == wxNOT_FOUND
)
4256 // Compensate for kerning difference
4257 wxString
stringFragment2(str
.Mid(r1
- offset
, fragmentLen
+1));
4258 wxString
stringFragment3(str
.Mid(r1
- offset
+ fragmentLen
, 1));
4260 wxCoord w1
, h1
, w2
, h2
, w3
, h3
;
4261 dc
.GetTextExtent(stringFragment
, & w1
, & h1
);
4262 dc
.GetTextExtent(stringFragment2
, & w2
, & h2
);
4263 dc
.GetTextExtent(stringFragment3
, & w3
, & h3
);
4265 int kerningDiff
= (w1
+ w3
) - w2
;
4266 x
= x
- kerningDiff
;
4271 // 2. Selected chunk, if any.
4272 if (selectionRange
.GetEnd() >= range
.GetStart())
4274 int s1
= wxMax(selectionRange
.GetStart(), range
.GetStart());
4275 int s2
= wxMin(selectionRange
.GetEnd(), range
.GetEnd());
4277 int fragmentLen
= s2
- s1
+ 1;
4278 if (fragmentLen
< 0)
4279 wxLogDebug(wxT("Mid(%d, %d"), (int)(s1
- offset
), (int)fragmentLen
);
4280 wxString stringFragment
= str
.Mid(s1
- offset
, fragmentLen
);
4282 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, true);
4285 if (stringChunk
.Find(wxT("\t")) == wxNOT_FOUND
)
4287 // Compensate for kerning difference
4288 wxString
stringFragment2(str
.Mid(s1
- offset
, fragmentLen
+1));
4289 wxString
stringFragment3(str
.Mid(s1
- offset
+ fragmentLen
, 1));
4291 wxCoord w1
, h1
, w2
, h2
, w3
, h3
;
4292 dc
.GetTextExtent(stringFragment
, & w1
, & h1
);
4293 dc
.GetTextExtent(stringFragment2
, & w2
, & h2
);
4294 dc
.GetTextExtent(stringFragment3
, & w3
, & h3
);
4296 int kerningDiff
= (w1
+ w3
) - w2
;
4297 x
= x
- kerningDiff
;
4302 // 3. Remaining unselected chunk, if any
4303 if (selectionRange
.GetEnd() < range
.GetEnd())
4305 int s2
= wxMin(selectionRange
.GetEnd()+1, range
.GetEnd());
4306 int r2
= range
.GetEnd();
4308 int fragmentLen
= r2
- s2
+ 1;
4309 if (fragmentLen
< 0)
4310 wxLogDebug(wxT("Mid(%d, %d"), (int)(s2
- offset
), (int)fragmentLen
);
4311 wxString stringFragment
= str
.Mid(s2
- offset
, fragmentLen
);
4313 DrawTabbedString(dc
, textAttr
, rect
, stringFragment
, x
, y
, false);
4320 bool wxRichTextPlainText::DrawTabbedString(wxDC
& dc
, const wxTextAttr
& attr
, const wxRect
& rect
,wxString
& str
, wxCoord
& x
, wxCoord
& y
, bool selected
)
4322 bool hasTabs
= (str
.Find(wxT('\t')) != wxNOT_FOUND
);
4324 wxArrayInt tabArray
;
4328 if (attr
.GetTabs().IsEmpty())
4329 tabArray
= wxRichTextParagraph::GetDefaultTabs();
4331 tabArray
= attr
.GetTabs();
4332 tabCount
= tabArray
.GetCount();
4334 for (int i
= 0; i
< tabCount
; ++i
)
4336 int pos
= tabArray
[i
];
4337 pos
= ConvertTenthsMMToPixels(dc
, pos
);
4344 int nextTabPos
= -1;
4350 wxColour
highlightColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT
));
4351 wxColour
highlightTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT
));
4353 wxCheckSetBrush(dc
, wxBrush(highlightColour
));
4354 wxCheckSetPen(dc
, wxPen(highlightColour
));
4355 dc
.SetTextForeground(highlightTextColour
);
4356 dc
.SetBackgroundMode(wxTRANSPARENT
);
4360 dc
.SetTextForeground(attr
.GetTextColour());
4362 if (attr
.HasFlag(wxTEXT_ATTR_BACKGROUND_COLOUR
) && attr
.GetBackgroundColour().IsOk())
4364 dc
.SetBackgroundMode(wxSOLID
);
4365 dc
.SetTextBackground(attr
.GetBackgroundColour());
4368 dc
.SetBackgroundMode(wxTRANSPARENT
);
4373 // the string has a tab
4374 // break up the string at the Tab
4375 wxString stringChunk
= str
.BeforeFirst(wxT('\t'));
4376 str
= str
.AfterFirst(wxT('\t'));
4377 dc
.GetTextExtent(stringChunk
, & w
, & h
);
4379 bool not_found
= true;
4380 for (int i
= 0; i
< tabCount
&& not_found
; ++i
)
4382 nextTabPos
= tabArray
.Item(i
);
4384 // Find the next tab position.
4385 // Even if we're at the end of the tab array, we must still draw the chunk.
4387 if (nextTabPos
> tabPos
|| (i
== (tabCount
- 1)))
4389 if (nextTabPos
<= tabPos
)
4391 int defaultTabWidth
= ConvertTenthsMMToPixels(dc
, WIDTH_FOR_DEFAULT_TABS
);
4392 nextTabPos
= tabPos
+ defaultTabWidth
;
4399 wxRect
selRect(x
, rect
.y
, w
, rect
.GetHeight());
4400 dc
.DrawRectangle(selRect
);
4402 dc
.DrawText(stringChunk
, x
, y
);
4404 if (attr
.HasTextEffects() && (attr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH
))
4406 wxPen oldPen
= dc
.GetPen();
4407 wxCheckSetPen(dc
, wxPen(attr
.GetTextColour(), 1));
4408 dc
.DrawLine(x
, (int) (y
+(h
/2)+0.5), x
+w
, (int) (y
+(h
/2)+0.5));
4409 wxCheckSetPen(dc
, oldPen
);
4415 hasTabs
= (str
.Find(wxT('\t')) != wxNOT_FOUND
);
4420 dc
.GetTextExtent(str
, & w
, & h
);
4423 wxRect
selRect(x
, rect
.y
, w
, rect
.GetHeight());
4424 dc
.DrawRectangle(selRect
);
4426 dc
.DrawText(str
, x
, y
);
4428 if (attr
.HasTextEffects() && (attr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH
))
4430 wxPen oldPen
= dc
.GetPen();
4431 wxCheckSetPen(dc
, wxPen(attr
.GetTextColour(), 1));
4432 dc
.DrawLine(x
, (int) (y
+(h
/2)+0.5), x
+w
, (int) (y
+(h
/2)+0.5));
4433 wxCheckSetPen(dc
, oldPen
);
4442 /// Lay the item out
4443 bool wxRichTextPlainText::Layout(wxDC
& dc
, const wxRect
& WXUNUSED(rect
), int WXUNUSED(style
))
4445 // Only lay out if we haven't already cached the size
4447 GetRangeSize(GetRange(), m_size
, m_descent
, dc
, 0, wxPoint(0, 0));
4453 void wxRichTextPlainText::Copy(const wxRichTextPlainText
& obj
)
4455 wxRichTextObject::Copy(obj
);
4457 m_text
= obj
.m_text
;
4460 /// Get/set the object size for the given range. Returns false if the range
4461 /// is invalid for this object.
4462 bool wxRichTextPlainText::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& descent
, wxDC
& dc
, int WXUNUSED(flags
), wxPoint position
) const
4464 if (!range
.IsWithin(GetRange()))
4467 wxRichTextParagraph
* para
= wxDynamicCast(GetParent(), wxRichTextParagraph
);
4468 wxASSERT (para
!= NULL
);
4470 wxTextAttr
textAttr(para
? para
->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4472 // Always assume unformatted text, since at this level we have no knowledge
4473 // of line breaks - and we don't need it, since we'll calculate size within
4474 // formatted text by doing it in chunks according to the line ranges
4476 wxFont
font(GetBuffer()->GetFontTable().FindFont(textAttr
));
4477 wxCheckSetFont(dc
, font
);
4479 int startPos
= range
.GetStart() - GetRange().GetStart();
4480 long len
= range
.GetLength();
4482 wxString
str(m_text
);
4483 wxString toReplace
= wxRichTextLineBreakChar
;
4484 str
.Replace(toReplace
, wxT(" "));
4486 wxString stringChunk
= str
.Mid(startPos
, (size_t) len
);
4488 if (textAttr
.HasTextEffects() && (textAttr
.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS
))
4489 stringChunk
.MakeUpper();
4493 if (stringChunk
.Find(wxT('\t')) != wxNOT_FOUND
)
4495 // the string has a tab
4496 wxArrayInt tabArray
;
4497 if (textAttr
.GetTabs().IsEmpty())
4498 tabArray
= wxRichTextParagraph::GetDefaultTabs();
4500 tabArray
= textAttr
.GetTabs();
4502 int tabCount
= tabArray
.GetCount();
4504 for (int i
= 0; i
< tabCount
; ++i
)
4506 int pos
= tabArray
[i
];
4507 pos
= ((wxRichTextPlainText
*) this)->ConvertTenthsMMToPixels(dc
, pos
);
4511 int nextTabPos
= -1;
4513 while (stringChunk
.Find(wxT('\t')) >= 0)
4515 // the string has a tab
4516 // break up the string at the Tab
4517 wxString stringFragment
= stringChunk
.BeforeFirst(wxT('\t'));
4518 stringChunk
= stringChunk
.AfterFirst(wxT('\t'));
4519 dc
.GetTextExtent(stringFragment
, & w
, & h
);
4521 int absoluteWidth
= width
+ position
.x
;
4523 bool notFound
= true;
4524 for (int i
= 0; i
< tabCount
&& notFound
; ++i
)
4526 nextTabPos
= tabArray
.Item(i
);
4528 // Find the next tab position.
4529 // Even if we're at the end of the tab array, we must still process the chunk.
4531 if (nextTabPos
> absoluteWidth
|| (i
== (tabCount
- 1)))
4533 if (nextTabPos
<= absoluteWidth
)
4535 int defaultTabWidth
= ((wxRichTextPlainText
*) this)->ConvertTenthsMMToPixels(dc
, WIDTH_FOR_DEFAULT_TABS
);
4536 nextTabPos
= absoluteWidth
+ defaultTabWidth
;
4540 width
= nextTabPos
- position
.x
;
4545 dc
.GetTextExtent(stringChunk
, & w
, & h
, & descent
);
4547 size
= wxSize(width
, dc
.GetCharHeight());
4552 /// Do a split, returning an object containing the second part, and setting
4553 /// the first part in 'this'.
4554 wxRichTextObject
* wxRichTextPlainText::DoSplit(long pos
)
4556 long index
= pos
- GetRange().GetStart();
4558 if (index
< 0 || index
>= (int) m_text
.length())
4561 wxString firstPart
= m_text
.Mid(0, index
);
4562 wxString secondPart
= m_text
.Mid(index
);
4566 wxRichTextPlainText
* newObject
= new wxRichTextPlainText(secondPart
);
4567 newObject
->SetAttributes(GetAttributes());
4569 newObject
->SetRange(wxRichTextRange(pos
, GetRange().GetEnd()));
4570 GetRange().SetEnd(pos
-1);
4576 void wxRichTextPlainText::CalculateRange(long start
, long& end
)
4578 end
= start
+ m_text
.length() - 1;
4579 m_range
.SetRange(start
, end
);
4583 bool wxRichTextPlainText::DeleteRange(const wxRichTextRange
& range
)
4585 wxRichTextRange r
= range
;
4587 r
.LimitTo(GetRange());
4589 if (r
.GetStart() == GetRange().GetStart() && r
.GetEnd() == GetRange().GetEnd())
4595 long startIndex
= r
.GetStart() - GetRange().GetStart();
4596 long len
= r
.GetLength();
4598 m_text
= m_text
.Mid(0, startIndex
) + m_text
.Mid(startIndex
+len
);
4602 /// Get text for the given range.
4603 wxString
wxRichTextPlainText::GetTextForRange(const wxRichTextRange
& range
) const
4605 wxRichTextRange r
= range
;
4607 r
.LimitTo(GetRange());
4609 long startIndex
= r
.GetStart() - GetRange().GetStart();
4610 long len
= r
.GetLength();
4612 return m_text
.Mid(startIndex
, len
);
4615 /// Returns true if this object can merge itself with the given one.
4616 bool wxRichTextPlainText::CanMerge(wxRichTextObject
* object
) const
4618 return object
->GetClassInfo() == CLASSINFO(wxRichTextPlainText
) &&
4619 (m_text
.empty() || wxTextAttrEq(GetAttributes(), object
->GetAttributes()));
4622 /// Returns true if this object merged itself with the given one.
4623 /// The calling code will then delete the given object.
4624 bool wxRichTextPlainText::Merge(wxRichTextObject
* object
)
4626 wxRichTextPlainText
* textObject
= wxDynamicCast(object
, wxRichTextPlainText
);
4627 wxASSERT( textObject
!= NULL
);
4631 m_text
+= textObject
->GetText();
4638 /// Dump to output stream for debugging
4639 void wxRichTextPlainText::Dump(wxTextOutputStream
& stream
)
4641 wxRichTextObject::Dump(stream
);
4642 stream
<< m_text
<< wxT("\n");
4645 /// Get the first position from pos that has a line break character.
4646 long wxRichTextPlainText::GetFirstLineBreakPosition(long pos
)
4649 int len
= m_text
.length();
4650 int startPos
= pos
- m_range
.GetStart();
4651 for (i
= startPos
; i
< len
; i
++)
4653 wxChar ch
= m_text
[i
];
4654 if (ch
== wxRichTextLineBreakChar
)
4656 return i
+ m_range
.GetStart();
4664 * This is a kind of box, used to represent the whole buffer
4667 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBuffer
, wxRichTextParagraphLayoutBox
)
4669 wxList
wxRichTextBuffer::sm_handlers
;
4670 wxRichTextRenderer
* wxRichTextBuffer::sm_renderer
= NULL
;
4671 int wxRichTextBuffer::sm_bulletRightMargin
= 20;
4672 float wxRichTextBuffer::sm_bulletProportion
= (float) 0.3;
4675 void wxRichTextBuffer::Init()
4677 m_commandProcessor
= new wxCommandProcessor
;
4678 m_styleSheet
= NULL
;
4680 m_batchedCommandDepth
= 0;
4681 m_batchedCommand
= NULL
;
4688 wxRichTextBuffer::~wxRichTextBuffer()
4690 delete m_commandProcessor
;
4691 delete m_batchedCommand
;
4694 ClearEventHandlers();
4697 void wxRichTextBuffer::ResetAndClearCommands()
4701 GetCommandProcessor()->ClearCommands();
4704 Invalidate(wxRICHTEXT_ALL
);
4707 void wxRichTextBuffer::Copy(const wxRichTextBuffer
& obj
)
4709 wxRichTextParagraphLayoutBox::Copy(obj
);
4711 m_styleSheet
= obj
.m_styleSheet
;
4712 m_modified
= obj
.m_modified
;
4713 m_batchedCommandDepth
= obj
.m_batchedCommandDepth
;
4714 m_batchedCommand
= obj
.m_batchedCommand
;
4715 m_suppressUndo
= obj
.m_suppressUndo
;
4718 /// Push style sheet to top of stack
4719 bool wxRichTextBuffer::PushStyleSheet(wxRichTextStyleSheet
* styleSheet
)
4722 styleSheet
->InsertSheet(m_styleSheet
);
4724 SetStyleSheet(styleSheet
);
4729 /// Pop style sheet from top of stack
4730 wxRichTextStyleSheet
* wxRichTextBuffer::PopStyleSheet()
4734 wxRichTextStyleSheet
* oldSheet
= m_styleSheet
;
4735 m_styleSheet
= oldSheet
->GetNextSheet();
4744 /// Submit command to insert paragraphs
4745 bool wxRichTextBuffer::InsertParagraphsWithUndo(long pos
, const wxRichTextParagraphLayoutBox
& paragraphs
, wxRichTextCtrl
* ctrl
, int flags
)
4747 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4749 wxTextAttr
attr(GetDefaultStyle());
4751 wxTextAttr
* p
= NULL
;
4752 wxTextAttr paraAttr
;
4753 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4755 paraAttr
= GetStyleForNewParagraph(pos
);
4756 if (!paraAttr
.IsDefault())
4762 action
->GetNewParagraphs() = paragraphs
;
4766 wxRichTextObjectList::compatibility_iterator node
= m_children
.GetLast();
4769 wxRichTextParagraph
* obj
= (wxRichTextParagraph
*) node
->GetData();
4770 obj
->SetAttributes(*p
);
4771 node
= node
->GetPrevious();
4775 action
->SetPosition(pos
);
4777 // Set the range we'll need to delete in Undo
4778 action
->SetRange(wxRichTextRange(pos
, pos
+ paragraphs
.GetRange().GetEnd() - 1));
4780 SubmitAction(action
);
4785 /// Submit command to insert the given text
4786 bool wxRichTextBuffer::InsertTextWithUndo(long pos
, const wxString
& text
, wxRichTextCtrl
* ctrl
, int flags
)
4788 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4790 wxTextAttr
* p
= NULL
;
4791 wxTextAttr paraAttr
;
4792 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4794 // Get appropriate paragraph style
4795 paraAttr
= GetStyleForNewParagraph(pos
, false, false);
4796 if (!paraAttr
.IsDefault())
4800 action
->GetNewParagraphs().AddParagraphs(text
, p
);
4802 int length
= action
->GetNewParagraphs().GetRange().GetLength();
4804 if (text
.length() > 0 && text
.Last() != wxT('\n'))
4806 // Don't count the newline when undoing
4808 action
->GetNewParagraphs().SetPartialParagraph(true);
4810 else if (text
.length() > 0 && text
.Last() == wxT('\n'))
4813 action
->SetPosition(pos
);
4815 // Set the range we'll need to delete in Undo
4816 action
->SetRange(wxRichTextRange(pos
, pos
+ length
- 1));
4818 SubmitAction(action
);
4823 /// Submit command to insert the given text
4824 bool wxRichTextBuffer::InsertNewlineWithUndo(long pos
, wxRichTextCtrl
* ctrl
, int flags
)
4826 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Text"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4828 wxTextAttr
* p
= NULL
;
4829 wxTextAttr paraAttr
;
4830 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4832 paraAttr
= GetStyleForNewParagraph(pos
, false, true /* look for next paragraph style */);
4833 if (!paraAttr
.IsDefault())
4837 wxTextAttr
attr(GetDefaultStyle());
4839 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(wxEmptyString
, this, & attr
);
4840 action
->GetNewParagraphs().AppendChild(newPara
);
4841 action
->GetNewParagraphs().UpdateRanges();
4842 action
->GetNewParagraphs().SetPartialParagraph(false);
4843 action
->SetPosition(pos
);
4846 newPara
->SetAttributes(*p
);
4848 // Set the range we'll need to delete in Undo
4849 action
->SetRange(wxRichTextRange(pos
, pos
));
4851 SubmitAction(action
);
4856 /// Submit command to insert the given image
4857 bool wxRichTextBuffer::InsertImageWithUndo(long pos
, const wxRichTextImageBlock
& imageBlock
, wxRichTextCtrl
* ctrl
, int flags
)
4859 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Image"), wxRICHTEXT_INSERT
, this, ctrl
, false);
4861 wxTextAttr
* p
= NULL
;
4862 wxTextAttr paraAttr
;
4863 if (flags
& wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
)
4865 paraAttr
= GetStyleForNewParagraph(pos
);
4866 if (!paraAttr
.IsDefault())
4870 wxTextAttr
attr(GetDefaultStyle());
4872 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(this, & attr
);
4874 newPara
->SetAttributes(*p
);
4876 wxRichTextImage
* imageObject
= new wxRichTextImage(imageBlock
, newPara
);
4877 newPara
->AppendChild(imageObject
);
4878 action
->GetNewParagraphs().AppendChild(newPara
);
4879 action
->GetNewParagraphs().UpdateRanges();
4881 action
->GetNewParagraphs().SetPartialParagraph(true);
4883 action
->SetPosition(pos
);
4885 // Set the range we'll need to delete in Undo
4886 action
->SetRange(wxRichTextRange(pos
, pos
));
4888 SubmitAction(action
);
4893 /// Get the style that is appropriate for a new paragraph at this position.
4894 /// If the previous paragraph has a paragraph style name, look up the next-paragraph
4896 wxTextAttr
wxRichTextBuffer::GetStyleForNewParagraph(long pos
, bool caretPosition
, bool lookUpNewParaStyle
) const
4898 wxRichTextParagraph
* para
= GetParagraphAtPosition(pos
, caretPosition
);
4902 bool foundAttributes
= false;
4904 // Look for a matching paragraph style
4905 if (lookUpNewParaStyle
&& !para
->GetAttributes().GetParagraphStyleName().IsEmpty() && GetStyleSheet())
4907 wxRichTextParagraphStyleDefinition
* paraDef
= GetStyleSheet()->FindParagraphStyle(para
->GetAttributes().GetParagraphStyleName());
4910 // If we're not at the end of the paragraph, then we apply THIS style, and not the designated next style.
4911 if (para
->GetRange().GetEnd() == pos
&& !paraDef
->GetNextStyle().IsEmpty())
4913 wxRichTextParagraphStyleDefinition
* nextParaDef
= GetStyleSheet()->FindParagraphStyle(paraDef
->GetNextStyle());
4916 foundAttributes
= true;
4917 attr
= nextParaDef
->GetStyleMergedWithBase(GetStyleSheet());
4921 // If we didn't find the 'next style', use this style instead.
4922 if (!foundAttributes
)
4924 foundAttributes
= true;
4925 attr
= paraDef
->GetStyleMergedWithBase(GetStyleSheet());
4929 if (!foundAttributes
)
4931 attr
= para
->GetAttributes();
4932 int flags
= attr
.GetFlags();
4934 // Eliminate character styles
4935 flags
&= ( (~ wxTEXT_ATTR_FONT
) |
4936 (~ wxTEXT_ATTR_TEXT_COLOUR
) |
4937 (~ wxTEXT_ATTR_BACKGROUND_COLOUR
) );
4938 attr
.SetFlags(flags
);
4941 // Now see if we need to number the paragraph.
4942 if (attr
.HasBulletStyle())
4944 wxTextAttr numberingAttr
;
4945 if (FindNextParagraphNumber(para
, numberingAttr
))
4946 wxRichTextApplyStyle(attr
, (const wxTextAttr
&) numberingAttr
);
4952 return wxTextAttr();
4955 /// Submit command to delete this range
4956 bool wxRichTextBuffer::DeleteRangeWithUndo(const wxRichTextRange
& range
, wxRichTextCtrl
* ctrl
)
4958 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Delete"), wxRICHTEXT_DELETE
, this, ctrl
);
4960 action
->SetPosition(ctrl
->GetCaretPosition());
4962 // Set the range to delete
4963 action
->SetRange(range
);
4965 // Copy the fragment that we'll need to restore in Undo
4966 CopyFragment(range
, action
->GetOldParagraphs());
4968 // Special case: if there is only one (non-partial) paragraph,
4969 // we must save the *next* paragraph's style, because that
4970 // is the style we must apply when inserting the content back
4971 // when undoing the delete. (This is because we're merging the
4972 // paragraph with the previous paragraph and throwing away
4973 // the style, and we need to restore it.)
4974 if (!action
->GetOldParagraphs().GetPartialParagraph() && action
->GetOldParagraphs().GetChildCount() == 1)
4976 wxRichTextParagraph
* lastPara
= GetParagraphAtPosition(range
.GetStart());
4979 wxRichTextParagraph
* nextPara
= GetParagraphAtPosition(range
.GetEnd()+1);
4982 wxRichTextParagraph
* para
= (wxRichTextParagraph
*) action
->GetOldParagraphs().GetChild(0);
4983 para
->SetAttributes(nextPara
->GetAttributes());
4988 SubmitAction(action
);
4993 /// Collapse undo/redo commands
4994 bool wxRichTextBuffer::BeginBatchUndo(const wxString
& cmdName
)
4996 if (m_batchedCommandDepth
== 0)
4998 wxASSERT(m_batchedCommand
== NULL
);
4999 if (m_batchedCommand
)
5001 GetCommandProcessor()->Submit(m_batchedCommand
);
5003 m_batchedCommand
= new wxRichTextCommand(cmdName
);
5006 m_batchedCommandDepth
++;
5011 /// Collapse undo/redo commands
5012 bool wxRichTextBuffer::EndBatchUndo()
5014 m_batchedCommandDepth
--;
5016 wxASSERT(m_batchedCommandDepth
>= 0);
5017 wxASSERT(m_batchedCommand
!= NULL
);
5019 if (m_batchedCommandDepth
== 0)
5021 GetCommandProcessor()->Submit(m_batchedCommand
);
5022 m_batchedCommand
= NULL
;
5028 /// Submit immediately, or delay according to whether collapsing is on
5029 bool wxRichTextBuffer::SubmitAction(wxRichTextAction
* action
)
5031 if (BatchingUndo() && m_batchedCommand
&& !SuppressingUndo())
5032 m_batchedCommand
->AddAction(action
);
5035 wxRichTextCommand
* cmd
= new wxRichTextCommand(action
->GetName());
5036 cmd
->AddAction(action
);
5038 // Only store it if we're not suppressing undo.
5039 return GetCommandProcessor()->Submit(cmd
, !SuppressingUndo());
5045 /// Begin suppressing undo/redo commands.
5046 bool wxRichTextBuffer::BeginSuppressUndo()
5053 /// End suppressing undo/redo commands.
5054 bool wxRichTextBuffer::EndSuppressUndo()
5061 /// Begin using a style
5062 bool wxRichTextBuffer::BeginStyle(const wxTextAttr
& style
)
5064 wxTextAttr
newStyle(GetDefaultStyle());
5066 // Save the old default style
5067 m_attributeStack
.Append((wxObject
*) new wxTextAttr(GetDefaultStyle()));
5069 wxRichTextApplyStyle(newStyle
, style
);
5070 newStyle
.SetFlags(style
.GetFlags()|newStyle
.GetFlags());
5072 SetDefaultStyle(newStyle
);
5074 // wxLogDebug("Default style size = %d", GetDefaultStyle().GetFont().GetPointSize());
5080 bool wxRichTextBuffer::EndStyle()
5082 if (!m_attributeStack
.GetFirst())
5084 wxLogDebug(_("Too many EndStyle calls!"));
5088 wxList::compatibility_iterator node
= m_attributeStack
.GetLast();
5089 wxTextAttr
* attr
= (wxTextAttr
*)node
->GetData();
5090 m_attributeStack
.Erase(node
);
5092 SetDefaultStyle(*attr
);
5099 bool wxRichTextBuffer::EndAllStyles()
5101 while (m_attributeStack
.GetCount() != 0)
5106 /// Clear the style stack
5107 void wxRichTextBuffer::ClearStyleStack()
5109 for (wxList::compatibility_iterator node
= m_attributeStack
.GetFirst(); node
; node
= node
->GetNext())
5110 delete (wxTextAttr
*) node
->GetData();
5111 m_attributeStack
.Clear();
5114 /// Begin using bold
5115 bool wxRichTextBuffer::BeginBold()
5118 attr
.SetFontWeight(wxBOLD
);
5120 return BeginStyle(attr
);
5123 /// Begin using italic
5124 bool wxRichTextBuffer::BeginItalic()
5127 attr
.SetFontStyle(wxITALIC
);
5129 return BeginStyle(attr
);
5132 /// Begin using underline
5133 bool wxRichTextBuffer::BeginUnderline()
5136 attr
.SetFontUnderlined(true);
5138 return BeginStyle(attr
);
5141 /// Begin using point size
5142 bool wxRichTextBuffer::BeginFontSize(int pointSize
)
5145 attr
.SetFontSize(pointSize
);
5147 return BeginStyle(attr
);
5150 /// Begin using this font
5151 bool wxRichTextBuffer::BeginFont(const wxFont
& font
)
5156 return BeginStyle(attr
);
5159 /// Begin using this colour
5160 bool wxRichTextBuffer::BeginTextColour(const wxColour
& colour
)
5163 attr
.SetFlags(wxTEXT_ATTR_TEXT_COLOUR
);
5164 attr
.SetTextColour(colour
);
5166 return BeginStyle(attr
);
5169 /// Begin using alignment
5170 bool wxRichTextBuffer::BeginAlignment(wxTextAttrAlignment alignment
)
5173 attr
.SetFlags(wxTEXT_ATTR_ALIGNMENT
);
5174 attr
.SetAlignment(alignment
);
5176 return BeginStyle(attr
);
5179 /// Begin left indent
5180 bool wxRichTextBuffer::BeginLeftIndent(int leftIndent
, int leftSubIndent
)
5183 attr
.SetFlags(wxTEXT_ATTR_LEFT_INDENT
);
5184 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5186 return BeginStyle(attr
);
5189 /// Begin right indent
5190 bool wxRichTextBuffer::BeginRightIndent(int rightIndent
)
5193 attr
.SetFlags(wxTEXT_ATTR_RIGHT_INDENT
);
5194 attr
.SetRightIndent(rightIndent
);
5196 return BeginStyle(attr
);
5199 /// Begin paragraph spacing
5200 bool wxRichTextBuffer::BeginParagraphSpacing(int before
, int after
)
5204 flags
|= wxTEXT_ATTR_PARA_SPACING_BEFORE
;
5206 flags
|= wxTEXT_ATTR_PARA_SPACING_AFTER
;
5209 attr
.SetFlags(flags
);
5210 attr
.SetParagraphSpacingBefore(before
);
5211 attr
.SetParagraphSpacingAfter(after
);
5213 return BeginStyle(attr
);
5216 /// Begin line spacing
5217 bool wxRichTextBuffer::BeginLineSpacing(int lineSpacing
)
5220 attr
.SetFlags(wxTEXT_ATTR_LINE_SPACING
);
5221 attr
.SetLineSpacing(lineSpacing
);
5223 return BeginStyle(attr
);
5226 /// Begin numbered bullet
5227 bool wxRichTextBuffer::BeginNumberedBullet(int bulletNumber
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5230 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5231 attr
.SetBulletStyle(bulletStyle
);
5232 attr
.SetBulletNumber(bulletNumber
);
5233 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5235 return BeginStyle(attr
);
5238 /// Begin symbol bullet
5239 bool wxRichTextBuffer::BeginSymbolBullet(const wxString
& symbol
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5242 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5243 attr
.SetBulletStyle(bulletStyle
);
5244 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5245 attr
.SetBulletText(symbol
);
5247 return BeginStyle(attr
);
5250 /// Begin standard bullet
5251 bool wxRichTextBuffer::BeginStandardBullet(const wxString
& bulletName
, int leftIndent
, int leftSubIndent
, int bulletStyle
)
5254 attr
.SetFlags(wxTEXT_ATTR_BULLET_STYLE
|wxTEXT_ATTR_LEFT_INDENT
);
5255 attr
.SetBulletStyle(bulletStyle
);
5256 attr
.SetLeftIndent(leftIndent
, leftSubIndent
);
5257 attr
.SetBulletName(bulletName
);
5259 return BeginStyle(attr
);
5262 /// Begin named character style
5263 bool wxRichTextBuffer::BeginCharacterStyle(const wxString
& characterStyle
)
5265 if (GetStyleSheet())
5267 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterStyle
);
5270 wxTextAttr attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5271 return BeginStyle(attr
);
5277 /// Begin named paragraph style
5278 bool wxRichTextBuffer::BeginParagraphStyle(const wxString
& paragraphStyle
)
5280 if (GetStyleSheet())
5282 wxRichTextParagraphStyleDefinition
* def
= GetStyleSheet()->FindParagraphStyle(paragraphStyle
);
5285 wxTextAttr attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5286 return BeginStyle(attr
);
5292 /// Begin named list style
5293 bool wxRichTextBuffer::BeginListStyle(const wxString
& listStyle
, int level
, int number
)
5295 if (GetStyleSheet())
5297 wxRichTextListStyleDefinition
* def
= GetStyleSheet()->FindListStyle(listStyle
);
5300 wxTextAttr
attr(def
->GetCombinedStyleForLevel(level
));
5302 attr
.SetBulletNumber(number
);
5304 return BeginStyle(attr
);
5311 bool wxRichTextBuffer::BeginURL(const wxString
& url
, const wxString
& characterStyle
)
5315 if (!characterStyle
.IsEmpty() && GetStyleSheet())
5317 wxRichTextCharacterStyleDefinition
* def
= GetStyleSheet()->FindCharacterStyle(characterStyle
);
5320 attr
= def
->GetStyleMergedWithBase(GetStyleSheet());
5325 return BeginStyle(attr
);
5328 /// Adds a handler to the end
5329 void wxRichTextBuffer::AddHandler(wxRichTextFileHandler
*handler
)
5331 sm_handlers
.Append(handler
);
5334 /// Inserts a handler at the front
5335 void wxRichTextBuffer::InsertHandler(wxRichTextFileHandler
*handler
)
5337 sm_handlers
.Insert( handler
);
5340 /// Removes a handler
5341 bool wxRichTextBuffer::RemoveHandler(const wxString
& name
)
5343 wxRichTextFileHandler
*handler
= FindHandler(name
);
5346 sm_handlers
.DeleteObject(handler
);
5354 /// Finds a handler by filename or, if supplied, type
5355 wxRichTextFileHandler
*wxRichTextBuffer::FindHandlerFilenameOrType(const wxString
& filename
, int imageType
)
5357 if (imageType
!= wxRICHTEXT_TYPE_ANY
)
5358 return FindHandler(imageType
);
5359 else if (!filename
.IsEmpty())
5361 wxString path
, file
, ext
;
5362 wxSplitPath(filename
, & path
, & file
, & ext
);
5363 return FindHandler(ext
, imageType
);
5370 /// Finds a handler by name
5371 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(const wxString
& name
)
5373 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5376 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5377 if (handler
->GetName().Lower() == name
.Lower()) return handler
;
5379 node
= node
->GetNext();
5384 /// Finds a handler by extension and type
5385 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(const wxString
& extension
, int type
)
5387 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5390 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5391 if ( handler
->GetExtension().Lower() == extension
.Lower() &&
5392 (type
== wxRICHTEXT_TYPE_ANY
|| handler
->GetType() == type
) )
5394 node
= node
->GetNext();
5399 /// Finds a handler by type
5400 wxRichTextFileHandler
* wxRichTextBuffer::FindHandler(int type
)
5402 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5405 wxRichTextFileHandler
*handler
= (wxRichTextFileHandler
*)node
->GetData();
5406 if (handler
->GetType() == type
) return handler
;
5407 node
= node
->GetNext();
5412 void wxRichTextBuffer::InitStandardHandlers()
5414 if (!FindHandler(wxRICHTEXT_TYPE_TEXT
))
5415 AddHandler(new wxRichTextPlainTextHandler
);
5418 void wxRichTextBuffer::CleanUpHandlers()
5420 wxList::compatibility_iterator node
= sm_handlers
.GetFirst();
5423 wxRichTextFileHandler
* handler
= (wxRichTextFileHandler
*)node
->GetData();
5424 wxList::compatibility_iterator next
= node
->GetNext();
5429 sm_handlers
.Clear();
5432 wxString
wxRichTextBuffer::GetExtWildcard(bool combine
, bool save
, wxArrayInt
* types
)
5439 wxList::compatibility_iterator node
= GetHandlers().GetFirst();
5443 wxRichTextFileHandler
* handler
= (wxRichTextFileHandler
*) node
->GetData();
5444 if (handler
->IsVisible() && ((save
&& handler
->CanSave()) || !save
&& handler
->CanLoad()))
5449 wildcard
+= wxT(";");
5450 wildcard
+= wxT("*.") + handler
->GetExtension();
5455 wildcard
+= wxT("|");
5456 wildcard
+= handler
->GetName();
5457 wildcard
+= wxT(" ");
5458 wildcard
+= _("files");
5459 wildcard
+= wxT(" (*.");
5460 wildcard
+= handler
->GetExtension();
5461 wildcard
+= wxT(")|*.");
5462 wildcard
+= handler
->GetExtension();
5464 types
->Add(handler
->GetType());
5469 node
= node
->GetNext();
5473 wildcard
= wxT("(") + wildcard
+ wxT(")|") + wildcard
;
5478 bool wxRichTextBuffer::LoadFile(const wxString
& filename
, int type
)
5480 wxRichTextFileHandler
* handler
= FindHandlerFilenameOrType(filename
, type
);
5483 SetDefaultStyle(wxTextAttr());
5484 handler
->SetFlags(GetHandlerFlags());
5485 bool success
= handler
->LoadFile(this, filename
);
5486 Invalidate(wxRICHTEXT_ALL
);
5494 bool wxRichTextBuffer::SaveFile(const wxString
& filename
, int type
)
5496 wxRichTextFileHandler
* handler
= FindHandlerFilenameOrType(filename
, type
);
5499 handler
->SetFlags(GetHandlerFlags());
5500 return handler
->SaveFile(this, filename
);
5506 /// Load from a stream
5507 bool wxRichTextBuffer::LoadFile(wxInputStream
& stream
, int type
)
5509 wxRichTextFileHandler
* handler
= FindHandler(type
);
5512 SetDefaultStyle(wxTextAttr());
5513 handler
->SetFlags(GetHandlerFlags());
5514 bool success
= handler
->LoadFile(this, stream
);
5515 Invalidate(wxRICHTEXT_ALL
);
5522 /// Save to a stream
5523 bool wxRichTextBuffer::SaveFile(wxOutputStream
& stream
, int type
)
5525 wxRichTextFileHandler
* handler
= FindHandler(type
);
5528 handler
->SetFlags(GetHandlerFlags());
5529 return handler
->SaveFile(this, stream
);
5535 /// Copy the range to the clipboard
5536 bool wxRichTextBuffer::CopyToClipboard(const wxRichTextRange
& range
)
5538 bool success
= false;
5539 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5541 if (!wxTheClipboard
->IsOpened() && wxTheClipboard
->Open())
5543 wxTheClipboard
->Clear();
5545 // Add composite object
5547 wxDataObjectComposite
* compositeObject
= new wxDataObjectComposite();
5550 wxString text
= GetTextForRange(range
);
5553 text
= wxTextFile::Translate(text
, wxTextFileType_Dos
);
5556 compositeObject
->Add(new wxTextDataObject(text
), false /* not preferred */);
5559 // Add rich text buffer data object. This needs the XML handler to be present.
5561 if (FindHandler(wxRICHTEXT_TYPE_XML
))
5563 wxRichTextBuffer
* richTextBuf
= new wxRichTextBuffer
;
5564 CopyFragment(range
, *richTextBuf
);
5566 compositeObject
->Add(new wxRichTextBufferDataObject(richTextBuf
), true /* preferred */);
5569 if (wxTheClipboard
->SetData(compositeObject
))
5572 wxTheClipboard
->Close();
5581 /// Paste the clipboard content to the buffer
5582 bool wxRichTextBuffer::PasteFromClipboard(long position
)
5584 bool success
= false;
5585 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5586 if (CanPasteFromClipboard())
5588 if (wxTheClipboard
->Open())
5590 if (wxTheClipboard
->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())))
5592 wxRichTextBufferDataObject data
;
5593 wxTheClipboard
->GetData(data
);
5594 wxRichTextBuffer
* richTextBuffer
= data
.GetRichTextBuffer();
5597 InsertParagraphsWithUndo(position
+1, *richTextBuffer
, GetRichTextCtrl(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
);
5598 delete richTextBuffer
;
5601 else if (wxTheClipboard
->IsSupported(wxDF_TEXT
) || wxTheClipboard
->IsSupported(wxDF_UNICODETEXT
))
5603 wxTextDataObject data
;
5604 wxTheClipboard
->GetData(data
);
5605 wxString
text(data
.GetText());
5606 text
.Replace(_T("\r\n"), _T("\n"));
5608 InsertTextWithUndo(position
+1, text
, GetRichTextCtrl());
5612 else if (wxTheClipboard
->IsSupported(wxDF_BITMAP
))
5614 wxBitmapDataObject data
;
5615 wxTheClipboard
->GetData(data
);
5616 wxBitmap
bitmap(data
.GetBitmap());
5617 wxImage
image(bitmap
.ConvertToImage());
5619 wxRichTextAction
* action
= new wxRichTextAction(NULL
, _("Insert Image"), wxRICHTEXT_INSERT
, this, GetRichTextCtrl(), false);
5621 action
->GetNewParagraphs().AddImage(image
);
5623 if (action
->GetNewParagraphs().GetChildCount() == 1)
5624 action
->GetNewParagraphs().SetPartialParagraph(true);
5626 action
->SetPosition(position
);
5628 // Set the range we'll need to delete in Undo
5629 action
->SetRange(wxRichTextRange(position
, position
));
5631 SubmitAction(action
);
5635 wxTheClipboard
->Close();
5639 wxUnusedVar(position
);
5644 /// Can we paste from the clipboard?
5645 bool wxRichTextBuffer::CanPasteFromClipboard() const
5647 bool canPaste
= false;
5648 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5649 if (!wxTheClipboard
->IsOpened() && wxTheClipboard
->Open())
5651 if (wxTheClipboard
->IsSupported(wxDF_TEXT
) || wxTheClipboard
->IsSupported(wxDF_UNICODETEXT
) ||
5652 wxTheClipboard
->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())) ||
5653 wxTheClipboard
->IsSupported(wxDF_BITMAP
))
5657 wxTheClipboard
->Close();
5663 /// Dumps contents of buffer for debugging purposes
5664 void wxRichTextBuffer::Dump()
5668 wxStringOutputStream
stream(& text
);
5669 wxTextOutputStream
textStream(stream
);
5676 /// Add an event handler
5677 bool wxRichTextBuffer::AddEventHandler(wxEvtHandler
* handler
)
5679 m_eventHandlers
.Append(handler
);
5683 /// Remove an event handler
5684 bool wxRichTextBuffer::RemoveEventHandler(wxEvtHandler
* handler
, bool deleteHandler
)
5686 wxList::compatibility_iterator node
= m_eventHandlers
.Find(handler
);
5689 m_eventHandlers
.Erase(node
);
5699 /// Clear event handlers
5700 void wxRichTextBuffer::ClearEventHandlers()
5702 m_eventHandlers
.Clear();
5705 /// Send event to event handlers. If sendToAll is true, will send to all event handlers,
5706 /// otherwise will stop at the first successful one.
5707 bool wxRichTextBuffer::SendEvent(wxEvent
& event
, bool sendToAll
)
5709 bool success
= false;
5710 for (wxList::compatibility_iterator node
= m_eventHandlers
.GetFirst(); node
; node
= node
->GetNext())
5712 wxEvtHandler
* handler
= (wxEvtHandler
*) node
->GetData();
5713 if (handler
->ProcessEvent(event
))
5723 /// Set style sheet and notify of the change
5724 bool wxRichTextBuffer::SetStyleSheetAndNotify(wxRichTextStyleSheet
* sheet
)
5726 wxRichTextStyleSheet
* oldSheet
= GetStyleSheet();
5728 wxWindowID id
= wxID_ANY
;
5729 if (GetRichTextCtrl())
5730 id
= GetRichTextCtrl()->GetId();
5732 wxRichTextEvent
event(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING
, id
);
5733 event
.SetEventObject(GetRichTextCtrl());
5734 event
.SetOldStyleSheet(oldSheet
);
5735 event
.SetNewStyleSheet(sheet
);
5738 if (SendEvent(event
) && !event
.IsAllowed())
5740 if (sheet
!= oldSheet
)
5746 if (oldSheet
&& oldSheet
!= sheet
)
5749 SetStyleSheet(sheet
);
5751 event
.SetEventType(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED
);
5752 event
.SetOldStyleSheet(NULL
);
5755 return SendEvent(event
);
5758 /// Set renderer, deleting old one
5759 void wxRichTextBuffer::SetRenderer(wxRichTextRenderer
* renderer
)
5763 sm_renderer
= renderer
;
5766 bool wxRichTextStdRenderer::DrawStandardBullet(wxRichTextParagraph
* paragraph
, wxDC
& dc
, const wxTextAttr
& bulletAttr
, const wxRect
& rect
)
5768 if (bulletAttr
.GetTextColour().Ok())
5770 wxCheckSetPen(dc
, wxPen(bulletAttr
.GetTextColour()));
5771 wxCheckSetBrush(dc
, wxBrush(bulletAttr
.GetTextColour()));
5775 wxCheckSetPen(dc
, *wxBLACK_PEN
);
5776 wxCheckSetBrush(dc
, *wxBLACK_BRUSH
);
5780 if (bulletAttr
.HasFont())
5782 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(bulletAttr
);
5785 font
= (*wxNORMAL_FONT
);
5787 wxCheckSetFont(dc
, font
);
5789 int charHeight
= dc
.GetCharHeight();
5791 int bulletWidth
= (int) (((float) charHeight
) * wxRichTextBuffer::GetBulletProportion());
5792 int bulletHeight
= bulletWidth
;
5796 // Calculate the top position of the character (as opposed to the whole line height)
5797 int y
= rect
.y
+ (rect
.height
- charHeight
);
5799 // Calculate where the bullet should be positioned
5800 y
= y
+ (charHeight
+1)/2 - (bulletHeight
+1)/2;
5802 // The margin between a bullet and text.
5803 int margin
= paragraph
->ConvertTenthsMMToPixels(dc
, wxRichTextBuffer::GetBulletRightMargin());
5805 if (bulletAttr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT
)
5806 x
= rect
.x
+ rect
.width
- bulletWidth
- margin
;
5807 else if (bulletAttr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE
)
5808 x
= x
+ (rect
.width
)/2 - bulletWidth
/2;
5810 if (bulletAttr
.GetBulletName() == wxT("standard/square"))
5812 dc
.DrawRectangle(x
, y
, bulletWidth
, bulletHeight
);
5814 else if (bulletAttr
.GetBulletName() == wxT("standard/diamond"))
5817 pts
[0].x
= x
; pts
[0].y
= y
+ bulletHeight
/2;
5818 pts
[1].x
= x
+ bulletWidth
/2; pts
[1].y
= y
;
5819 pts
[2].x
= x
+ bulletWidth
; pts
[2].y
= y
+ bulletHeight
/2;
5820 pts
[3].x
= x
+ bulletWidth
/2; pts
[3].y
= y
+ bulletHeight
;
5822 dc
.DrawPolygon(4, pts
);
5824 else if (bulletAttr
.GetBulletName() == wxT("standard/triangle"))
5827 pts
[0].x
= x
; pts
[0].y
= y
;
5828 pts
[1].x
= x
+ bulletWidth
; pts
[1].y
= y
+ bulletHeight
/2;
5829 pts
[2].x
= x
; pts
[2].y
= y
+ bulletHeight
;
5831 dc
.DrawPolygon(3, pts
);
5833 else // "standard/circle", and catch-all
5835 dc
.DrawEllipse(x
, y
, bulletWidth
, bulletHeight
);
5841 bool wxRichTextStdRenderer::DrawTextBullet(wxRichTextParagraph
* paragraph
, wxDC
& dc
, const wxTextAttr
& attr
, const wxRect
& rect
, const wxString
& text
)
5846 if ((attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL
) && !attr
.GetBulletFont().IsEmpty() && attr
.HasFont())
5848 wxTextAttr fontAttr
;
5849 fontAttr
.SetFontSize(attr
.GetFontSize());
5850 fontAttr
.SetFontStyle(attr
.GetFontStyle());
5851 fontAttr
.SetFontWeight(attr
.GetFontWeight());
5852 fontAttr
.SetFontUnderlined(attr
.GetFontUnderlined());
5853 fontAttr
.SetFontFaceName(attr
.GetBulletFont());
5854 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(fontAttr
);
5856 else if (attr
.HasFont())
5857 font
= paragraph
->GetBuffer()->GetFontTable().FindFont(attr
);
5859 font
= (*wxNORMAL_FONT
);
5861 wxCheckSetFont(dc
, font
);
5863 if (attr
.GetTextColour().Ok())
5864 dc
.SetTextForeground(attr
.GetTextColour());
5866 dc
.SetBackgroundMode(wxTRANSPARENT
);
5868 int charHeight
= dc
.GetCharHeight();
5870 dc
.GetTextExtent(text
, & tw
, & th
);
5874 // Calculate the top position of the character (as opposed to the whole line height)
5875 int y
= rect
.y
+ (rect
.height
- charHeight
);
5877 // The margin between a bullet and text.
5878 int margin
= paragraph
->ConvertTenthsMMToPixels(dc
, wxRichTextBuffer::GetBulletRightMargin());
5880 if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT
)
5881 x
= (rect
.x
+ rect
.width
) - tw
- margin
;
5882 else if (attr
.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE
)
5883 x
= x
+ (rect
.width
)/2 - tw
/2;
5885 dc
.DrawText(text
, x
, y
);
5893 bool wxRichTextStdRenderer::DrawBitmapBullet(wxRichTextParagraph
* WXUNUSED(paragraph
), wxDC
& WXUNUSED(dc
), const wxTextAttr
& WXUNUSED(attr
), const wxRect
& WXUNUSED(rect
))
5895 // Currently unimplemented. The intention is to store bitmaps by name in a media store associated
5896 // with the buffer. The store will allow retrieval from memory, disk or other means.
5900 /// Enumerate the standard bullet names currently supported
5901 bool wxRichTextStdRenderer::EnumerateStandardBulletNames(wxArrayString
& bulletNames
)
5903 bulletNames
.Add(wxT("standard/circle"));
5904 bulletNames
.Add(wxT("standard/square"));
5905 bulletNames
.Add(wxT("standard/diamond"));
5906 bulletNames
.Add(wxT("standard/triangle"));
5912 * Module to initialise and clean up handlers
5915 class wxRichTextModule
: public wxModule
5917 DECLARE_DYNAMIC_CLASS(wxRichTextModule
)
5919 wxRichTextModule() {}
5922 wxRichTextBuffer::SetRenderer(new wxRichTextStdRenderer
);
5923 wxRichTextBuffer::InitStandardHandlers();
5924 wxRichTextParagraph::InitDefaultTabs();
5929 wxRichTextBuffer::CleanUpHandlers();
5930 wxRichTextDecimalToRoman(-1);
5931 wxRichTextParagraph::ClearDefaultTabs();
5932 wxRichTextCtrl::ClearAvailableFontNames();
5933 wxRichTextBuffer::SetRenderer(NULL
);
5937 IMPLEMENT_DYNAMIC_CLASS(wxRichTextModule
, wxModule
)
5940 // If the richtext lib is dynamically loaded after the app has already started
5941 // (such as from wxPython) then the built-in module system will not init this
5942 // module. Provide this function to do it manually.
5943 void wxRichTextModuleInit()
5945 wxModule
* module = new wxRichTextModule
;
5947 wxModule::RegisterModule(module);
5952 * Commands for undo/redo
5956 wxRichTextCommand::wxRichTextCommand(const wxString
& name
, wxRichTextCommandId id
, wxRichTextBuffer
* buffer
,
5957 wxRichTextCtrl
* ctrl
, bool ignoreFirstTime
): wxCommand(true, name
)
5959 /* wxRichTextAction* action = */ new wxRichTextAction(this, name
, id
, buffer
, ctrl
, ignoreFirstTime
);
5962 wxRichTextCommand::wxRichTextCommand(const wxString
& name
): wxCommand(true, name
)
5966 wxRichTextCommand::~wxRichTextCommand()
5971 void wxRichTextCommand::AddAction(wxRichTextAction
* action
)
5973 if (!m_actions
.Member(action
))
5974 m_actions
.Append(action
);
5977 bool wxRichTextCommand::Do()
5979 for (wxList::compatibility_iterator node
= m_actions
.GetFirst(); node
; node
= node
->GetNext())
5981 wxRichTextAction
* action
= (wxRichTextAction
*) node
->GetData();
5988 bool wxRichTextCommand::Undo()
5990 for (wxList::compatibility_iterator node
= m_actions
.GetLast(); node
; node
= node
->GetPrevious())
5992 wxRichTextAction
* action
= (wxRichTextAction
*) node
->GetData();
5999 void wxRichTextCommand::ClearActions()
6001 WX_CLEAR_LIST(wxList
, m_actions
);
6009 wxRichTextAction::wxRichTextAction(wxRichTextCommand
* cmd
, const wxString
& name
, wxRichTextCommandId id
, wxRichTextBuffer
* buffer
,
6010 wxRichTextCtrl
* ctrl
, bool ignoreFirstTime
)
6013 m_ignoreThis
= ignoreFirstTime
;
6018 m_newParagraphs
.SetDefaultStyle(buffer
->GetDefaultStyle());
6019 m_newParagraphs
.SetBasicStyle(buffer
->GetBasicStyle());
6021 cmd
->AddAction(this);
6024 wxRichTextAction::~wxRichTextAction()
6028 bool wxRichTextAction::Do()
6030 m_buffer
->Modify(true);
6034 case wxRICHTEXT_INSERT
:
6036 // Store a list of line start character and y positions so we can figure out which area
6037 // we need to refresh
6038 wxArrayInt optimizationLineCharPositions
;
6039 wxArrayInt optimizationLineYPositions
;
6041 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6042 // NOTE: we're assuming that the buffer is laid out correctly at this point.
6043 // If we had several actions, which only invalidate and leave layout until the
6044 // paint handler is called, then this might not be true. So we may need to switch
6045 // optimisation on only when we're simply adding text and not simultaneously
6046 // deleting a selection, for example. Or, we make sure the buffer is laid out correctly
6047 // first, but of course this means we'll be doing it twice.
6048 if (!m_buffer
->GetDirty() && m_ctrl
) // can only do optimisation if the buffer is already laid out correctly
6050 wxSize clientSize
= m_ctrl
->GetClientSize();
6051 wxPoint firstVisiblePt
= m_ctrl
->GetFirstVisiblePoint();
6052 int lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6054 wxRichTextParagraph
* para
= m_buffer
->GetParagraphAtPosition(GetPosition());
6055 wxRichTextObjectList::compatibility_iterator node
= m_buffer
->GetChildren().Find(para
);
6058 wxRichTextParagraph
* child
= (wxRichTextParagraph
*) node
->GetData();
6059 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
6062 wxRichTextLine
* line
= node2
->GetData();
6063 wxPoint pt
= line
->GetAbsolutePosition();
6064 wxRichTextRange range
= line
->GetAbsoluteRange();
6068 node2
= wxRichTextLineList::compatibility_iterator();
6069 node
= wxRichTextObjectList::compatibility_iterator();
6071 else if (range
.GetStart() > GetPosition() && pt
.y
>= firstVisiblePt
.y
)
6073 optimizationLineCharPositions
.Add(range
.GetStart());
6074 optimizationLineYPositions
.Add(pt
.y
);
6078 node2
= node2
->GetNext();
6082 node
= node
->GetNext();
6087 m_buffer
->InsertFragment(GetPosition(), m_newParagraphs
);
6088 m_buffer
->UpdateRanges();
6089 m_buffer
->Invalidate(GetRange());
6091 long newCaretPosition
= GetPosition() + m_newParagraphs
.GetRange().GetLength();
6093 // Character position to caret position
6094 newCaretPosition
--;
6096 // Don't take into account the last newline
6097 if (m_newParagraphs
.GetPartialParagraph())
6098 newCaretPosition
--;
6100 if (m_newParagraphs
.GetChildren().GetCount() > 1)
6102 wxRichTextObject
* p
= (wxRichTextObject
*) m_newParagraphs
.GetChildren().GetLast()->GetData();
6103 if (p
->GetRange().GetLength() == 1)
6104 newCaretPosition
--;
6107 newCaretPosition
= wxMin(newCaretPosition
, (m_buffer
->GetRange().GetEnd()-1));
6109 if (optimizationLineCharPositions
.GetCount() > 0)
6110 UpdateAppearance(newCaretPosition
, true /* send update event */, & optimizationLineCharPositions
, & optimizationLineYPositions
);
6112 UpdateAppearance(newCaretPosition
, true /* send update event */);
6114 wxRichTextEvent
cmdEvent(
6115 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED
,
6116 m_ctrl
? m_ctrl
->GetId() : -1);
6117 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6118 cmdEvent
.SetRange(GetRange());
6119 cmdEvent
.SetPosition(GetRange().GetStart());
6121 m_buffer
->SendEvent(cmdEvent
);
6125 case wxRICHTEXT_DELETE
:
6127 m_buffer
->DeleteRange(GetRange());
6128 m_buffer
->UpdateRanges();
6129 m_buffer
->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6131 UpdateAppearance(GetRange().GetStart()-1, true /* send update event */);
6133 wxRichTextEvent
cmdEvent(
6134 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED
,
6135 m_ctrl
? m_ctrl
->GetId() : -1);
6136 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6137 cmdEvent
.SetRange(GetRange());
6138 cmdEvent
.SetPosition(GetRange().GetStart());
6140 m_buffer
->SendEvent(cmdEvent
);
6144 case wxRICHTEXT_CHANGE_STYLE
:
6146 ApplyParagraphs(GetNewParagraphs());
6147 m_buffer
->Invalidate(GetRange());
6149 UpdateAppearance(GetPosition());
6151 wxRichTextEvent
cmdEvent(
6152 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED
,
6153 m_ctrl
? m_ctrl
->GetId() : -1);
6154 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6155 cmdEvent
.SetRange(GetRange());
6156 cmdEvent
.SetPosition(GetRange().GetStart());
6158 m_buffer
->SendEvent(cmdEvent
);
6169 bool wxRichTextAction::Undo()
6171 m_buffer
->Modify(true);
6175 case wxRICHTEXT_INSERT
:
6177 m_buffer
->DeleteRange(GetRange());
6178 m_buffer
->UpdateRanges();
6179 m_buffer
->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6181 long newCaretPosition
= GetPosition() - 1;
6183 UpdateAppearance(newCaretPosition
, true /* send update event */);
6185 wxRichTextEvent
cmdEvent(
6186 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED
,
6187 m_ctrl
? m_ctrl
->GetId() : -1);
6188 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6189 cmdEvent
.SetRange(GetRange());
6190 cmdEvent
.SetPosition(GetRange().GetStart());
6192 m_buffer
->SendEvent(cmdEvent
);
6196 case wxRICHTEXT_DELETE
:
6198 m_buffer
->InsertFragment(GetRange().GetStart(), m_oldParagraphs
);
6199 m_buffer
->UpdateRanges();
6200 m_buffer
->Invalidate(GetRange());
6202 UpdateAppearance(GetPosition(), true /* send update event */);
6204 wxRichTextEvent
cmdEvent(
6205 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED
,
6206 m_ctrl
? m_ctrl
->GetId() : -1);
6207 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6208 cmdEvent
.SetRange(GetRange());
6209 cmdEvent
.SetPosition(GetRange().GetStart());
6211 m_buffer
->SendEvent(cmdEvent
);
6215 case wxRICHTEXT_CHANGE_STYLE
:
6217 ApplyParagraphs(GetOldParagraphs());
6218 m_buffer
->Invalidate(GetRange());
6220 UpdateAppearance(GetPosition());
6222 wxRichTextEvent
cmdEvent(
6223 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED
,
6224 m_ctrl
? m_ctrl
->GetId() : -1);
6225 cmdEvent
.SetEventObject(m_ctrl
? (wxObject
*) m_ctrl
: (wxObject
*) m_buffer
);
6226 cmdEvent
.SetRange(GetRange());
6227 cmdEvent
.SetPosition(GetRange().GetStart());
6229 m_buffer
->SendEvent(cmdEvent
);
6240 /// Update the control appearance
6241 void wxRichTextAction::UpdateAppearance(long caretPosition
, bool sendUpdateEvent
, wxArrayInt
* optimizationLineCharPositions
, wxArrayInt
* optimizationLineYPositions
)
6245 m_ctrl
->SetCaretPosition(caretPosition
);
6246 if (!m_ctrl
->IsFrozen())
6248 m_ctrl
->LayoutContent();
6249 m_ctrl
->PositionCaret();
6251 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6252 // Find refresh rectangle if we are in a position to optimise refresh
6253 if (m_cmdId
== wxRICHTEXT_INSERT
&& optimizationLineCharPositions
&& optimizationLineCharPositions
->GetCount() > 0)
6257 wxSize clientSize
= m_ctrl
->GetClientSize();
6258 wxPoint firstVisiblePt
= m_ctrl
->GetFirstVisiblePoint();
6260 // Start/end positions
6262 int lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6264 bool foundStart
= false;
6265 bool foundEnd
= false;
6267 // position offset - how many characters were inserted
6268 int positionOffset
= GetRange().GetLength();
6270 // find the first line which is being drawn at the same position as it was
6271 // before. Since we're talking about a simple insertion, we can assume
6272 // that the rest of the window does not need to be redrawn.
6274 wxRichTextParagraph
* para
= m_buffer
->GetParagraphAtPosition(GetPosition());
6275 wxRichTextObjectList::compatibility_iterator node
= m_buffer
->GetChildren().Find(para
);
6278 wxRichTextParagraph
* child
= (wxRichTextParagraph
*) node
->GetData();
6279 wxRichTextLineList::compatibility_iterator node2
= child
->GetLines().GetFirst();
6282 wxRichTextLine
* line
= node2
->GetData();
6283 wxPoint pt
= line
->GetAbsolutePosition();
6284 wxRichTextRange range
= line
->GetAbsoluteRange();
6286 // we want to find the first line that is in the same position
6287 // as before. This will mean we're at the end of the changed text.
6289 if (pt
.y
> lastY
) // going past the end of the window, no more info
6291 node2
= wxRichTextLineList::compatibility_iterator();
6292 node
= wxRichTextObjectList::compatibility_iterator();
6298 firstY
= pt
.y
- firstVisiblePt
.y
;
6302 // search for this line being at the same position as before
6303 for (i
= 0; i
< optimizationLineCharPositions
->GetCount(); i
++)
6305 if (((*optimizationLineCharPositions
)[i
] + positionOffset
== range
.GetStart()) &&
6306 ((*optimizationLineYPositions
)[i
] == pt
.y
))
6308 // Stop, we're now the same as we were
6310 lastY
= pt
.y
- firstVisiblePt
.y
;
6312 node2
= wxRichTextLineList::compatibility_iterator();
6313 node
= wxRichTextObjectList::compatibility_iterator();
6321 node2
= node2
->GetNext();
6325 node
= node
->GetNext();
6329 firstY
= firstVisiblePt
.y
;
6331 lastY
= firstVisiblePt
.y
+ clientSize
.y
;
6333 wxRect
rect(firstVisiblePt
.x
, firstY
, firstVisiblePt
.x
+ clientSize
.x
, lastY
- firstY
);
6334 m_ctrl
->RefreshRect(rect
);
6336 // TODO: we need to make sure that lines are only drawn if in the update region. The rect
6337 // passed to Draw is currently used in different ways (to pass the position the content should
6338 // be drawn at as well as the relevant region).
6342 m_ctrl
->Refresh(false);
6344 if (sendUpdateEvent
)
6345 wxTextCtrl::SendTextUpdatedEvent(m_ctrl
);
6350 /// Replace the buffer paragraphs with the new ones.
6351 void wxRichTextAction::ApplyParagraphs(const wxRichTextParagraphLayoutBox
& fragment
)
6353 wxRichTextObjectList::compatibility_iterator node
= fragment
.GetChildren().GetFirst();
6356 wxRichTextParagraph
* para
= wxDynamicCast(node
->GetData(), wxRichTextParagraph
);
6357 wxASSERT (para
!= NULL
);
6359 // We'll replace the existing paragraph by finding the paragraph at this position,
6360 // delete its node data, and setting a copy as the new node data.
6361 // TODO: make more efficient by simply swapping old and new paragraph objects.
6363 wxRichTextParagraph
* existingPara
= m_buffer
->GetParagraphAtPosition(para
->GetRange().GetStart());
6366 wxRichTextObjectList::compatibility_iterator bufferParaNode
= m_buffer
->GetChildren().Find(existingPara
);
6369 wxRichTextParagraph
* newPara
= new wxRichTextParagraph(*para
);
6370 newPara
->SetParent(m_buffer
);
6372 bufferParaNode
->SetData(newPara
);
6374 delete existingPara
;
6378 node
= node
->GetNext();
6385 * This stores beginning and end positions for a range of data.
6388 /// Limit this range to be within 'range'
6389 bool wxRichTextRange::LimitTo(const wxRichTextRange
& range
)
6391 if (m_start
< range
.m_start
)
6392 m_start
= range
.m_start
;
6394 if (m_end
> range
.m_end
)
6395 m_end
= range
.m_end
;
6401 * wxRichTextImage implementation
6402 * This object represents an image.
6405 IMPLEMENT_DYNAMIC_CLASS(wxRichTextImage
, wxRichTextObject
)
6407 wxRichTextImage::wxRichTextImage(const wxImage
& image
, wxRichTextObject
* parent
, wxTextAttr
* charStyle
):
6408 wxRichTextObject(parent
)
6412 SetAttributes(*charStyle
);
6415 wxRichTextImage::wxRichTextImage(const wxRichTextImageBlock
& imageBlock
, wxRichTextObject
* parent
, wxTextAttr
* charStyle
):
6416 wxRichTextObject(parent
)
6418 m_imageBlock
= imageBlock
;
6419 m_imageBlock
.Load(m_image
);
6421 SetAttributes(*charStyle
);
6424 /// Load wxImage from the block
6425 bool wxRichTextImage::LoadFromBlock()
6427 m_imageBlock
.Load(m_image
);
6428 return m_imageBlock
.Ok();
6431 /// Make block from the wxImage
6432 bool wxRichTextImage::MakeBlock()
6434 if (m_imageBlock
.GetImageType() == wxBITMAP_TYPE_ANY
|| m_imageBlock
.GetImageType() == -1)
6435 m_imageBlock
.SetImageType(wxBITMAP_TYPE_PNG
);
6437 m_imageBlock
.MakeImageBlock(m_image
, m_imageBlock
.GetImageType());
6438 return m_imageBlock
.Ok();
6443 bool wxRichTextImage::Draw(wxDC
& dc
, const wxRichTextRange
& range
, const wxRichTextRange
& selectionRange
, const wxRect
& rect
, int WXUNUSED(descent
), int WXUNUSED(style
))
6445 if (!m_image
.Ok() && m_imageBlock
.Ok())
6451 if (m_image
.Ok() && !m_bitmap
.Ok())
6452 m_bitmap
= wxBitmap(m_image
);
6454 int y
= rect
.y
+ (rect
.height
- m_image
.GetHeight());
6457 dc
.DrawBitmap(m_bitmap
, rect
.x
, y
, true);
6459 if (selectionRange
.Contains(range
.GetStart()))
6461 wxCheckSetBrush(dc
, *wxBLACK_BRUSH
);
6462 wxCheckSetPen(dc
, *wxBLACK_PEN
);
6463 dc
.SetLogicalFunction(wxINVERT
);
6464 dc
.DrawRectangle(rect
);
6465 dc
.SetLogicalFunction(wxCOPY
);
6471 /// Lay the item out
6472 bool wxRichTextImage::Layout(wxDC
& WXUNUSED(dc
), const wxRect
& rect
, int WXUNUSED(style
))
6479 SetCachedSize(wxSize(m_image
.GetWidth(), m_image
.GetHeight()));
6480 SetPosition(rect
.GetPosition());
6486 /// Get/set the object size for the given range. Returns false if the range
6487 /// is invalid for this object.
6488 bool wxRichTextImage::GetRangeSize(const wxRichTextRange
& range
, wxSize
& size
, int& WXUNUSED(descent
), wxDC
& WXUNUSED(dc
), int WXUNUSED(flags
), wxPoint
WXUNUSED(position
)) const
6490 if (!range
.IsWithin(GetRange()))
6496 size
.x
= m_image
.GetWidth();
6497 size
.y
= m_image
.GetHeight();
6503 void wxRichTextImage::Copy(const wxRichTextImage
& obj
)
6505 wxRichTextObject::Copy(obj
);
6507 m_image
= obj
.m_image
;
6508 m_imageBlock
= obj
.m_imageBlock
;
6516 /// Compare two attribute objects
6517 bool wxTextAttrEq(const wxTextAttr
& attr1
, const wxTextAttr
& attr2
)
6519 return (attr1
== attr2
);
6522 // Partial equality test taking flags into account
6523 bool wxTextAttrEqPartial(const wxTextAttr
& attr1
, const wxTextAttr
& attr2
, int flags
)
6525 return attr1
.EqPartial(attr2
, flags
);
6529 bool wxRichTextTabsEq(const wxArrayInt
& tabs1
, const wxArrayInt
& tabs2
)
6531 if (tabs1
.GetCount() != tabs2
.GetCount())
6535 for (i
= 0; i
< tabs1
.GetCount(); i
++)
6537 if (tabs1
[i
] != tabs2
[i
])
6543 bool wxRichTextApplyStyle(wxTextAttr
& destStyle
, const wxTextAttr
& style
, wxTextAttr
* compareWith
)
6545 return destStyle
.Apply(style
, compareWith
);
6548 // Remove attributes
6549 bool wxRichTextRemoveStyle(wxTextAttr
& destStyle
, const wxTextAttr
& style
)
6551 return wxTextAttr::RemoveStyle(destStyle
, style
);
6554 /// Combine two bitlists, specifying the bits of interest with separate flags.
6555 bool wxRichTextCombineBitlists(int& valueA
, int valueB
, int& flagsA
, int flagsB
)
6557 return wxTextAttr::CombineBitlists(valueA
, valueB
, flagsA
, flagsB
);
6560 /// Compare two bitlists
6561 bool wxRichTextBitlistsEqPartial(int valueA
, int valueB
, int flags
)
6563 return wxTextAttr::BitlistsEqPartial(valueA
, valueB
, flags
);
6566 /// Split into paragraph and character styles
6567 bool wxRichTextSplitParaCharStyles(const wxTextAttr
& style
, wxTextAttr
& parStyle
, wxTextAttr
& charStyle
)
6569 return wxTextAttr::SplitParaCharStyles(style
, parStyle
, charStyle
);
6572 /// Convert a decimal to Roman numerals
6573 wxString
wxRichTextDecimalToRoman(long n
)
6575 static wxArrayInt decimalNumbers
;
6576 static wxArrayString romanNumbers
;
6581 decimalNumbers
.Clear();
6582 romanNumbers
.Clear();
6583 return wxEmptyString
;
6586 if (decimalNumbers
.GetCount() == 0)
6588 #define wxRichTextAddDecRom(n, r) decimalNumbers.Add(n); romanNumbers.Add(r);
6590 wxRichTextAddDecRom(1000, wxT("M"));
6591 wxRichTextAddDecRom(900, wxT("CM"));
6592 wxRichTextAddDecRom(500, wxT("D"));
6593 wxRichTextAddDecRom(400, wxT("CD"));
6594 wxRichTextAddDecRom(100, wxT("C"));
6595 wxRichTextAddDecRom(90, wxT("XC"));
6596 wxRichTextAddDecRom(50, wxT("L"));
6597 wxRichTextAddDecRom(40, wxT("XL"));
6598 wxRichTextAddDecRom(10, wxT("X"));
6599 wxRichTextAddDecRom(9, wxT("IX"));
6600 wxRichTextAddDecRom(5, wxT("V"));
6601 wxRichTextAddDecRom(4, wxT("IV"));
6602 wxRichTextAddDecRom(1, wxT("I"));
6608 while (n
> 0 && i
< 13)
6610 if (n
>= decimalNumbers
[i
])
6612 n
-= decimalNumbers
[i
];
6613 roman
+= romanNumbers
[i
];
6620 if (roman
.IsEmpty())
6626 * wxRichTextFileHandler
6627 * Base class for file handlers
6630 IMPLEMENT_CLASS(wxRichTextFileHandler
, wxObject
)
6632 #if wxUSE_FFILE && wxUSE_STREAMS
6633 bool wxRichTextFileHandler::LoadFile(wxRichTextBuffer
*buffer
, const wxString
& filename
)
6635 wxFFileInputStream
stream(filename
);
6637 return LoadFile(buffer
, stream
);
6642 bool wxRichTextFileHandler::SaveFile(wxRichTextBuffer
*buffer
, const wxString
& filename
)
6644 wxFFileOutputStream
stream(filename
);
6646 return SaveFile(buffer
, stream
);
6650 #endif // wxUSE_FFILE && wxUSE_STREAMS
6652 /// Can we handle this filename (if using files)? By default, checks the extension.
6653 bool wxRichTextFileHandler::CanHandle(const wxString
& filename
) const
6655 wxString path
, file
, ext
;
6656 wxSplitPath(filename
, & path
, & file
, & ext
);
6658 return (ext
.Lower() == GetExtension());
6662 * wxRichTextTextHandler
6663 * Plain text handler
6666 IMPLEMENT_CLASS(wxRichTextPlainTextHandler
, wxRichTextFileHandler
)
6669 bool wxRichTextPlainTextHandler::DoLoadFile(wxRichTextBuffer
*buffer
, wxInputStream
& stream
)
6677 while (!stream
.Eof())
6679 int ch
= stream
.GetC();
6683 if (ch
== 10 && lastCh
!= 13)
6686 if (ch
> 0 && ch
!= 10)
6693 buffer
->ResetAndClearCommands();
6695 buffer
->AddParagraphs(str
);
6696 buffer
->UpdateRanges();
6701 bool wxRichTextPlainTextHandler::DoSaveFile(wxRichTextBuffer
*buffer
, wxOutputStream
& stream
)
6706 wxString text
= buffer
->GetText();
6708 wxString newLine
= wxRichTextLineBreakChar
;
6709 text
.Replace(newLine
, wxT("\n"));
6711 wxCharBuffer buf
= text
.ToAscii();
6713 stream
.Write((const char*) buf
, text
.length());
6716 #endif // wxUSE_STREAMS
6719 * Stores information about an image, in binary in-memory form
6722 wxRichTextImageBlock::wxRichTextImageBlock()
6727 wxRichTextImageBlock::wxRichTextImageBlock(const wxRichTextImageBlock
& block
):wxObject()
6733 wxRichTextImageBlock::~wxRichTextImageBlock()
6742 void wxRichTextImageBlock::Init()
6749 void wxRichTextImageBlock::Clear()
6758 // Load the original image into a memory block.
6759 // If the image is not a JPEG, we must convert it into a JPEG
6760 // to conserve space.
6761 // If it's not a JPEG we can make use of 'image', already scaled, so we don't have to
6762 // load the image a 2nd time.
6764 bool wxRichTextImageBlock::MakeImageBlock(const wxString
& filename
, int imageType
, wxImage
& image
, bool convertToJPEG
)
6766 m_imageType
= imageType
;
6768 wxString
filenameToRead(filename
);
6769 bool removeFile
= false;
6771 if (imageType
== -1)
6772 return false; // Could not determine image type
6774 if ((imageType
!= wxBITMAP_TYPE_JPEG
) && convertToJPEG
)
6777 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
6781 wxUnusedVar(success
);
6783 image
.SaveFile(tempFile
, wxBITMAP_TYPE_JPEG
);
6784 filenameToRead
= tempFile
;
6787 m_imageType
= wxBITMAP_TYPE_JPEG
;
6790 if (!file
.Open(filenameToRead
))
6793 m_dataSize
= (size_t) file
.Length();
6798 m_data
= ReadBlock(filenameToRead
, m_dataSize
);
6801 wxRemoveFile(filenameToRead
);
6803 return (m_data
!= NULL
);
6806 // Make an image block from the wxImage in the given
6808 bool wxRichTextImageBlock::MakeImageBlock(wxImage
& image
, int imageType
, int quality
)
6810 m_imageType
= imageType
;
6811 image
.SetOption(wxT("quality"), quality
);
6813 if (imageType
== -1)
6814 return false; // Could not determine image type
6817 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
6820 wxUnusedVar(success
);
6822 if (!image
.SaveFile(tempFile
, m_imageType
))
6824 if (wxFileExists(tempFile
))
6825 wxRemoveFile(tempFile
);
6830 if (!file
.Open(tempFile
))
6833 m_dataSize
= (size_t) file
.Length();
6838 m_data
= ReadBlock(tempFile
, m_dataSize
);
6840 wxRemoveFile(tempFile
);
6842 return (m_data
!= NULL
);
6847 bool wxRichTextImageBlock::Write(const wxString
& filename
)
6849 return WriteBlock(filename
, m_data
, m_dataSize
);
6852 void wxRichTextImageBlock::Copy(const wxRichTextImageBlock
& block
)
6854 m_imageType
= block
.m_imageType
;
6860 m_dataSize
= block
.m_dataSize
;
6861 if (m_dataSize
== 0)
6864 m_data
= new unsigned char[m_dataSize
];
6866 for (i
= 0; i
< m_dataSize
; i
++)
6867 m_data
[i
] = block
.m_data
[i
];
6871 void wxRichTextImageBlock::operator=(const wxRichTextImageBlock
& block
)
6876 // Load a wxImage from the block
6877 bool wxRichTextImageBlock::Load(wxImage
& image
)
6882 // Read in the image.
6884 wxMemoryInputStream
mstream(m_data
, m_dataSize
);
6885 bool success
= image
.LoadFile(mstream
, GetImageType());
6888 bool success
= wxGetTempFileName(_("image"), tempFile
) ;
6891 if (!WriteBlock(tempFile
, m_data
, m_dataSize
))
6895 success
= image
.LoadFile(tempFile
, GetImageType());
6896 wxRemoveFile(tempFile
);
6902 // Write data in hex to a stream
6903 bool wxRichTextImageBlock::WriteHex(wxOutputStream
& stream
)
6905 const int bufSize
= 512;
6906 char buf
[bufSize
+1];
6908 int left
= m_dataSize
;
6913 if (left
*2 > bufSize
)
6915 n
= bufSize
; left
-= (bufSize
/2);
6919 n
= left
*2; left
= 0;
6923 for (i
= 0; i
< (n
/2); i
++)
6925 wxDecToHex(m_data
[j
], b
, b
+1);
6930 stream
.Write((const char*) buf
, n
);
6935 // Read data in hex from a stream
6936 bool wxRichTextImageBlock::ReadHex(wxInputStream
& stream
, int length
, int imageType
)
6938 int dataSize
= length
/2;
6944 m_data
= new unsigned char[dataSize
];
6946 for (i
= 0; i
< dataSize
; i
++)
6948 str
[0] = (char)stream
.GetC();
6949 str
[1] = (char)stream
.GetC();
6951 m_data
[i
] = (unsigned char)wxHexToDec(str
);
6954 m_dataSize
= dataSize
;
6955 m_imageType
= imageType
;
6960 // Allocate and read from stream as a block of memory
6961 unsigned char* wxRichTextImageBlock::ReadBlock(wxInputStream
& stream
, size_t size
)
6963 unsigned char* block
= new unsigned char[size
];
6967 stream
.Read(block
, size
);
6972 unsigned char* wxRichTextImageBlock::ReadBlock(const wxString
& filename
, size_t size
)
6974 wxFileInputStream
stream(filename
);
6978 return ReadBlock(stream
, size
);
6981 // Write memory block to stream
6982 bool wxRichTextImageBlock::WriteBlock(wxOutputStream
& stream
, unsigned char* block
, size_t size
)
6984 stream
.Write((void*) block
, size
);
6985 return stream
.IsOk();
6989 // Write memory block to file
6990 bool wxRichTextImageBlock::WriteBlock(const wxString
& filename
, unsigned char* block
, size_t size
)
6992 wxFileOutputStream
outStream(filename
);
6993 if (!outStream
.Ok())
6996 return WriteBlock(outStream
, block
, size
);
6999 // Gets the extension for the block's type
7000 wxString
wxRichTextImageBlock::GetExtension() const
7002 wxImageHandler
* handler
= wxImage::FindHandler(GetImageType());
7004 return handler
->GetExtension();
7006 return wxEmptyString
;
7012 * The data object for a wxRichTextBuffer
7015 const wxChar
*wxRichTextBufferDataObject::ms_richTextBufferFormatId
= wxT("wxShape");
7017 wxRichTextBufferDataObject::wxRichTextBufferDataObject(wxRichTextBuffer
* richTextBuffer
)
7019 m_richTextBuffer
= richTextBuffer
;
7021 // this string should uniquely identify our format, but is otherwise
7023 m_formatRichTextBuffer
.SetId(GetRichTextBufferFormatId());
7025 SetFormat(m_formatRichTextBuffer
);
7028 wxRichTextBufferDataObject::~wxRichTextBufferDataObject()
7030 delete m_richTextBuffer
;
7033 // after a call to this function, the richTextBuffer is owned by the caller and it
7034 // is responsible for deleting it!
7035 wxRichTextBuffer
* wxRichTextBufferDataObject::GetRichTextBuffer()
7037 wxRichTextBuffer
* richTextBuffer
= m_richTextBuffer
;
7038 m_richTextBuffer
= NULL
;
7040 return richTextBuffer
;
7043 wxDataFormat
wxRichTextBufferDataObject::GetPreferredFormat(Direction
WXUNUSED(dir
)) const
7045 return m_formatRichTextBuffer
;
7048 size_t wxRichTextBufferDataObject::GetDataSize() const
7050 if (!m_richTextBuffer
)
7056 wxStringOutputStream
stream(& bufXML
);
7057 if (!m_richTextBuffer
->SaveFile(stream
, wxRICHTEXT_TYPE_XML
))
7059 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
7065 wxCharBuffer buffer
= bufXML
.mb_str(wxConvUTF8
);
7066 return strlen(buffer
) + 1;
7068 return bufXML
.Length()+1;
7072 bool wxRichTextBufferDataObject::GetDataHere(void *pBuf
) const
7074 if (!pBuf
|| !m_richTextBuffer
)
7080 wxStringOutputStream
stream(& bufXML
);
7081 if (!m_richTextBuffer
->SaveFile(stream
, wxRICHTEXT_TYPE_XML
))
7083 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
7089 wxCharBuffer buffer
= bufXML
.mb_str(wxConvUTF8
);
7090 size_t len
= strlen(buffer
);
7091 memcpy((char*) pBuf
, (const char*) buffer
, len
);
7092 ((char*) pBuf
)[len
] = 0;
7094 size_t len
= bufXML
.Length();
7095 memcpy((char*) pBuf
, (const char*) bufXML
.c_str(), len
);
7096 ((char*) pBuf
)[len
] = 0;
7102 bool wxRichTextBufferDataObject::SetData(size_t WXUNUSED(len
), const void *buf
)
7104 delete m_richTextBuffer
;
7105 m_richTextBuffer
= NULL
;
7107 wxString
bufXML((const char*) buf
, wxConvUTF8
);
7109 m_richTextBuffer
= new wxRichTextBuffer
;
7111 wxStringInputStream
stream(bufXML
);
7112 if (!m_richTextBuffer
->LoadFile(stream
, wxRICHTEXT_TYPE_XML
))
7114 wxLogError(wxT("Could not read the buffer from an XML stream.\nYou may have forgotten to add the XML file handler."));
7116 delete m_richTextBuffer
;
7117 m_richTextBuffer
= NULL
;
7129 * wxRichTextFontTable
7130 * Manages quick access to a pool of fonts for rendering rich text
7133 WX_DECLARE_STRING_HASH_MAP_WITH_DECL(wxFont
, wxRichTextFontTableHashMap
, class WXDLLIMPEXP_RICHTEXT
);
7135 class wxRichTextFontTableData
: public wxObjectRefData
7138 wxRichTextFontTableData() {}
7140 wxFont
FindFont(const wxTextAttr
& fontSpec
);
7142 wxRichTextFontTableHashMap m_hashMap
;
7145 wxFont
wxRichTextFontTableData::FindFont(const wxTextAttr
& fontSpec
)
7147 wxString
facename(fontSpec
.GetFontFaceName());
7148 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()));
7149 wxRichTextFontTableHashMap::iterator entry
= m_hashMap
.find(spec
);
7151 if ( entry
== m_hashMap
.end() )
7153 wxFont
font(fontSpec
.GetFontSize(), wxDEFAULT
, fontSpec
.GetFontStyle(), fontSpec
.GetFontWeight(), fontSpec
.GetFontUnderlined(), facename
.c_str());
7154 m_hashMap
[spec
] = font
;
7159 return entry
->second
;
7163 IMPLEMENT_DYNAMIC_CLASS(wxRichTextFontTable
, wxObject
)
7165 wxRichTextFontTable::wxRichTextFontTable()
7167 m_refData
= new wxRichTextFontTableData
;
7168 m_refData
->IncRef();
7171 wxRichTextFontTable::wxRichTextFontTable(const wxRichTextFontTable
& table
)
7176 wxRichTextFontTable::~wxRichTextFontTable()
7181 bool wxRichTextFontTable::operator == (const wxRichTextFontTable
& table
) const
7183 return (m_refData
== table
.m_refData
);
7186 void wxRichTextFontTable::operator= (const wxRichTextFontTable
& table
)
7191 wxFont
wxRichTextFontTable::FindFont(const wxTextAttr
& fontSpec
)
7193 wxRichTextFontTableData
* data
= (wxRichTextFontTableData
*) m_refData
;
7195 return data
->FindFont(fontSpec
);
7200 void wxRichTextFontTable::Clear()
7202 wxRichTextFontTableData
* data
= (wxRichTextFontTableData
*) m_refData
;
7204 data
->m_hashMap
.clear();