]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/richtext/richtextbuffer.cpp
removed no longer used src/iodbc directory
[wxWidgets.git] / src / richtext / richtextbuffer.cpp
... / ...
CommitLineData
1/////////////////////////////////////////////////////////////////////////////
2// Name: src/richtext/richtextbuffer.cpp
3// Purpose: Buffer for wxRichTextCtrl
4// Author: Julian Smart
5// Modified by:
6// Created: 2005-09-30
7// RCS-ID: $Id$
8// Copyright: (c) Julian Smart
9// Licence: wxWindows licence
10/////////////////////////////////////////////////////////////////////////////
11
12// For compilers that support precompilation, includes "wx.h".
13#include "wx/wxprec.h"
14
15#ifdef __BORLANDC__
16 #pragma hdrstop
17#endif
18
19#if wxUSE_RICHTEXT
20
21#include "wx/richtext/richtextbuffer.h"
22
23#ifndef WX_PRECOMP
24 #include "wx/dc.h"
25 #include "wx/intl.h"
26 #include "wx/log.h"
27 #include "wx/dataobj.h"
28 #include "wx/module.h"
29#endif
30
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"
39
40#include "wx/richtext/richtextctrl.h"
41#include "wx/richtext/richtextstyles.h"
42
43#include "wx/listimpl.cpp"
44
45WX_DEFINE_LIST(wxRichTextObjectList)
46WX_DEFINE_LIST(wxRichTextLineList)
47
48// Switch off if the platform doesn't like it for some reason
49#define wxRICHTEXT_USE_OPTIMIZED_DRAWING 1
50
51const wxChar wxRichTextLineBreakChar = (wxChar) 29;
52
53// Helpers for efficiency
54
55inline void wxCheckSetFont(wxDC& dc, const wxFont& font)
56{
57 const wxFont& font1 = dc.GetFont();
58 if (font1.IsOk() && font.IsOk())
59 {
60 if (font1.GetPointSize() == font.GetPointSize() &&
61 font1.GetFamily() == font.GetFamily() &&
62 font1.GetStyle() == font.GetStyle() &&
63 font1.GetWeight() == font.GetWeight() &&
64 font1.GetUnderlined() == font.GetUnderlined() &&
65 font1.GetFaceName() == font.GetFaceName())
66 return;
67 }
68 dc.SetFont(font);
69}
70
71inline void wxCheckSetPen(wxDC& dc, const wxPen& pen)
72{
73 const wxPen& pen1 = dc.GetPen();
74 if (pen1.IsOk() && pen.IsOk())
75 {
76 if (pen1.GetWidth() == pen.GetWidth() &&
77 pen1.GetStyle() == pen.GetStyle() &&
78 pen1.GetColour() == pen.GetColour())
79 return;
80 }
81 dc.SetPen(pen);
82}
83
84inline void wxCheckSetBrush(wxDC& dc, const wxBrush& brush)
85{
86 const wxBrush& brush1 = dc.GetBrush();
87 if (brush1.IsOk() && brush.IsOk())
88 {
89 if (brush1.GetStyle() == brush.GetStyle() &&
90 brush1.GetColour() == brush.GetColour())
91 return;
92 }
93 dc.SetBrush(brush);
94}
95
96/*!
97 * wxRichTextObject
98 * This is the base for drawable objects.
99 */
100
101IMPLEMENT_CLASS(wxRichTextObject, wxObject)
102
103wxRichTextObject::wxRichTextObject(wxRichTextObject* parent)
104{
105 m_dirty = false;
106 m_refCount = 1;
107 m_parent = parent;
108 m_leftMargin = 0;
109 m_rightMargin = 0;
110 m_topMargin = 0;
111 m_bottomMargin = 0;
112 m_descent = 0;
113}
114
115wxRichTextObject::~wxRichTextObject()
116{
117}
118
119void wxRichTextObject::Dereference()
120{
121 m_refCount --;
122 if (m_refCount <= 0)
123 delete this;
124}
125
126/// Copy
127void wxRichTextObject::Copy(const wxRichTextObject& obj)
128{
129 m_size = obj.m_size;
130 m_pos = obj.m_pos;
131 m_dirty = obj.m_dirty;
132 m_range = obj.m_range;
133 m_attributes = obj.m_attributes;
134 m_descent = obj.m_descent;
135}
136
137void wxRichTextObject::SetMargins(int margin)
138{
139 m_leftMargin = m_rightMargin = m_topMargin = m_bottomMargin = margin;
140}
141
142void wxRichTextObject::SetMargins(int leftMargin, int rightMargin, int topMargin, int bottomMargin)
143{
144 m_leftMargin = leftMargin;
145 m_rightMargin = rightMargin;
146 m_topMargin = topMargin;
147 m_bottomMargin = bottomMargin;
148}
149
150// Convert units in tenths of a millimetre to device units
151int wxRichTextObject::ConvertTenthsMMToPixels(wxDC& dc, int units)
152{
153 int p = ConvertTenthsMMToPixels(dc.GetPPI().x, units);
154
155 // Unscale
156 wxRichTextBuffer* buffer = GetBuffer();
157 if (buffer)
158 p = (int) ((double)p / buffer->GetScale());
159 return p;
160}
161
162// Convert units in tenths of a millimetre to device units
163int wxRichTextObject::ConvertTenthsMMToPixels(int ppi, int units)
164{
165 // There are ppi pixels in 254.1 "1/10 mm"
166
167 double pixels = ((double) units * (double)ppi) / 254.1;
168
169 return (int) pixels;
170}
171
172/// Dump to output stream for debugging
173void wxRichTextObject::Dump(wxTextOutputStream& stream)
174{
175 stream << GetClassInfo()->GetClassName() << wxT("\n");
176 stream << wxString::Format(wxT("Size: %d,%d. Position: %d,%d, Range: %ld,%ld"), m_size.x, m_size.y, m_pos.x, m_pos.y, m_range.GetStart(), m_range.GetEnd()) << wxT("\n");
177 stream << wxString::Format(wxT("Text colour: %d,%d,%d."), (int) m_attributes.GetTextColour().Red(), (int) m_attributes.GetTextColour().Green(), (int) m_attributes.GetTextColour().Blue()) << wxT("\n");
178}
179
180/// Gets the containing buffer
181wxRichTextBuffer* wxRichTextObject::GetBuffer() const
182{
183 const wxRichTextObject* obj = this;
184 while (obj && !obj->IsKindOf(CLASSINFO(wxRichTextBuffer)))
185 obj = obj->GetParent();
186 return wxDynamicCast(obj, wxRichTextBuffer);
187}
188
189/*!
190 * wxRichTextCompositeObject
191 * This is the base for drawable objects.
192 */
193
194IMPLEMENT_CLASS(wxRichTextCompositeObject, wxRichTextObject)
195
196wxRichTextCompositeObject::wxRichTextCompositeObject(wxRichTextObject* parent):
197 wxRichTextObject(parent)
198{
199}
200
201wxRichTextCompositeObject::~wxRichTextCompositeObject()
202{
203 DeleteChildren();
204}
205
206/// Get the nth child
207wxRichTextObject* wxRichTextCompositeObject::GetChild(size_t n) const
208{
209 wxASSERT ( n < m_children.GetCount() );
210
211 return m_children.Item(n)->GetData();
212}
213
214/// Append a child, returning the position
215size_t wxRichTextCompositeObject::AppendChild(wxRichTextObject* child)
216{
217 m_children.Append(child);
218 child->SetParent(this);
219 return m_children.GetCount() - 1;
220}
221
222/// Insert the child in front of the given object, or at the beginning
223bool wxRichTextCompositeObject::InsertChild(wxRichTextObject* child, wxRichTextObject* inFrontOf)
224{
225 if (inFrontOf)
226 {
227 wxRichTextObjectList::compatibility_iterator node = m_children.Find(inFrontOf);
228 m_children.Insert(node, child);
229 }
230 else
231 m_children.Insert(child);
232 child->SetParent(this);
233
234 return true;
235}
236
237/// Delete the child
238bool wxRichTextCompositeObject::RemoveChild(wxRichTextObject* child, bool deleteChild)
239{
240 wxRichTextObjectList::compatibility_iterator node = m_children.Find(child);
241 if (node)
242 {
243 wxRichTextObject* obj = node->GetData();
244 m_children.Erase(node);
245 if (deleteChild)
246 delete obj;
247
248 return true;
249 }
250 return false;
251}
252
253/// Delete all children
254bool wxRichTextCompositeObject::DeleteChildren()
255{
256 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
257 while (node)
258 {
259 wxRichTextObjectList::compatibility_iterator oldNode = node;
260
261 wxRichTextObject* child = node->GetData();
262 child->Dereference(); // Only delete if reference count is zero
263
264 node = node->GetNext();
265 m_children.Erase(oldNode);
266 }
267
268 return true;
269}
270
271/// Get the child count
272size_t wxRichTextCompositeObject::GetChildCount() const
273{
274 return m_children.GetCount();
275}
276
277/// Copy
278void wxRichTextCompositeObject::Copy(const wxRichTextCompositeObject& obj)
279{
280 wxRichTextObject::Copy(obj);
281
282 DeleteChildren();
283
284 wxRichTextObjectList::compatibility_iterator node = obj.m_children.GetFirst();
285 while (node)
286 {
287 wxRichTextObject* child = node->GetData();
288 wxRichTextObject* newChild = child->Clone();
289 newChild->SetParent(this);
290 m_children.Append(newChild);
291
292 node = node->GetNext();
293 }
294}
295
296/// Hit-testing: returns a flag indicating hit test details, plus
297/// information about position
298int wxRichTextCompositeObject::HitTest(wxDC& dc, const wxPoint& pt, long& textPosition)
299{
300 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
301 while (node)
302 {
303 wxRichTextObject* child = node->GetData();
304
305 int ret = child->HitTest(dc, pt, textPosition);
306 if (ret != wxRICHTEXT_HITTEST_NONE)
307 return ret;
308
309 node = node->GetNext();
310 }
311
312 return wxRICHTEXT_HITTEST_NONE;
313}
314
315/// Finds the absolute position and row height for the given character position
316bool wxRichTextCompositeObject::FindPosition(wxDC& dc, long index, wxPoint& pt, int* height, bool forceLineStart)
317{
318 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
319 while (node)
320 {
321 wxRichTextObject* child = node->GetData();
322
323 if (child->FindPosition(dc, index, pt, height, forceLineStart))
324 return true;
325
326 node = node->GetNext();
327 }
328
329 return false;
330}
331
332/// Calculate range
333void wxRichTextCompositeObject::CalculateRange(long start, long& end)
334{
335 long current = start;
336 long lastEnd = current;
337
338 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
339 while (node)
340 {
341 wxRichTextObject* child = node->GetData();
342 long childEnd = 0;
343
344 child->CalculateRange(current, childEnd);
345 lastEnd = childEnd;
346
347 current = childEnd + 1;
348
349 node = node->GetNext();
350 }
351
352 end = lastEnd;
353
354 // An object with no children has zero length
355 if (m_children.GetCount() == 0)
356 end --;
357
358 m_range.SetRange(start, end);
359}
360
361/// Delete range from layout.
362bool wxRichTextCompositeObject::DeleteRange(const wxRichTextRange& range)
363{
364 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
365
366 while (node)
367 {
368 wxRichTextObject* obj = (wxRichTextObject*) node->GetData();
369 wxRichTextObjectList::compatibility_iterator next = node->GetNext();
370
371 // Delete the range in each paragraph
372
373 // When a chunk has been deleted, internally the content does not
374 // now match the ranges.
375 // However, so long as deletion is not done on the same object twice this is OK.
376 // If you may delete content from the same object twice, recalculate
377 // the ranges inbetween DeleteRange calls by calling CalculateRanges, and
378 // adjust the range you're deleting accordingly.
379
380 if (!obj->GetRange().IsOutside(range))
381 {
382 obj->DeleteRange(range);
383
384 // Delete an empty object, or paragraph within this range.
385 if (obj->IsEmpty() ||
386 (range.GetStart() <= obj->GetRange().GetStart() && range.GetEnd() >= obj->GetRange().GetEnd()))
387 {
388 // An empty paragraph has length 1, so won't be deleted unless the
389 // whole range is deleted.
390 RemoveChild(obj, true);
391 }
392 }
393
394 node = next;
395 }
396
397 return true;
398}
399
400/// Get any text in this object for the given range
401wxString wxRichTextCompositeObject::GetTextForRange(const wxRichTextRange& range) const
402{
403 wxString text;
404 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
405 while (node)
406 {
407 wxRichTextObject* child = node->GetData();
408 wxRichTextRange childRange = range;
409 if (!child->GetRange().IsOutside(range))
410 {
411 childRange.LimitTo(child->GetRange());
412
413 wxString childText = child->GetTextForRange(childRange);
414
415 text += childText;
416 }
417 node = node->GetNext();
418 }
419
420 return text;
421}
422
423/// Recursively merge all pieces that can be merged.
424bool wxRichTextCompositeObject::Defragment()
425{
426 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
427 while (node)
428 {
429 wxRichTextObject* child = node->GetData();
430 wxRichTextCompositeObject* composite = wxDynamicCast(child, wxRichTextCompositeObject);
431 if (composite)
432 composite->Defragment();
433
434 if (node->GetNext())
435 {
436 wxRichTextObject* nextChild = node->GetNext()->GetData();
437 if (child->CanMerge(nextChild) && child->Merge(nextChild))
438 {
439 nextChild->Dereference();
440 m_children.Erase(node->GetNext());
441
442 // Don't set node -- we'll see if we can merge again with the next
443 // child.
444 }
445 else
446 node = node->GetNext();
447 }
448 else
449 node = node->GetNext();
450 }
451
452 return true;
453}
454
455/// Dump to output stream for debugging
456void wxRichTextCompositeObject::Dump(wxTextOutputStream& stream)
457{
458 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
459 while (node)
460 {
461 wxRichTextObject* child = node->GetData();
462 child->Dump(stream);
463 node = node->GetNext();
464 }
465}
466
467
468/*!
469 * wxRichTextBox
470 * This defines a 2D space to lay out objects
471 */
472
473IMPLEMENT_DYNAMIC_CLASS(wxRichTextBox, wxRichTextCompositeObject)
474
475wxRichTextBox::wxRichTextBox(wxRichTextObject* parent):
476 wxRichTextCompositeObject(parent)
477{
478}
479
480/// Draw the item
481bool wxRichTextBox::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextRange& selectionRange, const wxRect& WXUNUSED(rect), int descent, int style)
482{
483 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
484 while (node)
485 {
486 wxRichTextObject* child = node->GetData();
487
488 wxRect childRect = wxRect(child->GetPosition(), child->GetCachedSize());
489 child->Draw(dc, range, selectionRange, childRect, descent, style);
490
491 node = node->GetNext();
492 }
493 return true;
494}
495
496/// Lay the item out
497bool wxRichTextBox::Layout(wxDC& dc, const wxRect& rect, int style)
498{
499 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
500 while (node)
501 {
502 wxRichTextObject* child = node->GetData();
503 child->Layout(dc, rect, style);
504
505 node = node->GetNext();
506 }
507 m_dirty = false;
508 return true;
509}
510
511/// Get/set the size for the given range. Assume only has one child.
512bool wxRichTextBox::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, int flags, wxPoint position) const
513{
514 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
515 if (node)
516 {
517 wxRichTextObject* child = node->GetData();
518 return child->GetRangeSize(range, size, descent, dc, flags, position);
519 }
520 else
521 return false;
522}
523
524/// Copy
525void wxRichTextBox::Copy(const wxRichTextBox& obj)
526{
527 wxRichTextCompositeObject::Copy(obj);
528}
529
530
531/*!
532 * wxRichTextParagraphLayoutBox
533 * This box knows how to lay out paragraphs.
534 */
535
536IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraphLayoutBox, wxRichTextBox)
537
538wxRichTextParagraphLayoutBox::wxRichTextParagraphLayoutBox(wxRichTextObject* parent):
539 wxRichTextBox(parent)
540{
541 Init();
542}
543
544/// Initialize the object.
545void wxRichTextParagraphLayoutBox::Init()
546{
547 m_ctrl = NULL;
548
549 // For now, assume is the only box and has no initial size.
550 m_range = wxRichTextRange(0, -1);
551
552 m_invalidRange.SetRange(-1, -1);
553 m_leftMargin = 4;
554 m_rightMargin = 4;
555 m_topMargin = 4;
556 m_bottomMargin = 4;
557 m_partialParagraph = false;
558}
559
560/// Draw the item
561bool wxRichTextParagraphLayoutBox::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextRange& selectionRange, const wxRect& rect, int descent, int style)
562{
563 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
564 while (node)
565 {
566 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
567 wxASSERT (child != NULL);
568
569 if (child && !child->GetRange().IsOutside(range))
570 {
571 wxRect childRect(child->GetPosition(), child->GetCachedSize());
572
573 if (((style & wxRICHTEXT_DRAW_IGNORE_CACHE) == 0) && childRect.GetTop() > rect.GetBottom())
574 {
575 // Stop drawing
576 break;
577 }
578 else if (((style & wxRICHTEXT_DRAW_IGNORE_CACHE) == 0) && childRect.GetBottom() < rect.GetTop())
579 {
580 // Skip
581 }
582 else
583 child->Draw(dc, range, selectionRange, childRect, descent, style);
584 }
585
586 node = node->GetNext();
587 }
588 return true;
589}
590
591/// Lay the item out
592bool wxRichTextParagraphLayoutBox::Layout(wxDC& dc, const wxRect& rect, int style)
593{
594 wxRect availableSpace;
595 bool formatRect = (style & wxRICHTEXT_LAYOUT_SPECIFIED_RECT) == wxRICHTEXT_LAYOUT_SPECIFIED_RECT;
596
597 // If only laying out a specific area, the passed rect has a different meaning:
598 // the visible part of the buffer. This is used in wxRichTextCtrl::OnSize,
599 // so that during a size, only the visible part will be relaid out, or
600 // it would take too long causing flicker. As an approximation, we assume that
601 // everything up to the start of the visible area is laid out correctly.
602 if (formatRect)
603 {
604 availableSpace = wxRect(0 + m_leftMargin,
605 0 + m_topMargin,
606 rect.width - m_leftMargin - m_rightMargin,
607 rect.height);
608
609 // Invalidate the part of the buffer from the first visible line
610 // to the end. If other parts of the buffer are currently invalid,
611 // then they too will be taken into account if they are above
612 // the visible point.
613 long startPos = 0;
614 wxRichTextLine* line = GetLineAtYPosition(rect.y);
615 if (line)
616 startPos = line->GetAbsoluteRange().GetStart();
617
618 Invalidate(wxRichTextRange(startPos, GetRange().GetEnd()));
619 }
620 else
621 availableSpace = wxRect(rect.x + m_leftMargin,
622 rect.y + m_topMargin,
623 rect.width - m_leftMargin - m_rightMargin,
624 rect.height - m_topMargin - m_bottomMargin);
625
626 int maxWidth = 0;
627
628 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
629
630 bool layoutAll = true;
631
632 // Get invalid range, rounding to paragraph start/end.
633 wxRichTextRange invalidRange = GetInvalidRange(true);
634
635 if (invalidRange == wxRICHTEXT_NONE && !formatRect)
636 return true;
637
638 if (invalidRange == wxRICHTEXT_ALL)
639 layoutAll = true;
640 else // If we know what range is affected, start laying out from that point on.
641 if (invalidRange.GetStart() >= GetRange().GetStart())
642 {
643 wxRichTextParagraph* firstParagraph = GetParagraphAtPosition(invalidRange.GetStart());
644 if (firstParagraph)
645 {
646 wxRichTextObjectList::compatibility_iterator firstNode = m_children.Find(firstParagraph);
647 wxRichTextObjectList::compatibility_iterator previousNode;
648 if ( firstNode )
649 previousNode = firstNode->GetPrevious();
650 if (firstNode)
651 {
652 if (previousNode)
653 {
654 wxRichTextParagraph* previousParagraph = wxDynamicCast(previousNode->GetData(), wxRichTextParagraph);
655 availableSpace.y = previousParagraph->GetPosition().y + previousParagraph->GetCachedSize().y;
656 }
657
658 // Now we're going to start iterating from the first affected paragraph.
659 node = firstNode;
660
661 layoutAll = false;
662 }
663 }
664 }
665
666 // A way to force speedy rest-of-buffer layout (the 'else' below)
667 bool forceQuickLayout = false;
668
669 while (node)
670 {
671 // Assume this box only contains paragraphs
672
673 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
674 wxCHECK_MSG( child, false, _T("Unknown object in layout") );
675
676 // TODO: what if the child hasn't been laid out (e.g. involved in Undo) but still has 'old' lines
677 if ( !forceQuickLayout &&
678 (layoutAll ||
679 child->GetLines().IsEmpty() ||
680 !child->GetRange().IsOutside(invalidRange)) )
681 {
682 child->Layout(dc, availableSpace, style);
683
684 // Layout must set the cached size
685 availableSpace.y += child->GetCachedSize().y;
686 maxWidth = wxMax(maxWidth, child->GetCachedSize().x);
687
688 // If we're just formatting the visible part of the buffer,
689 // and we're now past the bottom of the window, start quick
690 // layout.
691 if (formatRect && child->GetPosition().y > rect.GetBottom())
692 forceQuickLayout = true;
693 }
694 else
695 {
696 // We're outside the immediately affected range, so now let's just
697 // move everything up or down. This assumes that all the children have previously
698 // been laid out and have wrapped line lists associated with them.
699 // TODO: check all paragraphs before the affected range.
700
701 int inc = availableSpace.y - child->GetPosition().y;
702
703 while (node)
704 {
705 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
706 if (child)
707 {
708 if (child->GetLines().GetCount() == 0)
709 child->Layout(dc, availableSpace, style);
710 else
711 child->SetPosition(wxPoint(child->GetPosition().x, child->GetPosition().y + inc));
712
713 availableSpace.y += child->GetCachedSize().y;
714 maxWidth = wxMax(maxWidth, child->GetCachedSize().x);
715 }
716
717 node = node->GetNext();
718 }
719 break;
720 }
721
722 node = node->GetNext();
723 }
724
725 SetCachedSize(wxSize(maxWidth, availableSpace.y));
726
727 m_dirty = false;
728 m_invalidRange = wxRICHTEXT_NONE;
729
730 return true;
731}
732
733/// Copy
734void wxRichTextParagraphLayoutBox::Copy(const wxRichTextParagraphLayoutBox& obj)
735{
736 wxRichTextBox::Copy(obj);
737
738 m_partialParagraph = obj.m_partialParagraph;
739 m_defaultAttributes = obj.m_defaultAttributes;
740}
741
742/// Get/set the size for the given range.
743bool wxRichTextParagraphLayoutBox::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, int flags, wxPoint position) const
744{
745 wxSize sz;
746
747 wxRichTextObjectList::compatibility_iterator startPara = wxRichTextObjectList::compatibility_iterator();
748 wxRichTextObjectList::compatibility_iterator endPara = wxRichTextObjectList::compatibility_iterator();
749
750 // First find the first paragraph whose starting position is within the range.
751 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
752 while (node)
753 {
754 // child is a paragraph
755 wxRichTextObject* child = node->GetData();
756 const wxRichTextRange& r = child->GetRange();
757
758 if (r.GetStart() <= range.GetStart() && r.GetEnd() >= range.GetStart())
759 {
760 startPara = node;
761 break;
762 }
763
764 node = node->GetNext();
765 }
766
767 // Next find the last paragraph containing part of the range
768 node = m_children.GetFirst();
769 while (node)
770 {
771 // child is a paragraph
772 wxRichTextObject* child = node->GetData();
773 const wxRichTextRange& r = child->GetRange();
774
775 if (r.GetStart() <= range.GetEnd() && r.GetEnd() >= range.GetEnd())
776 {
777 endPara = node;
778 break;
779 }
780
781 node = node->GetNext();
782 }
783
784 if (!startPara || !endPara)
785 return false;
786
787 // Now we can add up the sizes
788 for (node = startPara; node ; node = node->GetNext())
789 {
790 // child is a paragraph
791 wxRichTextObject* child = node->GetData();
792 const wxRichTextRange& childRange = child->GetRange();
793 wxRichTextRange rangeToFind = range;
794 rangeToFind.LimitTo(childRange);
795
796 wxSize childSize;
797
798 int childDescent = 0;
799 child->GetRangeSize(rangeToFind, childSize, childDescent, dc, flags, position);
800
801 descent = wxMax(childDescent, descent);
802
803 sz.x = wxMax(sz.x, childSize.x);
804 sz.y += childSize.y;
805
806 if (node == endPara)
807 break;
808 }
809
810 size = sz;
811
812 return true;
813}
814
815/// Get the paragraph at the given position
816wxRichTextParagraph* wxRichTextParagraphLayoutBox::GetParagraphAtPosition(long pos, bool caretPosition) const
817{
818 if (caretPosition)
819 pos ++;
820
821 // First find the first paragraph whose starting position is within the range.
822 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
823 while (node)
824 {
825 // child is a paragraph
826 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
827 wxASSERT (child != NULL);
828
829 // Return first child in buffer if position is -1
830 // if (pos == -1)
831 // return child;
832
833 if (child->GetRange().Contains(pos))
834 return child;
835
836 node = node->GetNext();
837 }
838 return NULL;
839}
840
841/// Get the line at the given position
842wxRichTextLine* wxRichTextParagraphLayoutBox::GetLineAtPosition(long pos, bool caretPosition) const
843{
844 if (caretPosition)
845 pos ++;
846
847 // First find the first paragraph whose starting position is within the range.
848 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
849 while (node)
850 {
851 // child is a paragraph
852 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
853 wxASSERT (child != NULL);
854
855 wxRichTextLineList::compatibility_iterator node2 = child->GetLines().GetFirst();
856 while (node2)
857 {
858 wxRichTextLine* line = node2->GetData();
859
860 wxRichTextRange range = line->GetAbsoluteRange();
861
862 if (range.Contains(pos) ||
863
864 // If the position is end-of-paragraph, then return the last line of
865 // of the paragraph.
866 (range.GetEnd() == child->GetRange().GetEnd()-1) && (pos == child->GetRange().GetEnd()))
867 return line;
868
869 node2 = node2->GetNext();
870 }
871
872 node = node->GetNext();
873 }
874
875 int lineCount = GetLineCount();
876 if (lineCount > 0)
877 return GetLineForVisibleLineNumber(lineCount-1);
878 else
879 return NULL;
880}
881
882/// Get the line at the given y pixel position, or the last line.
883wxRichTextLine* wxRichTextParagraphLayoutBox::GetLineAtYPosition(int y) const
884{
885 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
886 while (node)
887 {
888 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
889 wxASSERT (child != NULL);
890
891 wxRichTextLineList::compatibility_iterator node2 = child->GetLines().GetFirst();
892 while (node2)
893 {
894 wxRichTextLine* line = node2->GetData();
895
896 wxRect rect(line->GetRect());
897
898 if (y <= rect.GetBottom())
899 return line;
900
901 node2 = node2->GetNext();
902 }
903
904 node = node->GetNext();
905 }
906
907 // Return last line
908 int lineCount = GetLineCount();
909 if (lineCount > 0)
910 return GetLineForVisibleLineNumber(lineCount-1);
911 else
912 return NULL;
913}
914
915/// Get the number of visible lines
916int wxRichTextParagraphLayoutBox::GetLineCount() const
917{
918 int count = 0;
919
920 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
921 while (node)
922 {
923 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
924 wxASSERT (child != NULL);
925
926 count += child->GetLines().GetCount();
927 node = node->GetNext();
928 }
929 return count;
930}
931
932
933/// Get the paragraph for a given line
934wxRichTextParagraph* wxRichTextParagraphLayoutBox::GetParagraphForLine(wxRichTextLine* line) const
935{
936 return GetParagraphAtPosition(line->GetAbsoluteRange().GetStart());
937}
938
939/// Get the line size at the given position
940wxSize wxRichTextParagraphLayoutBox::GetLineSizeAtPosition(long pos, bool caretPosition) const
941{
942 wxRichTextLine* line = GetLineAtPosition(pos, caretPosition);
943 if (line)
944 {
945 return line->GetSize();
946 }
947 else
948 return wxSize(0, 0);
949}
950
951
952/// Convenience function to add a paragraph of text
953wxRichTextRange wxRichTextParagraphLayoutBox::AddParagraph(const wxString& text, wxTextAttr* paraStyle)
954{
955 // Don't use the base style, just the default style, and the base style will
956 // be combined at display time.
957 // Divide into paragraph and character styles.
958
959 wxTextAttr defaultCharStyle;
960 wxTextAttr defaultParaStyle;
961
962 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle, defaultCharStyle);
963 wxTextAttr* pStyle = paraStyle ? paraStyle : (wxTextAttr*) & defaultParaStyle;
964 wxTextAttr* cStyle = & defaultCharStyle;
965
966 wxRichTextParagraph* para = new wxRichTextParagraph(text, this, pStyle, cStyle);
967
968 AppendChild(para);
969
970 UpdateRanges();
971 SetDirty(true);
972
973 return para->GetRange();
974}
975
976/// Adds multiple paragraphs, based on newlines.
977wxRichTextRange wxRichTextParagraphLayoutBox::AddParagraphs(const wxString& text, wxTextAttr* paraStyle)
978{
979 // Don't use the base style, just the default style, and the base style will
980 // be combined at display time.
981 // Divide into paragraph and character styles.
982
983 wxTextAttr defaultCharStyle;
984 wxTextAttr defaultParaStyle;
985 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle, defaultCharStyle);
986
987 wxTextAttr* pStyle = paraStyle ? paraStyle : (wxTextAttr*) & defaultParaStyle;
988 wxTextAttr* cStyle = & defaultCharStyle;
989
990 wxRichTextParagraph* firstPara = NULL;
991 wxRichTextParagraph* lastPara = NULL;
992
993 wxRichTextRange range(-1, -1);
994
995 size_t i = 0;
996 size_t len = text.length();
997 wxString line;
998 wxRichTextParagraph* para = new wxRichTextParagraph(wxEmptyString, this, pStyle, cStyle);
999
1000 AppendChild(para);
1001
1002 firstPara = para;
1003 lastPara = para;
1004
1005 while (i < len)
1006 {
1007 wxChar ch = text[i];
1008 if (ch == wxT('\n') || ch == wxT('\r'))
1009 {
1010 if (i != (len-1))
1011 {
1012 wxRichTextPlainText* plainText = (wxRichTextPlainText*) para->GetChildren().GetFirst()->GetData();
1013 plainText->SetText(line);
1014
1015 para = new wxRichTextParagraph(wxEmptyString, this, pStyle, cStyle);
1016
1017 AppendChild(para);
1018
1019 lastPara = para;
1020 line = wxEmptyString;
1021 }
1022 }
1023 else
1024 line += ch;
1025
1026 i ++;
1027 }
1028
1029 if (!line.empty())
1030 {
1031 wxRichTextPlainText* plainText = (wxRichTextPlainText*) para->GetChildren().GetFirst()->GetData();
1032 plainText->SetText(line);
1033 }
1034
1035 UpdateRanges();
1036
1037 SetDirty(false);
1038
1039 return wxRichTextRange(firstPara->GetRange().GetStart(), lastPara->GetRange().GetEnd());
1040}
1041
1042/// Convenience function to add an image
1043wxRichTextRange wxRichTextParagraphLayoutBox::AddImage(const wxImage& image, wxTextAttr* paraStyle)
1044{
1045 // Don't use the base style, just the default style, and the base style will
1046 // be combined at display time.
1047 // Divide into paragraph and character styles.
1048
1049 wxTextAttr defaultCharStyle;
1050 wxTextAttr defaultParaStyle;
1051 wxRichTextSplitParaCharStyles(GetDefaultStyle(), defaultParaStyle, defaultCharStyle);
1052
1053 wxTextAttr* pStyle = paraStyle ? paraStyle : (wxTextAttr*) & defaultParaStyle;
1054 wxTextAttr* cStyle = & defaultCharStyle;
1055
1056 wxRichTextParagraph* para = new wxRichTextParagraph(this, pStyle);
1057 AppendChild(para);
1058 para->AppendChild(new wxRichTextImage(image, this, cStyle));
1059
1060 UpdateRanges();
1061 SetDirty(true);
1062
1063 return para->GetRange();
1064}
1065
1066
1067/// Insert fragment into this box at the given position. If partialParagraph is true,
1068/// it is assumed that the last (or only) paragraph is just a piece of data with no paragraph
1069/// marker.
1070
1071bool wxRichTextParagraphLayoutBox::InsertFragment(long position, wxRichTextParagraphLayoutBox& fragment)
1072{
1073 SetDirty(true);
1074
1075 // First, find the first paragraph whose starting position is within the range.
1076 wxRichTextParagraph* para = GetParagraphAtPosition(position);
1077 if (para)
1078 {
1079 wxTextAttrEx originalAttr = para->GetAttributes();
1080
1081 wxRichTextObjectList::compatibility_iterator node = m_children.Find(para);
1082
1083 // Now split at this position, returning the object to insert the new
1084 // ones in front of.
1085 wxRichTextObject* nextObject = para->SplitAt(position);
1086
1087 // Special case: partial paragraph, just one paragraph. Might be a small amount of
1088 // text, for example, so let's optimize.
1089
1090 if (fragment.GetPartialParagraph() && fragment.GetChildren().GetCount() == 1)
1091 {
1092 // Add the first para to this para...
1093 wxRichTextObjectList::compatibility_iterator firstParaNode = fragment.GetChildren().GetFirst();
1094 if (!firstParaNode)
1095 return false;
1096
1097 // Iterate through the fragment paragraph inserting the content into this paragraph.
1098 wxRichTextParagraph* firstPara = wxDynamicCast(firstParaNode->GetData(), wxRichTextParagraph);
1099 wxASSERT (firstPara != NULL);
1100
1101 wxRichTextObjectList::compatibility_iterator objectNode = firstPara->GetChildren().GetFirst();
1102 while (objectNode)
1103 {
1104 wxRichTextObject* newObj = objectNode->GetData()->Clone();
1105
1106 if (!nextObject)
1107 {
1108 // Append
1109 para->AppendChild(newObj);
1110 }
1111 else
1112 {
1113 // Insert before nextObject
1114 para->InsertChild(newObj, nextObject);
1115 }
1116
1117 objectNode = objectNode->GetNext();
1118 }
1119
1120 return true;
1121 }
1122 else
1123 {
1124 // Procedure for inserting a fragment consisting of a number of
1125 // paragraphs:
1126 //
1127 // 1. Remove and save the content that's after the insertion point, for adding
1128 // back once we've added the fragment.
1129 // 2. Add the content from the first fragment paragraph to the current
1130 // paragraph.
1131 // 3. Add remaining fragment paragraphs after the current paragraph.
1132 // 4. Add back the saved content from the first paragraph. If partialParagraph
1133 // is true, add it to the last paragraph added and not a new one.
1134
1135 // 1. Remove and save objects after split point.
1136 wxList savedObjects;
1137 if (nextObject)
1138 para->MoveToList(nextObject, savedObjects);
1139
1140 // 2. Add the content from the 1st fragment paragraph.
1141 wxRichTextObjectList::compatibility_iterator firstParaNode = fragment.GetChildren().GetFirst();
1142 if (!firstParaNode)
1143 return false;
1144
1145 wxRichTextParagraph* firstPara = wxDynamicCast(firstParaNode->GetData(), wxRichTextParagraph);
1146 wxASSERT(firstPara != NULL);
1147
1148 para->SetAttributes(firstPara->GetAttributes());
1149
1150 // Save empty paragraph attributes for appending later
1151 // These are character attributes deliberately set for a new paragraph. Without this,
1152 // we couldn't pass default attributes when appending a new paragraph.
1153 wxTextAttrEx emptyParagraphAttributes;
1154
1155 wxRichTextObjectList::compatibility_iterator objectNode = firstPara->GetChildren().GetFirst();
1156
1157 if (objectNode && firstPara->GetChildren().GetCount() == 1 && objectNode->GetData()->IsEmpty())
1158 emptyParagraphAttributes = objectNode->GetData()->GetAttributes();
1159
1160 while (objectNode)
1161 {
1162 wxRichTextObject* newObj = objectNode->GetData()->Clone();
1163
1164 // Append
1165 para->AppendChild(newObj);
1166
1167 objectNode = objectNode->GetNext();
1168 }
1169
1170 // 3. Add remaining fragment paragraphs after the current paragraph.
1171 wxRichTextObjectList::compatibility_iterator nextParagraphNode = node->GetNext();
1172 wxRichTextObject* nextParagraph = NULL;
1173 if (nextParagraphNode)
1174 nextParagraph = nextParagraphNode->GetData();
1175
1176 wxRichTextObjectList::compatibility_iterator i = fragment.GetChildren().GetFirst()->GetNext();
1177 wxRichTextParagraph* finalPara = para;
1178
1179 bool needExtraPara = (!i || !fragment.GetPartialParagraph());
1180
1181 // If there was only one paragraph, we need to insert a new one.
1182 while (i)
1183 {
1184 wxRichTextParagraph* para = wxDynamicCast(i->GetData(), wxRichTextParagraph);
1185 wxASSERT( para != NULL );
1186
1187 finalPara = (wxRichTextParagraph*) para->Clone();
1188
1189 if (nextParagraph)
1190 InsertChild(finalPara, nextParagraph);
1191 else
1192 AppendChild(finalPara);
1193
1194 i = i->GetNext();
1195 }
1196
1197 // If there was only one paragraph, or we have full paragraphs in our fragment,
1198 // we need to insert a new one.
1199 if (needExtraPara)
1200 {
1201 finalPara = new wxRichTextParagraph;
1202
1203 if (nextParagraph)
1204 InsertChild(finalPara, nextParagraph);
1205 else
1206 AppendChild(finalPara);
1207 }
1208
1209 // 4. Add back the remaining content.
1210 if (finalPara)
1211 {
1212 if (nextObject)
1213 finalPara->MoveFromList(savedObjects);
1214
1215 // Ensure there's at least one object
1216 if (finalPara->GetChildCount() == 0)
1217 {
1218 wxRichTextPlainText* text = new wxRichTextPlainText(wxEmptyString);
1219 text->SetAttributes(emptyParagraphAttributes);
1220
1221 finalPara->AppendChild(text);
1222 }
1223 }
1224
1225 if (finalPara && finalPara != para)
1226 finalPara->SetAttributes(originalAttr);
1227
1228 return true;
1229 }
1230 }
1231 else
1232 {
1233 // Append
1234 wxRichTextObjectList::compatibility_iterator i = fragment.GetChildren().GetFirst();
1235 while (i)
1236 {
1237 wxRichTextParagraph* para = wxDynamicCast(i->GetData(), wxRichTextParagraph);
1238 wxASSERT( para != NULL );
1239
1240 AppendChild(para->Clone());
1241
1242 i = i->GetNext();
1243 }
1244
1245 return true;
1246 }
1247}
1248
1249/// Make a copy of the fragment corresponding to the given range, putting it in 'fragment'.
1250/// If there was an incomplete paragraph at the end, partialParagraph is set to true.
1251bool wxRichTextParagraphLayoutBox::CopyFragment(const wxRichTextRange& range, wxRichTextParagraphLayoutBox& fragment)
1252{
1253 wxRichTextObjectList::compatibility_iterator i = GetChildren().GetFirst();
1254 while (i)
1255 {
1256 wxRichTextParagraph* para = wxDynamicCast(i->GetData(), wxRichTextParagraph);
1257 wxASSERT( para != NULL );
1258
1259 if (!para->GetRange().IsOutside(range))
1260 {
1261 fragment.AppendChild(para->Clone());
1262 }
1263 i = i->GetNext();
1264 }
1265
1266 // Now top and tail the first and last paragraphs in our new fragment (which might be the same).
1267 if (!fragment.IsEmpty())
1268 {
1269 wxRichTextRange topTailRange(range);
1270
1271 wxRichTextParagraph* firstPara = wxDynamicCast(fragment.GetChildren().GetFirst()->GetData(), wxRichTextParagraph);
1272 wxASSERT( firstPara != NULL );
1273
1274 // Chop off the start of the paragraph
1275 if (topTailRange.GetStart() > firstPara->GetRange().GetStart())
1276 {
1277 wxRichTextRange r(firstPara->GetRange().GetStart(), topTailRange.GetStart()-1);
1278 firstPara->DeleteRange(r);
1279
1280 // Make sure the numbering is correct
1281 long end;
1282 fragment.CalculateRange(firstPara->GetRange().GetStart(), end);
1283
1284 // Now, we've deleted some positions, so adjust the range
1285 // accordingly.
1286 topTailRange.SetEnd(topTailRange.GetEnd() - r.GetLength());
1287 }
1288
1289 wxRichTextParagraph* lastPara = wxDynamicCast(fragment.GetChildren().GetLast()->GetData(), wxRichTextParagraph);
1290 wxASSERT( lastPara != NULL );
1291
1292 if (topTailRange.GetEnd() < (lastPara->GetRange().GetEnd()-1))
1293 {
1294 wxRichTextRange r(topTailRange.GetEnd()+1, lastPara->GetRange().GetEnd()-1); /* -1 since actual text ends 1 position before end of para marker */
1295 lastPara->DeleteRange(r);
1296
1297 // Make sure the numbering is correct
1298 long end;
1299 fragment.CalculateRange(firstPara->GetRange().GetStart(), end);
1300
1301 // We only have part of a paragraph at the end
1302 fragment.SetPartialParagraph(true);
1303 }
1304 else
1305 {
1306 if (topTailRange.GetEnd() == (lastPara->GetRange().GetEnd() - 1))
1307 // We have a partial paragraph (don't save last new paragraph marker)
1308 fragment.SetPartialParagraph(true);
1309 else
1310 // We have a complete paragraph
1311 fragment.SetPartialParagraph(false);
1312 }
1313 }
1314
1315 return true;
1316}
1317
1318/// Given a position, get the number of the visible line (potentially many to a paragraph),
1319/// starting from zero at the start of the buffer.
1320long wxRichTextParagraphLayoutBox::GetVisibleLineNumber(long pos, bool caretPosition, bool startOfLine) const
1321{
1322 if (caretPosition)
1323 pos ++;
1324
1325 int lineCount = 0;
1326
1327 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
1328 while (node)
1329 {
1330 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
1331 wxASSERT( child != NULL );
1332
1333 if (child->GetRange().Contains(pos))
1334 {
1335 wxRichTextLineList::compatibility_iterator node2 = child->GetLines().GetFirst();
1336 while (node2)
1337 {
1338 wxRichTextLine* line = node2->GetData();
1339 wxRichTextRange lineRange = line->GetAbsoluteRange();
1340
1341 if (lineRange.Contains(pos))
1342 {
1343 // If the caret is displayed at the end of the previous wrapped line,
1344 // we want to return the line it's _displayed_ at (not the actual line
1345 // containing the position).
1346 if (lineRange.GetStart() == pos && !startOfLine && child->GetRange().GetStart() != pos)
1347 return lineCount - 1;
1348 else
1349 return lineCount;
1350 }
1351
1352 lineCount ++;
1353
1354 node2 = node2->GetNext();
1355 }
1356 // If we didn't find it in the lines, it must be
1357 // the last position of the paragraph. So return the last line.
1358 return lineCount-1;
1359 }
1360 else
1361 lineCount += child->GetLines().GetCount();
1362
1363 node = node->GetNext();
1364 }
1365
1366 // Not found
1367 return -1;
1368}
1369
1370/// Given a line number, get the corresponding wxRichTextLine object.
1371wxRichTextLine* wxRichTextParagraphLayoutBox::GetLineForVisibleLineNumber(long lineNumber) const
1372{
1373 int lineCount = 0;
1374
1375 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
1376 while (node)
1377 {
1378 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
1379 wxASSERT(child != NULL);
1380
1381 if (lineNumber < (int) (child->GetLines().GetCount() + lineCount))
1382 {
1383 wxRichTextLineList::compatibility_iterator node2 = child->GetLines().GetFirst();
1384 while (node2)
1385 {
1386 wxRichTextLine* line = node2->GetData();
1387
1388 if (lineCount == lineNumber)
1389 return line;
1390
1391 lineCount ++;
1392
1393 node2 = node2->GetNext();
1394 }
1395 }
1396 else
1397 lineCount += child->GetLines().GetCount();
1398
1399 node = node->GetNext();
1400 }
1401
1402 // Didn't find it
1403 return NULL;
1404}
1405
1406/// Delete range from layout.
1407bool wxRichTextParagraphLayoutBox::DeleteRange(const wxRichTextRange& range)
1408{
1409 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
1410
1411 wxRichTextParagraph* firstPara = NULL;
1412 while (node)
1413 {
1414 wxRichTextParagraph* obj = wxDynamicCast(node->GetData(), wxRichTextParagraph);
1415 wxASSERT (obj != NULL);
1416
1417 wxRichTextObjectList::compatibility_iterator next = node->GetNext();
1418
1419 // Delete the range in each paragraph
1420
1421 if (!obj->GetRange().IsOutside(range))
1422 {
1423 // Deletes the content of this object within the given range
1424 obj->DeleteRange(range);
1425
1426 wxRichTextRange thisRange = obj->GetRange();
1427
1428 // If the whole paragraph is within the range to delete,
1429 // delete the whole thing.
1430 if (range.GetStart() <= thisRange.GetStart() && range.GetEnd() >= thisRange.GetEnd())
1431 {
1432 // Delete the whole object
1433 RemoveChild(obj, true);
1434 obj = NULL;
1435 }
1436 else if (!firstPara)
1437 firstPara = obj;
1438
1439 // If the range includes the paragraph end, we need to join this
1440 // and the next paragraph.
1441 if (range.GetEnd() <= thisRange.GetEnd())
1442 {
1443 // We need to move the objects from the next paragraph
1444 // to this paragraph
1445
1446 wxRichTextParagraph* nextParagraph = NULL;
1447 if ((range.GetEnd() < thisRange.GetEnd()) && obj)
1448 nextParagraph = obj;
1449 else
1450 {
1451 // We're ending at the end of the paragraph, so merge the _next_ paragraph.
1452 if (next)
1453 nextParagraph = wxDynamicCast(next->GetData(), wxRichTextParagraph);
1454 }
1455
1456 bool applyFinalParagraphStyle = firstPara && nextParagraph && nextParagraph != firstPara;
1457
1458 wxTextAttrEx nextParaAttr;
1459 if (applyFinalParagraphStyle)
1460 nextParaAttr = nextParagraph->GetAttributes();
1461
1462 if (firstPara && nextParagraph && firstPara != nextParagraph)
1463 {
1464 // Move the objects to the previous para
1465 wxRichTextObjectList::compatibility_iterator node1 = nextParagraph->GetChildren().GetFirst();
1466
1467 while (node1)
1468 {
1469 wxRichTextObject* obj1 = node1->GetData();
1470
1471 // If the object is empty, optimise it out
1472 if (obj1->IsEmpty())
1473 {
1474 delete obj1;
1475 }
1476 else
1477 {
1478 firstPara->AppendChild(obj1);
1479 }
1480
1481 wxRichTextObjectList::compatibility_iterator next1 = node1->GetNext();
1482 nextParagraph->GetChildren().Erase(node1);
1483
1484 node1 = next1;
1485 }
1486
1487 // Delete the paragraph
1488 RemoveChild(nextParagraph, true);
1489 }
1490
1491 if (applyFinalParagraphStyle)
1492 firstPara->SetAttributes(nextParaAttr);
1493
1494 return true;
1495 }
1496 }
1497
1498 node = next;
1499 }
1500
1501 return true;
1502}
1503
1504/// Get any text in this object for the given range
1505wxString wxRichTextParagraphLayoutBox::GetTextForRange(const wxRichTextRange& range) const
1506{
1507 int lineCount = 0;
1508 wxString text;
1509 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
1510 while (node)
1511 {
1512 wxRichTextObject* child = node->GetData();
1513 if (!child->GetRange().IsOutside(range))
1514 {
1515 wxRichTextRange childRange = range;
1516 childRange.LimitTo(child->GetRange());
1517
1518 wxString childText = child->GetTextForRange(childRange);
1519
1520 text += childText;
1521
1522 if ((childRange.GetEnd() == child->GetRange().GetEnd()) && node->GetNext())
1523 text += wxT("\n");
1524
1525 lineCount ++;
1526 }
1527 node = node->GetNext();
1528 }
1529
1530 return text;
1531}
1532
1533/// Get all the text
1534wxString wxRichTextParagraphLayoutBox::GetText() const
1535{
1536 return GetTextForRange(GetRange());
1537}
1538
1539/// Get the paragraph by number
1540wxRichTextParagraph* wxRichTextParagraphLayoutBox::GetParagraphAtLine(long paragraphNumber) const
1541{
1542 if ((size_t) paragraphNumber >= GetChildCount())
1543 return NULL;
1544
1545 return (wxRichTextParagraph*) GetChild((size_t) paragraphNumber);
1546}
1547
1548/// Get the length of the paragraph
1549int wxRichTextParagraphLayoutBox::GetParagraphLength(long paragraphNumber) const
1550{
1551 wxRichTextParagraph* para = GetParagraphAtLine(paragraphNumber);
1552 if (para)
1553 return para->GetRange().GetLength() - 1; // don't include newline
1554 else
1555 return 0;
1556}
1557
1558/// Get the text of the paragraph
1559wxString wxRichTextParagraphLayoutBox::GetParagraphText(long paragraphNumber) const
1560{
1561 wxRichTextParagraph* para = GetParagraphAtLine(paragraphNumber);
1562 if (para)
1563 return para->GetTextForRange(para->GetRange());
1564 else
1565 return wxEmptyString;
1566}
1567
1568/// Convert zero-based line column and paragraph number to a position.
1569long wxRichTextParagraphLayoutBox::XYToPosition(long x, long y) const
1570{
1571 wxRichTextParagraph* para = GetParagraphAtLine(y);
1572 if (para)
1573 {
1574 return para->GetRange().GetStart() + x;
1575 }
1576 else
1577 return -1;
1578}
1579
1580/// Convert zero-based position to line column and paragraph number
1581bool wxRichTextParagraphLayoutBox::PositionToXY(long pos, long* x, long* y) const
1582{
1583 wxRichTextParagraph* para = GetParagraphAtPosition(pos);
1584 if (para)
1585 {
1586 int count = 0;
1587 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
1588 while (node)
1589 {
1590 wxRichTextObject* child = node->GetData();
1591 if (child == para)
1592 break;
1593 count ++;
1594 node = node->GetNext();
1595 }
1596
1597 *y = count;
1598 *x = pos - para->GetRange().GetStart();
1599
1600 return true;
1601 }
1602 else
1603 return false;
1604}
1605
1606/// Get the leaf object in a paragraph at this position.
1607/// Given a line number, get the corresponding wxRichTextLine object.
1608wxRichTextObject* wxRichTextParagraphLayoutBox::GetLeafObjectAtPosition(long position) const
1609{
1610 wxRichTextParagraph* para = GetParagraphAtPosition(position);
1611 if (para)
1612 {
1613 wxRichTextObjectList::compatibility_iterator node = para->GetChildren().GetFirst();
1614
1615 while (node)
1616 {
1617 wxRichTextObject* child = node->GetData();
1618 if (child->GetRange().Contains(position))
1619 return child;
1620
1621 node = node->GetNext();
1622 }
1623 if (position == para->GetRange().GetEnd() && para->GetChildCount() > 0)
1624 return para->GetChildren().GetLast()->GetData();
1625 }
1626 return NULL;
1627}
1628
1629/// Set character or paragraph text attributes: apply character styles only to immediate text nodes
1630bool wxRichTextParagraphLayoutBox::SetStyle(const wxRichTextRange& range, const wxTextAttr& style, int flags)
1631{
1632 bool characterStyle = false;
1633 bool paragraphStyle = false;
1634
1635 if (style.IsCharacterStyle())
1636 characterStyle = true;
1637 if (style.IsParagraphStyle())
1638 paragraphStyle = true;
1639
1640 bool withUndo = ((flags & wxRICHTEXT_SETSTYLE_WITH_UNDO) != 0);
1641 bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
1642 bool parasOnly = ((flags & wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY) != 0);
1643 bool charactersOnly = ((flags & wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY) != 0);
1644 bool resetExistingStyle = ((flags & wxRICHTEXT_SETSTYLE_RESET) != 0);
1645 bool removeStyle = ((flags & wxRICHTEXT_SETSTYLE_REMOVE) != 0);
1646
1647 // Apply paragraph style first, if any
1648 wxTextAttr wholeStyle(style);
1649
1650 if (!removeStyle && wholeStyle.HasParagraphStyleName() && GetStyleSheet())
1651 {
1652 wxRichTextParagraphStyleDefinition* def = GetStyleSheet()->FindParagraphStyle(wholeStyle.GetParagraphStyleName());
1653 if (def)
1654 wxRichTextApplyStyle(wholeStyle, def->GetStyleMergedWithBase(GetStyleSheet()));
1655 }
1656
1657 // Limit the attributes to be set to the content to only character attributes.
1658 wxTextAttr characterAttributes(wholeStyle);
1659 characterAttributes.SetFlags(characterAttributes.GetFlags() & (wxTEXT_ATTR_CHARACTER));
1660
1661 if (!removeStyle && characterAttributes.HasCharacterStyleName() && GetStyleSheet())
1662 {
1663 wxRichTextCharacterStyleDefinition* def = GetStyleSheet()->FindCharacterStyle(characterAttributes.GetCharacterStyleName());
1664 if (def)
1665 wxRichTextApplyStyle(characterAttributes, def->GetStyleMergedWithBase(GetStyleSheet()));
1666 }
1667
1668 // If we are associated with a control, make undoable; otherwise, apply immediately
1669 // to the data.
1670
1671 bool haveControl = (GetRichTextCtrl() != NULL);
1672
1673 wxRichTextAction* action = NULL;
1674
1675 if (haveControl && withUndo)
1676 {
1677 action = new wxRichTextAction(NULL, _("Change Style"), wxRICHTEXT_CHANGE_STYLE, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
1678 action->SetRange(range);
1679 action->SetPosition(GetRichTextCtrl()->GetCaretPosition());
1680 }
1681
1682 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
1683 while (node)
1684 {
1685 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
1686 wxASSERT (para != NULL);
1687
1688 if (para && para->GetChildCount() > 0)
1689 {
1690 // Stop searching if we're beyond the range of interest
1691 if (para->GetRange().GetStart() > range.GetEnd())
1692 break;
1693
1694 if (!para->GetRange().IsOutside(range))
1695 {
1696 // We'll be using a copy of the paragraph to make style changes,
1697 // not updating the buffer directly.
1698 wxRichTextParagraph* newPara wxDUMMY_INITIALIZE(NULL);
1699
1700 if (haveControl && withUndo)
1701 {
1702 newPara = new wxRichTextParagraph(*para);
1703 action->GetNewParagraphs().AppendChild(newPara);
1704
1705 // Also store the old ones for Undo
1706 action->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para));
1707 }
1708 else
1709 newPara = para;
1710
1711 // If we're specifying paragraphs only, then we really mean character formatting
1712 // to be included in the paragraph style
1713 if ((paragraphStyle || parasOnly) && !charactersOnly)
1714 {
1715 if (removeStyle)
1716 {
1717 // Removes the given style from the paragraph
1718 wxRichTextRemoveStyle(newPara->GetAttributes(), style);
1719 }
1720 else if (resetExistingStyle)
1721 newPara->GetAttributes() = wholeStyle;
1722 else
1723 {
1724 if (applyMinimal)
1725 {
1726 // Only apply attributes that will make a difference to the combined
1727 // style as seen on the display
1728 wxTextAttr combinedAttr(para->GetCombinedAttributes());
1729 wxRichTextApplyStyle(newPara->GetAttributes(), wholeStyle, & combinedAttr);
1730 }
1731 else
1732 wxRichTextApplyStyle(newPara->GetAttributes(), wholeStyle);
1733 }
1734 }
1735
1736 // When applying paragraph styles dynamically, don't change the text objects' attributes
1737 // since they will computed as needed. Only apply the character styling if it's _only_
1738 // character styling. This policy is subject to change and might be put under user control.
1739
1740 // Hm. we might well be applying a mix of paragraph and character styles, in which
1741 // case we _do_ want to apply character styles regardless of what para styles are set.
1742 // But if we're applying a paragraph style, which has some character attributes, but
1743 // we only want the paragraphs to hold this character style, then we _don't_ want to
1744 // apply the character style. So we need to be able to choose.
1745
1746 // if (!paragraphStyle && characterStyle && range.GetStart() != newPara->GetRange().GetEnd())
1747 if (!parasOnly && characterStyle && range.GetStart() != newPara->GetRange().GetEnd())
1748 {
1749 wxRichTextRange childRange(range);
1750 childRange.LimitTo(newPara->GetRange());
1751
1752 // Find the starting position and if necessary split it so
1753 // we can start applying a different style.
1754 // TODO: check that the style actually changes or is different
1755 // from style outside of range
1756 wxRichTextObject* firstObject wxDUMMY_INITIALIZE(NULL);
1757 wxRichTextObject* lastObject wxDUMMY_INITIALIZE(NULL);
1758
1759 if (childRange.GetStart() == newPara->GetRange().GetStart())
1760 firstObject = newPara->GetChildren().GetFirst()->GetData();
1761 else
1762 firstObject = newPara->SplitAt(range.GetStart());
1763
1764 // Increment by 1 because we're apply the style one _after_ the split point
1765 long splitPoint = childRange.GetEnd();
1766 if (splitPoint != newPara->GetRange().GetEnd())
1767 splitPoint ++;
1768
1769 // Find last object
1770 if (splitPoint == newPara->GetRange().GetEnd() || splitPoint == (newPara->GetRange().GetEnd() - 1))
1771 lastObject = newPara->GetChildren().GetLast()->GetData();
1772 else
1773 // lastObject is set as a side-effect of splitting. It's
1774 // returned as the object before the new object.
1775 (void) newPara->SplitAt(splitPoint, & lastObject);
1776
1777 wxASSERT(firstObject != NULL);
1778 wxASSERT(lastObject != NULL);
1779
1780 if (!firstObject || !lastObject)
1781 continue;
1782
1783 wxRichTextObjectList::compatibility_iterator firstNode = newPara->GetChildren().Find(firstObject);
1784 wxRichTextObjectList::compatibility_iterator lastNode = newPara->GetChildren().Find(lastObject);
1785
1786 wxASSERT(firstNode);
1787 wxASSERT(lastNode);
1788
1789 wxRichTextObjectList::compatibility_iterator node2 = firstNode;
1790
1791 while (node2)
1792 {
1793 wxRichTextObject* child = node2->GetData();
1794
1795 if (removeStyle)
1796 {
1797 // Removes the given style from the paragraph
1798 wxRichTextRemoveStyle(child->GetAttributes(), style);
1799 }
1800 else if (resetExistingStyle)
1801 child->GetAttributes() = characterAttributes;
1802 else
1803 {
1804 if (applyMinimal)
1805 {
1806 // Only apply attributes that will make a difference to the combined
1807 // style as seen on the display
1808 wxTextAttr combinedAttr(newPara->GetCombinedAttributes(child->GetAttributes()));
1809 wxRichTextApplyStyle(child->GetAttributes(), characterAttributes, & combinedAttr);
1810 }
1811 else
1812 wxRichTextApplyStyle(child->GetAttributes(), characterAttributes);
1813 }
1814
1815 if (node2 == lastNode)
1816 break;
1817
1818 node2 = node2->GetNext();
1819 }
1820 }
1821 }
1822 }
1823
1824 node = node->GetNext();
1825 }
1826
1827 // Do action, or delay it until end of batch.
1828 if (haveControl && withUndo)
1829 GetRichTextCtrl()->GetBuffer().SubmitAction(action);
1830
1831 return true;
1832}
1833
1834/// Get the text attributes for this position.
1835bool wxRichTextParagraphLayoutBox::GetStyle(long position, wxTextAttr& style)
1836{
1837 return DoGetStyle(position, style, true);
1838}
1839
1840bool wxRichTextParagraphLayoutBox::GetUncombinedStyle(long position, wxTextAttr& style)
1841{
1842 return DoGetStyle(position, style, false);
1843}
1844
1845/// Implementation helper for GetStyle. If combineStyles is true, combine base, paragraph and
1846/// context attributes.
1847bool wxRichTextParagraphLayoutBox::DoGetStyle(long position, wxTextAttr& style, bool combineStyles)
1848{
1849 wxRichTextObject* obj wxDUMMY_INITIALIZE(NULL);
1850
1851 if (style.IsParagraphStyle())
1852 {
1853 obj = GetParagraphAtPosition(position);
1854 if (obj)
1855 {
1856 if (combineStyles)
1857 {
1858 // Start with the base style
1859 style = GetAttributes();
1860
1861 // Apply the paragraph style
1862 wxRichTextApplyStyle(style, obj->GetAttributes());
1863 }
1864 else
1865 style = obj->GetAttributes();
1866
1867 return true;
1868 }
1869 }
1870 else
1871 {
1872 obj = GetLeafObjectAtPosition(position);
1873 if (obj)
1874 {
1875 if (combineStyles)
1876 {
1877 wxRichTextParagraph* para = wxDynamicCast(obj->GetParent(), wxRichTextParagraph);
1878 style = para ? para->GetCombinedAttributes(obj->GetAttributes()) : obj->GetAttributes();
1879 }
1880 else
1881 style = obj->GetAttributes();
1882
1883 return true;
1884 }
1885 }
1886 return false;
1887}
1888
1889static bool wxHasStyle(long flags, long style)
1890{
1891 return (flags & style) != 0;
1892}
1893
1894/// Combines 'style' with 'currentStyle' for the purpose of summarising the attributes of a range of
1895/// content.
1896bool wxRichTextParagraphLayoutBox::CollectStyle(wxTextAttr& currentStyle, const wxTextAttr& style, long& multipleStyleAttributes, int& multipleTextEffectAttributes)
1897{
1898 if (style.HasFont())
1899 {
1900 if (style.HasFontSize() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_FONT_SIZE))
1901 {
1902 if (currentStyle.HasFontSize())
1903 {
1904 if (currentStyle.GetFontSize() != style.GetFontSize())
1905 {
1906 // Clash of style - mark as such
1907 multipleStyleAttributes |= wxTEXT_ATTR_FONT_SIZE;
1908 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_FONT_SIZE);
1909 }
1910 }
1911 else
1912 {
1913 currentStyle.SetFontSize(style.GetFontSize());
1914 }
1915 }
1916
1917 if (style.HasFontItalic() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_FONT_ITALIC))
1918 {
1919 if (currentStyle.HasFontItalic())
1920 {
1921 if (currentStyle.GetFontStyle() != style.GetFontStyle())
1922 {
1923 // Clash of style - mark as such
1924 multipleStyleAttributes |= wxTEXT_ATTR_FONT_ITALIC;
1925 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_FONT_ITALIC);
1926 }
1927 }
1928 else
1929 {
1930 currentStyle.SetFontStyle(style.GetFontStyle());
1931 }
1932 }
1933
1934 if (style.HasFontWeight() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_FONT_WEIGHT))
1935 {
1936 if (currentStyle.HasFontWeight())
1937 {
1938 if (currentStyle.GetFontWeight() != style.GetFontWeight())
1939 {
1940 // Clash of style - mark as such
1941 multipleStyleAttributes |= wxTEXT_ATTR_FONT_WEIGHT;
1942 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_FONT_WEIGHT);
1943 }
1944 }
1945 else
1946 {
1947 currentStyle.SetFontWeight(style.GetFontWeight());
1948 }
1949 }
1950
1951 if (style.HasFontFaceName() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_FONT_FACE))
1952 {
1953 if (currentStyle.HasFontFaceName())
1954 {
1955 wxString faceName1(currentStyle.GetFontFaceName());
1956 wxString faceName2(style.GetFontFaceName());
1957
1958 if (faceName1 != faceName2)
1959 {
1960 // Clash of style - mark as such
1961 multipleStyleAttributes |= wxTEXT_ATTR_FONT_FACE;
1962 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_FONT_FACE);
1963 }
1964 }
1965 else
1966 {
1967 currentStyle.SetFontFaceName(style.GetFontFaceName());
1968 }
1969 }
1970
1971 if (style.HasFontUnderlined() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_FONT_UNDERLINE))
1972 {
1973 if (currentStyle.HasFontUnderlined())
1974 {
1975 if (currentStyle.GetFontUnderlined() != style.GetFontUnderlined())
1976 {
1977 // Clash of style - mark as such
1978 multipleStyleAttributes |= wxTEXT_ATTR_FONT_UNDERLINE;
1979 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_FONT_UNDERLINE);
1980 }
1981 }
1982 else
1983 {
1984 currentStyle.SetFontUnderlined(style.GetFontUnderlined());
1985 }
1986 }
1987 }
1988
1989 if (style.HasTextColour() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_TEXT_COLOUR))
1990 {
1991 if (currentStyle.HasTextColour())
1992 {
1993 if (currentStyle.GetTextColour() != style.GetTextColour())
1994 {
1995 // Clash of style - mark as such
1996 multipleStyleAttributes |= wxTEXT_ATTR_TEXT_COLOUR;
1997 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_TEXT_COLOUR);
1998 }
1999 }
2000 else
2001 currentStyle.SetTextColour(style.GetTextColour());
2002 }
2003
2004 if (style.HasBackgroundColour() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_BACKGROUND_COLOUR))
2005 {
2006 if (currentStyle.HasBackgroundColour())
2007 {
2008 if (currentStyle.GetBackgroundColour() != style.GetBackgroundColour())
2009 {
2010 // Clash of style - mark as such
2011 multipleStyleAttributes |= wxTEXT_ATTR_BACKGROUND_COLOUR;
2012 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_BACKGROUND_COLOUR);
2013 }
2014 }
2015 else
2016 currentStyle.SetBackgroundColour(style.GetBackgroundColour());
2017 }
2018
2019 if (style.HasAlignment() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_ALIGNMENT))
2020 {
2021 if (currentStyle.HasAlignment())
2022 {
2023 if (currentStyle.GetAlignment() != style.GetAlignment())
2024 {
2025 // Clash of style - mark as such
2026 multipleStyleAttributes |= wxTEXT_ATTR_ALIGNMENT;
2027 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_ALIGNMENT);
2028 }
2029 }
2030 else
2031 currentStyle.SetAlignment(style.GetAlignment());
2032 }
2033
2034 if (style.HasTabs() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_TABS))
2035 {
2036 if (currentStyle.HasTabs())
2037 {
2038 if (!wxRichTextTabsEq(currentStyle.GetTabs(), style.GetTabs()))
2039 {
2040 // Clash of style - mark as such
2041 multipleStyleAttributes |= wxTEXT_ATTR_TABS;
2042 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_TABS);
2043 }
2044 }
2045 else
2046 currentStyle.SetTabs(style.GetTabs());
2047 }
2048
2049 if (style.HasLeftIndent() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_LEFT_INDENT))
2050 {
2051 if (currentStyle.HasLeftIndent())
2052 {
2053 if (currentStyle.GetLeftIndent() != style.GetLeftIndent() || currentStyle.GetLeftSubIndent() != style.GetLeftSubIndent())
2054 {
2055 // Clash of style - mark as such
2056 multipleStyleAttributes |= wxTEXT_ATTR_LEFT_INDENT;
2057 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_LEFT_INDENT);
2058 }
2059 }
2060 else
2061 currentStyle.SetLeftIndent(style.GetLeftIndent(), style.GetLeftSubIndent());
2062 }
2063
2064 if (style.HasRightIndent() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_RIGHT_INDENT))
2065 {
2066 if (currentStyle.HasRightIndent())
2067 {
2068 if (currentStyle.GetRightIndent() != style.GetRightIndent())
2069 {
2070 // Clash of style - mark as such
2071 multipleStyleAttributes |= wxTEXT_ATTR_RIGHT_INDENT;
2072 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_RIGHT_INDENT);
2073 }
2074 }
2075 else
2076 currentStyle.SetRightIndent(style.GetRightIndent());
2077 }
2078
2079 if (style.HasParagraphSpacingAfter() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_PARA_SPACING_AFTER))
2080 {
2081 if (currentStyle.HasParagraphSpacingAfter())
2082 {
2083 if (currentStyle.GetParagraphSpacingAfter() != style.GetParagraphSpacingAfter())
2084 {
2085 // Clash of style - mark as such
2086 multipleStyleAttributes |= wxTEXT_ATTR_PARA_SPACING_AFTER;
2087 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_PARA_SPACING_AFTER);
2088 }
2089 }
2090 else
2091 currentStyle.SetParagraphSpacingAfter(style.GetParagraphSpacingAfter());
2092 }
2093
2094 if (style.HasParagraphSpacingBefore() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_PARA_SPACING_BEFORE))
2095 {
2096 if (currentStyle.HasParagraphSpacingBefore())
2097 {
2098 if (currentStyle.GetParagraphSpacingBefore() != style.GetParagraphSpacingBefore())
2099 {
2100 // Clash of style - mark as such
2101 multipleStyleAttributes |= wxTEXT_ATTR_PARA_SPACING_BEFORE;
2102 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_PARA_SPACING_BEFORE);
2103 }
2104 }
2105 else
2106 currentStyle.SetParagraphSpacingBefore(style.GetParagraphSpacingBefore());
2107 }
2108
2109 if (style.HasLineSpacing() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_LINE_SPACING))
2110 {
2111 if (currentStyle.HasLineSpacing())
2112 {
2113 if (currentStyle.GetLineSpacing() != style.GetLineSpacing())
2114 {
2115 // Clash of style - mark as such
2116 multipleStyleAttributes |= wxTEXT_ATTR_LINE_SPACING;
2117 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_LINE_SPACING);
2118 }
2119 }
2120 else
2121 currentStyle.SetLineSpacing(style.GetLineSpacing());
2122 }
2123
2124 if (style.HasCharacterStyleName() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_CHARACTER_STYLE_NAME))
2125 {
2126 if (currentStyle.HasCharacterStyleName())
2127 {
2128 if (currentStyle.GetCharacterStyleName() != style.GetCharacterStyleName())
2129 {
2130 // Clash of style - mark as such
2131 multipleStyleAttributes |= wxTEXT_ATTR_CHARACTER_STYLE_NAME;
2132 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_CHARACTER_STYLE_NAME);
2133 }
2134 }
2135 else
2136 currentStyle.SetCharacterStyleName(style.GetCharacterStyleName());
2137 }
2138
2139 if (style.HasParagraphStyleName() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_PARAGRAPH_STYLE_NAME))
2140 {
2141 if (currentStyle.HasParagraphStyleName())
2142 {
2143 if (currentStyle.GetParagraphStyleName() != style.GetParagraphStyleName())
2144 {
2145 // Clash of style - mark as such
2146 multipleStyleAttributes |= wxTEXT_ATTR_PARAGRAPH_STYLE_NAME;
2147 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_PARAGRAPH_STYLE_NAME);
2148 }
2149 }
2150 else
2151 currentStyle.SetParagraphStyleName(style.GetParagraphStyleName());
2152 }
2153
2154 if (style.HasListStyleName() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_LIST_STYLE_NAME))
2155 {
2156 if (currentStyle.HasListStyleName())
2157 {
2158 if (currentStyle.GetListStyleName() != style.GetListStyleName())
2159 {
2160 // Clash of style - mark as such
2161 multipleStyleAttributes |= wxTEXT_ATTR_LIST_STYLE_NAME;
2162 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_LIST_STYLE_NAME);
2163 }
2164 }
2165 else
2166 currentStyle.SetListStyleName(style.GetListStyleName());
2167 }
2168
2169 if (style.HasBulletStyle() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_BULLET_STYLE))
2170 {
2171 if (currentStyle.HasBulletStyle())
2172 {
2173 if (currentStyle.GetBulletStyle() != style.GetBulletStyle())
2174 {
2175 // Clash of style - mark as such
2176 multipleStyleAttributes |= wxTEXT_ATTR_BULLET_STYLE;
2177 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_BULLET_STYLE);
2178 }
2179 }
2180 else
2181 currentStyle.SetBulletStyle(style.GetBulletStyle());
2182 }
2183
2184 if (style.HasBulletNumber() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_BULLET_NUMBER))
2185 {
2186 if (currentStyle.HasBulletNumber())
2187 {
2188 if (currentStyle.GetBulletNumber() != style.GetBulletNumber())
2189 {
2190 // Clash of style - mark as such
2191 multipleStyleAttributes |= wxTEXT_ATTR_BULLET_NUMBER;
2192 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_BULLET_NUMBER);
2193 }
2194 }
2195 else
2196 currentStyle.SetBulletNumber(style.GetBulletNumber());
2197 }
2198
2199 if (style.HasBulletText() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_BULLET_TEXT))
2200 {
2201 if (currentStyle.HasBulletText())
2202 {
2203 if (currentStyle.GetBulletText() != style.GetBulletText())
2204 {
2205 // Clash of style - mark as such
2206 multipleStyleAttributes |= wxTEXT_ATTR_BULLET_TEXT;
2207 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_BULLET_TEXT);
2208 }
2209 }
2210 else
2211 {
2212 currentStyle.SetBulletText(style.GetBulletText());
2213 currentStyle.SetBulletFont(style.GetBulletFont());
2214 }
2215 }
2216
2217 if (style.HasBulletName() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_BULLET_NAME))
2218 {
2219 if (currentStyle.HasBulletName())
2220 {
2221 if (currentStyle.GetBulletName() != style.GetBulletName())
2222 {
2223 // Clash of style - mark as such
2224 multipleStyleAttributes |= wxTEXT_ATTR_BULLET_NAME;
2225 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_BULLET_NAME);
2226 }
2227 }
2228 else
2229 {
2230 currentStyle.SetBulletName(style.GetBulletName());
2231 }
2232 }
2233
2234 if (style.HasURL() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_URL))
2235 {
2236 if (currentStyle.HasURL())
2237 {
2238 if (currentStyle.GetURL() != style.GetURL())
2239 {
2240 // Clash of style - mark as such
2241 multipleStyleAttributes |= wxTEXT_ATTR_URL;
2242 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_URL);
2243 }
2244 }
2245 else
2246 {
2247 currentStyle.SetURL(style.GetURL());
2248 }
2249 }
2250
2251 if (style.HasTextEffects() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_EFFECTS))
2252 {
2253 if (currentStyle.HasTextEffects())
2254 {
2255 // We need to find the bits in the new style that are different:
2256 // just look at those bits that are specified by the new style.
2257
2258 int currentRelevantTextEffects = currentStyle.GetTextEffects() & style.GetTextEffectFlags();
2259 int newRelevantTextEffects = style.GetTextEffects() & style.GetTextEffectFlags();
2260
2261 if (currentRelevantTextEffects != newRelevantTextEffects)
2262 {
2263 // Find the text effects that were different, using XOR
2264 int differentEffects = currentRelevantTextEffects ^ newRelevantTextEffects;
2265
2266 // Clash of style - mark as such
2267 multipleTextEffectAttributes |= differentEffects;
2268 currentStyle.SetTextEffectFlags(currentStyle.GetTextEffectFlags() & ~differentEffects);
2269 }
2270 }
2271 else
2272 {
2273 currentStyle.SetTextEffects(style.GetTextEffects());
2274 currentStyle.SetTextEffectFlags(style.GetTextEffectFlags());
2275 }
2276 }
2277
2278 if (style.HasOutlineLevel() && !wxHasStyle(multipleStyleAttributes, wxTEXT_ATTR_OUTLINE_LEVEL))
2279 {
2280 if (currentStyle.HasOutlineLevel())
2281 {
2282 if (currentStyle.GetOutlineLevel() != style.GetOutlineLevel())
2283 {
2284 // Clash of style - mark as such
2285 multipleStyleAttributes |= wxTEXT_ATTR_OUTLINE_LEVEL;
2286 currentStyle.SetFlags(currentStyle.GetFlags() & ~wxTEXT_ATTR_OUTLINE_LEVEL);
2287 }
2288 }
2289 else
2290 currentStyle.SetOutlineLevel(style.GetOutlineLevel());
2291 }
2292
2293 return true;
2294}
2295
2296/// Get the combined style for a range - if any attribute is different within the range,
2297/// that attribute is not present within the flags.
2298/// *** Note that this is not recursive, and so assumes that content inside a paragraph is not itself
2299/// nested.
2300bool wxRichTextParagraphLayoutBox::GetStyleForRange(const wxRichTextRange& range, wxTextAttr& style)
2301{
2302 style = wxTextAttr();
2303
2304 // The attributes that aren't valid because of multiple styles within the range
2305 long multipleStyleAttributes = 0;
2306 int multipleTextEffectAttributes = 0;
2307
2308 wxRichTextObjectList::compatibility_iterator node = GetChildren().GetFirst();
2309 while (node)
2310 {
2311 wxRichTextParagraph* para = (wxRichTextParagraph*) node->GetData();
2312 if (!(para->GetRange().GetStart() > range.GetEnd() || para->GetRange().GetEnd() < range.GetStart()))
2313 {
2314 if (para->GetChildren().GetCount() == 0)
2315 {
2316 wxTextAttr paraStyle = para->GetCombinedAttributes();
2317
2318 CollectStyle(style, paraStyle, multipleStyleAttributes, multipleTextEffectAttributes);
2319 }
2320 else
2321 {
2322 wxRichTextRange paraRange(para->GetRange());
2323 paraRange.LimitTo(range);
2324
2325 // First collect paragraph attributes only
2326 wxTextAttr paraStyle = para->GetCombinedAttributes();
2327 paraStyle.SetFlags(paraStyle.GetFlags() & wxTEXT_ATTR_PARAGRAPH);
2328 CollectStyle(style, paraStyle, multipleStyleAttributes, multipleTextEffectAttributes);
2329
2330 wxRichTextObjectList::compatibility_iterator childNode = para->GetChildren().GetFirst();
2331
2332 while (childNode)
2333 {
2334 wxRichTextObject* child = childNode->GetData();
2335 if (!(child->GetRange().GetStart() > range.GetEnd() || child->GetRange().GetEnd() < range.GetStart()))
2336 {
2337 wxTextAttr childStyle = para->GetCombinedAttributes(child->GetAttributes());
2338
2339 // Now collect character attributes only
2340 childStyle.SetFlags(childStyle.GetFlags() & wxTEXT_ATTR_CHARACTER);
2341
2342 CollectStyle(style, childStyle, multipleStyleAttributes, multipleTextEffectAttributes);
2343 }
2344
2345 childNode = childNode->GetNext();
2346 }
2347 }
2348 }
2349 node = node->GetNext();
2350 }
2351 return true;
2352}
2353
2354/// Set default style
2355bool wxRichTextParagraphLayoutBox::SetDefaultStyle(const wxTextAttr& style)
2356{
2357 m_defaultAttributes = style;
2358 return true;
2359}
2360
2361/// Test if this whole range has character attributes of the specified kind. If any
2362/// of the attributes are different within the range, the test fails. You
2363/// can use this to implement, for example, bold button updating. style must have
2364/// flags indicating which attributes are of interest.
2365bool wxRichTextParagraphLayoutBox::HasCharacterAttributes(const wxRichTextRange& range, const wxTextAttr& style) const
2366{
2367 int foundCount = 0;
2368 int matchingCount = 0;
2369
2370 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
2371 while (node)
2372 {
2373 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
2374 wxASSERT (para != NULL);
2375
2376 if (para)
2377 {
2378 // Stop searching if we're beyond the range of interest
2379 if (para->GetRange().GetStart() > range.GetEnd())
2380 return foundCount == matchingCount;
2381
2382 if (!para->GetRange().IsOutside(range))
2383 {
2384 wxRichTextObjectList::compatibility_iterator node2 = para->GetChildren().GetFirst();
2385
2386 while (node2)
2387 {
2388 wxRichTextObject* child = node2->GetData();
2389 if (!child->GetRange().IsOutside(range) && child->IsKindOf(CLASSINFO(wxRichTextPlainText)))
2390 {
2391 foundCount ++;
2392 wxTextAttr textAttr = para->GetCombinedAttributes(child->GetAttributes());
2393
2394 if (wxTextAttrEqPartial(textAttr, style, style.GetFlags()))
2395 matchingCount ++;
2396 }
2397
2398 node2 = node2->GetNext();
2399 }
2400 }
2401 }
2402
2403 node = node->GetNext();
2404 }
2405
2406 return foundCount == matchingCount;
2407}
2408
2409/// Test if this whole range has paragraph attributes of the specified kind. If any
2410/// of the attributes are different within the range, the test fails. You
2411/// can use this to implement, for example, centering button updating. style must have
2412/// flags indicating which attributes are of interest.
2413bool wxRichTextParagraphLayoutBox::HasParagraphAttributes(const wxRichTextRange& range, const wxTextAttr& style) const
2414{
2415 int foundCount = 0;
2416 int matchingCount = 0;
2417
2418 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
2419 while (node)
2420 {
2421 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
2422 wxASSERT (para != NULL);
2423
2424 if (para)
2425 {
2426 // Stop searching if we're beyond the range of interest
2427 if (para->GetRange().GetStart() > range.GetEnd())
2428 return foundCount == matchingCount;
2429
2430 if (!para->GetRange().IsOutside(range))
2431 {
2432 wxTextAttr textAttr = GetAttributes();
2433 // Apply the paragraph style
2434 wxRichTextApplyStyle(textAttr, para->GetAttributes());
2435
2436 foundCount ++;
2437 if (wxTextAttrEqPartial(textAttr, style, style.GetFlags()))
2438 matchingCount ++;
2439 }
2440 }
2441
2442 node = node->GetNext();
2443 }
2444 return foundCount == matchingCount;
2445}
2446
2447void wxRichTextParagraphLayoutBox::Clear()
2448{
2449 DeleteChildren();
2450}
2451
2452void wxRichTextParagraphLayoutBox::Reset()
2453{
2454 Clear();
2455
2456 wxRichTextBuffer* buffer = wxDynamicCast(this, wxRichTextBuffer);
2457 if (buffer && GetRichTextCtrl())
2458 {
2459 wxRichTextEvent event(wxEVT_COMMAND_RICHTEXT_BUFFER_RESET, GetRichTextCtrl()->GetId());
2460 event.SetEventObject(GetRichTextCtrl());
2461
2462 buffer->SendEvent(event, true);
2463 }
2464
2465 AddParagraph(wxEmptyString);
2466
2467 Invalidate(wxRICHTEXT_ALL);
2468}
2469
2470/// Invalidate the buffer. With no argument, invalidates whole buffer.
2471void wxRichTextParagraphLayoutBox::Invalidate(const wxRichTextRange& invalidRange)
2472{
2473 SetDirty(true);
2474
2475 if (invalidRange == wxRICHTEXT_ALL)
2476 {
2477 m_invalidRange = wxRICHTEXT_ALL;
2478 return;
2479 }
2480
2481 // Already invalidating everything
2482 if (m_invalidRange == wxRICHTEXT_ALL)
2483 return;
2484
2485 if ((invalidRange.GetStart() < m_invalidRange.GetStart()) || m_invalidRange.GetStart() == -1)
2486 m_invalidRange.SetStart(invalidRange.GetStart());
2487 if (invalidRange.GetEnd() > m_invalidRange.GetEnd())
2488 m_invalidRange.SetEnd(invalidRange.GetEnd());
2489}
2490
2491/// Get invalid range, rounding to entire paragraphs if argument is true.
2492wxRichTextRange wxRichTextParagraphLayoutBox::GetInvalidRange(bool wholeParagraphs) const
2493{
2494 if (m_invalidRange == wxRICHTEXT_ALL || m_invalidRange == wxRICHTEXT_NONE)
2495 return m_invalidRange;
2496
2497 wxRichTextRange range = m_invalidRange;
2498
2499 if (wholeParagraphs)
2500 {
2501 wxRichTextParagraph* para1 = GetParagraphAtPosition(range.GetStart());
2502 wxRichTextParagraph* para2 = GetParagraphAtPosition(range.GetEnd());
2503 if (para1)
2504 range.SetStart(para1->GetRange().GetStart());
2505 if (para2)
2506 range.SetEnd(para2->GetRange().GetEnd());
2507 }
2508 return range;
2509}
2510
2511/// Apply the style sheet to the buffer, for example if the styles have changed.
2512bool wxRichTextParagraphLayoutBox::ApplyStyleSheet(wxRichTextStyleSheet* styleSheet)
2513{
2514 wxASSERT(styleSheet != NULL);
2515 if (!styleSheet)
2516 return false;
2517
2518 int foundCount = 0;
2519
2520 wxRichTextAttr attr(GetBasicStyle());
2521 if (GetBasicStyle().HasParagraphStyleName())
2522 {
2523 wxRichTextParagraphStyleDefinition* paraDef = styleSheet->FindParagraphStyle(GetBasicStyle().GetParagraphStyleName());
2524 if (paraDef)
2525 {
2526 attr.Apply(paraDef->GetStyleMergedWithBase(styleSheet));
2527 SetBasicStyle(attr);
2528 foundCount ++;
2529 }
2530 }
2531
2532 if (GetBasicStyle().HasCharacterStyleName())
2533 {
2534 wxRichTextCharacterStyleDefinition* charDef = styleSheet->FindCharacterStyle(GetBasicStyle().GetCharacterStyleName());
2535 if (charDef)
2536 {
2537 attr.Apply(charDef->GetStyleMergedWithBase(styleSheet));
2538 SetBasicStyle(attr);
2539 foundCount ++;
2540 }
2541 }
2542
2543 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
2544 while (node)
2545 {
2546 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
2547 wxASSERT (para != NULL);
2548
2549 if (para)
2550 {
2551 // Combine paragraph and list styles. If there is a list style in the original attributes,
2552 // the current indentation overrides anything else and is used to find the item indentation.
2553 // Also, for applying paragraph styles, consider having 2 modes: (1) we merge with what we have,
2554 // thereby taking into account all user changes, (2) reset the style completely (except for indentation/list
2555 // exception as above).
2556 // Problem: when changing from one list style to another, there's a danger that the level info will get lost.
2557 // So when changing a list style interactively, could retrieve level based on current style, then
2558 // set appropriate indent and apply new style.
2559
2560 if (!para->GetAttributes().GetParagraphStyleName().IsEmpty() && !para->GetAttributes().GetListStyleName().IsEmpty())
2561 {
2562 int currentIndent = para->GetAttributes().GetLeftIndent();
2563
2564 wxRichTextParagraphStyleDefinition* paraDef = styleSheet->FindParagraphStyle(para->GetAttributes().GetParagraphStyleName());
2565 wxRichTextListStyleDefinition* listDef = styleSheet->FindListStyle(para->GetAttributes().GetListStyleName());
2566 if (paraDef && !listDef)
2567 {
2568 para->GetAttributes() = paraDef->GetStyleMergedWithBase(styleSheet);
2569 foundCount ++;
2570 }
2571 else if (listDef && !paraDef)
2572 {
2573 // Set overall style defined for the list style definition
2574 para->GetAttributes() = listDef->GetStyleMergedWithBase(styleSheet);
2575
2576 // Apply the style for this level
2577 wxRichTextApplyStyle(para->GetAttributes(), * listDef->GetLevelAttributes(listDef->FindLevelForIndent(currentIndent)));
2578 foundCount ++;
2579 }
2580 else if (listDef && paraDef)
2581 {
2582 // Combines overall list style, style for level, and paragraph style
2583 para->GetAttributes() = listDef->CombineWithParagraphStyle(currentIndent, paraDef->GetStyleMergedWithBase(styleSheet));
2584 foundCount ++;
2585 }
2586 }
2587 else if (para->GetAttributes().GetParagraphStyleName().IsEmpty() && !para->GetAttributes().GetListStyleName().IsEmpty())
2588 {
2589 int currentIndent = para->GetAttributes().GetLeftIndent();
2590
2591 wxRichTextListStyleDefinition* listDef = styleSheet->FindListStyle(para->GetAttributes().GetListStyleName());
2592
2593 // Overall list definition style
2594 para->GetAttributes() = listDef->GetStyleMergedWithBase(styleSheet);
2595
2596 // Style for this level
2597 wxRichTextApplyStyle(para->GetAttributes(), * listDef->GetLevelAttributes(listDef->FindLevelForIndent(currentIndent)));
2598
2599 foundCount ++;
2600 }
2601 else if (!para->GetAttributes().GetParagraphStyleName().IsEmpty() && para->GetAttributes().GetListStyleName().IsEmpty())
2602 {
2603 wxRichTextParagraphStyleDefinition* def = styleSheet->FindParagraphStyle(para->GetAttributes().GetParagraphStyleName());
2604 if (def)
2605 {
2606 para->GetAttributes() = def->GetStyleMergedWithBase(styleSheet);
2607 foundCount ++;
2608 }
2609 }
2610 }
2611
2612 node = node->GetNext();
2613 }
2614 return foundCount != 0;
2615}
2616
2617/// Set list style
2618bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags, int startFrom, int specifiedLevel)
2619{
2620 wxRichTextStyleSheet* styleSheet = GetStyleSheet();
2621
2622 bool withUndo = ((flags & wxRICHTEXT_SETSTYLE_WITH_UNDO) != 0);
2623 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2624 bool specifyLevel = ((flags & wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL) != 0);
2625 bool renumber = ((flags & wxRICHTEXT_SETSTYLE_RENUMBER) != 0);
2626
2627 // Current number, if numbering
2628 int n = startFrom;
2629
2630 wxASSERT (!specifyLevel || (specifyLevel && (specifiedLevel >= 0)));
2631
2632 // If we are associated with a control, make undoable; otherwise, apply immediately
2633 // to the data.
2634
2635 bool haveControl = (GetRichTextCtrl() != NULL);
2636
2637 wxRichTextAction* action = NULL;
2638
2639 if (haveControl && withUndo)
2640 {
2641 action = new wxRichTextAction(NULL, _("Change List Style"), wxRICHTEXT_CHANGE_STYLE, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2642 action->SetRange(range);
2643 action->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2644 }
2645
2646 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
2647 while (node)
2648 {
2649 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
2650 wxASSERT (para != NULL);
2651
2652 if (para && para->GetChildCount() > 0)
2653 {
2654 // Stop searching if we're beyond the range of interest
2655 if (para->GetRange().GetStart() > range.GetEnd())
2656 break;
2657
2658 if (!para->GetRange().IsOutside(range))
2659 {
2660 // We'll be using a copy of the paragraph to make style changes,
2661 // not updating the buffer directly.
2662 wxRichTextParagraph* newPara wxDUMMY_INITIALIZE(NULL);
2663
2664 if (haveControl && withUndo)
2665 {
2666 newPara = new wxRichTextParagraph(*para);
2667 action->GetNewParagraphs().AppendChild(newPara);
2668
2669 // Also store the old ones for Undo
2670 action->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para));
2671 }
2672 else
2673 newPara = para;
2674
2675 if (def)
2676 {
2677 int thisIndent = newPara->GetAttributes().GetLeftIndent();
2678 int thisLevel = specifyLevel ? specifiedLevel : def->FindLevelForIndent(thisIndent);
2679
2680 // How is numbering going to work?
2681 // If we are renumbering, or numbering for the first time, we need to keep
2682 // track of the number for each level. But we might be simply applying a different
2683 // list style.
2684 // In Word, applying a style to several paragraphs, even if at different levels,
2685 // reverts the level back to the same one. So we could do the same here.
2686 // Renumbering will need to be done when we promote/demote a paragraph.
2687
2688 // Apply the overall list style, and item style for this level
2689 wxTextAttr listStyle(def->GetCombinedStyleForLevel(thisLevel, styleSheet));
2690 wxRichTextApplyStyle(newPara->GetAttributes(), listStyle);
2691
2692 // Now we need to do numbering
2693 if (renumber)
2694 {
2695 newPara->GetAttributes().SetBulletNumber(n);
2696 }
2697
2698 n ++;
2699 }
2700 else if (!newPara->GetAttributes().GetListStyleName().IsEmpty())
2701 {
2702 // if def is NULL, remove list style, applying any associated paragraph style
2703 // to restore the attributes
2704
2705 newPara->GetAttributes().SetListStyleName(wxEmptyString);
2706 newPara->GetAttributes().SetLeftIndent(0, 0);
2707 newPara->GetAttributes().SetBulletText(wxEmptyString);
2708
2709 // Eliminate the main list-related attributes
2710 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);
2711
2712 if (styleSheet && !newPara->GetAttributes().GetParagraphStyleName().IsEmpty())
2713 {
2714 wxRichTextParagraphStyleDefinition* def = styleSheet->FindParagraphStyle(newPara->GetAttributes().GetParagraphStyleName());
2715 if (def)
2716 {
2717 newPara->GetAttributes() = def->GetStyleMergedWithBase(styleSheet);
2718 }
2719 }
2720 }
2721 }
2722 }
2723
2724 node = node->GetNext();
2725 }
2726
2727 // Do action, or delay it until end of batch.
2728 if (haveControl && withUndo)
2729 GetRichTextCtrl()->GetBuffer().SubmitAction(action);
2730
2731 return true;
2732}
2733
2734bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange& range, const wxString& defName, int flags, int startFrom, int specifiedLevel)
2735{
2736 if (GetStyleSheet())
2737 {
2738 wxRichTextListStyleDefinition* def = GetStyleSheet()->FindListStyle(defName);
2739 if (def)
2740 return SetListStyle(range, def, flags, startFrom, specifiedLevel);
2741 }
2742 return false;
2743}
2744
2745/// Clear list for given range
2746bool wxRichTextParagraphLayoutBox::ClearListStyle(const wxRichTextRange& range, int flags)
2747{
2748 return SetListStyle(range, NULL, flags);
2749}
2750
2751/// Number/renumber any list elements in the given range
2752bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags, int startFrom, int specifiedLevel)
2753{
2754 return DoNumberList(range, range, 0, def, flags, startFrom, specifiedLevel);
2755}
2756
2757/// Number/renumber any list elements in the given range. Also do promotion or demotion of items, if specified
2758bool wxRichTextParagraphLayoutBox::DoNumberList(const wxRichTextRange& range, const wxRichTextRange& promotionRange, int promoteBy,
2759 wxRichTextListStyleDefinition* def, int flags, int startFrom, int specifiedLevel)
2760{
2761 wxRichTextStyleSheet* styleSheet = GetStyleSheet();
2762
2763 bool withUndo = ((flags & wxRICHTEXT_SETSTYLE_WITH_UNDO) != 0);
2764 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2765#ifdef __WXDEBUG__
2766 bool specifyLevel = ((flags & wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL) != 0);
2767#endif
2768
2769 bool renumber = ((flags & wxRICHTEXT_SETSTYLE_RENUMBER) != 0);
2770
2771 // Max number of levels
2772 const int maxLevels = 10;
2773
2774 // The level we're looking at now
2775 int currentLevel = -1;
2776
2777 // The item number for each level
2778 int levels[maxLevels];
2779 int i;
2780
2781 // Reset all numbering
2782 for (i = 0; i < maxLevels; i++)
2783 {
2784 if (startFrom != -1)
2785 levels[i] = startFrom-1;
2786 else if (renumber) // start again
2787 levels[i] = 0;
2788 else
2789 levels[i] = -1; // start from the number we found, if any
2790 }
2791
2792 wxASSERT(!specifyLevel || (specifyLevel && (specifiedLevel >= 0)));
2793
2794 // If we are associated with a control, make undoable; otherwise, apply immediately
2795 // to the data.
2796
2797 bool haveControl = (GetRichTextCtrl() != NULL);
2798
2799 wxRichTextAction* action = NULL;
2800
2801 if (haveControl && withUndo)
2802 {
2803 action = new wxRichTextAction(NULL, _("Renumber List"), wxRICHTEXT_CHANGE_STYLE, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2804 action->SetRange(range);
2805 action->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2806 }
2807
2808 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
2809 while (node)
2810 {
2811 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
2812 wxASSERT (para != NULL);
2813
2814 if (para && para->GetChildCount() > 0)
2815 {
2816 // Stop searching if we're beyond the range of interest
2817 if (para->GetRange().GetStart() > range.GetEnd())
2818 break;
2819
2820 if (!para->GetRange().IsOutside(range))
2821 {
2822 // We'll be using a copy of the paragraph to make style changes,
2823 // not updating the buffer directly.
2824 wxRichTextParagraph* newPara wxDUMMY_INITIALIZE(NULL);
2825
2826 if (haveControl && withUndo)
2827 {
2828 newPara = new wxRichTextParagraph(*para);
2829 action->GetNewParagraphs().AppendChild(newPara);
2830
2831 // Also store the old ones for Undo
2832 action->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para));
2833 }
2834 else
2835 newPara = para;
2836
2837 wxRichTextListStyleDefinition* defToUse = def;
2838 if (!defToUse)
2839 {
2840 if (styleSheet && !newPara->GetAttributes().GetListStyleName().IsEmpty())
2841 defToUse = styleSheet->FindListStyle(newPara->GetAttributes().GetListStyleName());
2842 }
2843
2844 if (defToUse)
2845 {
2846 int thisIndent = newPara->GetAttributes().GetLeftIndent();
2847 int thisLevel = defToUse->FindLevelForIndent(thisIndent);
2848
2849 // If we've specified a level to apply to all, change the level.
2850 if (specifiedLevel != -1)
2851 thisLevel = specifiedLevel;
2852
2853 // Do promotion if specified
2854 if ((promoteBy != 0) && !para->GetRange().IsOutside(promotionRange))
2855 {
2856 thisLevel = thisLevel - promoteBy;
2857 if (thisLevel < 0)
2858 thisLevel = 0;
2859 if (thisLevel > 9)
2860 thisLevel = 9;
2861 }
2862
2863 // Apply the overall list style, and item style for this level
2864 wxTextAttr listStyle(defToUse->GetCombinedStyleForLevel(thisLevel, styleSheet));
2865 wxRichTextApplyStyle(newPara->GetAttributes(), listStyle);
2866
2867 // OK, we've (re)applied the style, now let's get the numbering right.
2868
2869 if (currentLevel == -1)
2870 currentLevel = thisLevel;
2871
2872 // Same level as before, do nothing except increment level's number afterwards
2873 if (currentLevel == thisLevel)
2874 {
2875 }
2876 // A deeper level: start renumbering all levels after current level
2877 else if (thisLevel > currentLevel)
2878 {
2879 for (i = currentLevel+1; i <= thisLevel; i++)
2880 {
2881 levels[i] = 0;
2882 }
2883 currentLevel = thisLevel;
2884 }
2885 else if (thisLevel < currentLevel)
2886 {
2887 currentLevel = thisLevel;
2888 }
2889
2890 // Use the current numbering if -1 and we have a bullet number already
2891 if (levels[currentLevel] == -1)
2892 {
2893 if (newPara->GetAttributes().HasBulletNumber())
2894 levels[currentLevel] = newPara->GetAttributes().GetBulletNumber();
2895 else
2896 levels[currentLevel] = 1;
2897 }
2898 else
2899 {
2900 levels[currentLevel] ++;
2901 }
2902
2903 newPara->GetAttributes().SetBulletNumber(levels[currentLevel]);
2904
2905 // Create the bullet text if an outline list
2906 if (listStyle.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE)
2907 {
2908 wxString text;
2909 for (i = 0; i <= currentLevel; i++)
2910 {
2911 if (!text.IsEmpty())
2912 text += wxT(".");
2913 text += wxString::Format(wxT("%d"), levels[i]);
2914 }
2915 newPara->GetAttributes().SetBulletText(text);
2916 }
2917 }
2918 }
2919 }
2920
2921 node = node->GetNext();
2922 }
2923
2924 // Do action, or delay it until end of batch.
2925 if (haveControl && withUndo)
2926 GetRichTextCtrl()->GetBuffer().SubmitAction(action);
2927
2928 return true;
2929}
2930
2931bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange& range, const wxString& defName, int flags, int startFrom, int specifiedLevel)
2932{
2933 if (GetStyleSheet())
2934 {
2935 wxRichTextListStyleDefinition* def = NULL;
2936 if (!defName.IsEmpty())
2937 def = GetStyleSheet()->FindListStyle(defName);
2938 return NumberList(range, def, flags, startFrom, specifiedLevel);
2939 }
2940 return false;
2941}
2942
2943/// Promote the list items within the given range. promoteBy can be a positive or negative number, e.g. 1 or -1
2944bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy, const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags, int specifiedLevel)
2945{
2946 // TODO
2947 // One strategy is to first work out the range within which renumbering must occur. Then could pass these two ranges
2948 // to NumberList with a flag indicating promotion is required within one of the ranges.
2949 // Find first and last paragraphs in range. Then for first, calculate new indentation and look back until we find
2950 // a paragraph that either has no list style, or has one that is different or whose indentation is less.
2951 // We start renumbering from the para after that different para we found. We specify that the numbering of that
2952 // list position will start from 1.
2953 // Similarly, we look after the last para in the promote range for an indentation that is less (or no list style).
2954 // We can end the renumbering at this point.
2955
2956 // For now, only renumber within the promotion range.
2957
2958 return DoNumberList(range, range, promoteBy, def, flags, 1, specifiedLevel);
2959}
2960
2961bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy, const wxRichTextRange& range, const wxString& defName, int flags, int specifiedLevel)
2962{
2963 if (GetStyleSheet())
2964 {
2965 wxRichTextListStyleDefinition* def = NULL;
2966 if (!defName.IsEmpty())
2967 def = GetStyleSheet()->FindListStyle(defName);
2968 return PromoteList(promoteBy, range, def, flags, specifiedLevel);
2969 }
2970 return false;
2971}
2972
2973/// Fills in the attributes for numbering a paragraph after previousParagraph. It also finds the
2974/// position of the paragraph that it had to start looking from.
2975bool wxRichTextParagraphLayoutBox::FindNextParagraphNumber(wxRichTextParagraph* previousParagraph, wxTextAttr& attr) const
2976{
2977 if (!previousParagraph->GetAttributes().HasFlag(wxTEXT_ATTR_BULLET_STYLE) || previousParagraph->GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE)
2978 return false;
2979
2980 wxRichTextStyleSheet* styleSheet = GetStyleSheet();
2981 if (styleSheet && !previousParagraph->GetAttributes().GetListStyleName().IsEmpty())
2982 {
2983 wxRichTextListStyleDefinition* def = styleSheet->FindListStyle(previousParagraph->GetAttributes().GetListStyleName());
2984 if (def)
2985 {
2986 // int thisIndent = previousParagraph->GetAttributes().GetLeftIndent();
2987 // int thisLevel = def->FindLevelForIndent(thisIndent);
2988
2989 bool isOutline = (previousParagraph->GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE) != 0;
2990
2991 attr.SetFlags(previousParagraph->GetAttributes().GetFlags() & (wxTEXT_ATTR_BULLET_STYLE|wxTEXT_ATTR_BULLET_NUMBER|wxTEXT_ATTR_BULLET_TEXT|wxTEXT_ATTR_BULLET_NAME));
2992 if (previousParagraph->GetAttributes().HasBulletName())
2993 attr.SetBulletName(previousParagraph->GetAttributes().GetBulletName());
2994 attr.SetBulletStyle(previousParagraph->GetAttributes().GetBulletStyle());
2995 attr.SetListStyleName(previousParagraph->GetAttributes().GetListStyleName());
2996
2997 int nextNumber = previousParagraph->GetAttributes().GetBulletNumber() + 1;
2998 attr.SetBulletNumber(nextNumber);
2999
3000 if (isOutline)
3001 {
3002 wxString text = previousParagraph->GetAttributes().GetBulletText();
3003 if (!text.IsEmpty())
3004 {
3005 int pos = text.Find(wxT('.'), true);
3006 if (pos != wxNOT_FOUND)
3007 {
3008 text = text.Mid(0, text.Length() - pos - 1);
3009 }
3010 else
3011 text = wxEmptyString;
3012 if (!text.IsEmpty())
3013 text += wxT(".");
3014 text += wxString::Format(wxT("%d"), nextNumber);
3015 attr.SetBulletText(text);
3016 }
3017 }
3018
3019 return true;
3020 }
3021 else
3022 return false;
3023 }
3024 else
3025 return false;
3026}
3027
3028/*!
3029 * wxRichTextParagraph
3030 * This object represents a single paragraph (or in a straight text editor, a line).
3031 */
3032
3033IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraph, wxRichTextBox)
3034
3035wxArrayInt wxRichTextParagraph::sm_defaultTabs;
3036
3037wxRichTextParagraph::wxRichTextParagraph(wxRichTextObject* parent, wxTextAttr* style):
3038 wxRichTextBox(parent)
3039{
3040 if (style)
3041 SetAttributes(*style);
3042}
3043
3044wxRichTextParagraph::wxRichTextParagraph(const wxString& text, wxRichTextObject* parent, wxTextAttr* paraStyle, wxTextAttr* charStyle):
3045 wxRichTextBox(parent)
3046{
3047 if (paraStyle)
3048 SetAttributes(*paraStyle);
3049
3050 AppendChild(new wxRichTextPlainText(text, this, charStyle));
3051}
3052
3053wxRichTextParagraph::~wxRichTextParagraph()
3054{
3055 ClearLines();
3056}
3057
3058/// Draw the item
3059bool wxRichTextParagraph::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextRange& selectionRange, const wxRect& WXUNUSED(rect), int WXUNUSED(descent), int style)
3060{
3061 wxTextAttr attr = GetCombinedAttributes();
3062
3063 // Draw the bullet, if any
3064 if (attr.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE)
3065 {
3066 if (attr.GetLeftSubIndent() != 0)
3067 {
3068 int spaceBeforePara = ConvertTenthsMMToPixels(dc, attr.GetParagraphSpacingBefore());
3069 int leftIndent = ConvertTenthsMMToPixels(dc, attr.GetLeftIndent());
3070
3071 wxTextAttr bulletAttr(GetCombinedAttributes());
3072
3073 // Combine with the font of the first piece of content, if one is specified
3074 if (GetChildren().GetCount() > 0)
3075 {
3076 wxRichTextObject* firstObj = (wxRichTextObject*) GetChildren().GetFirst()->GetData();
3077 if (firstObj->GetAttributes().HasFont())
3078 {
3079 wxRichTextApplyStyle(bulletAttr, firstObj->GetAttributes());
3080 }
3081 }
3082
3083 // Get line height from first line, if any
3084 wxRichTextLine* line = m_cachedLines.GetFirst() ? (wxRichTextLine* ) m_cachedLines.GetFirst()->GetData() : (wxRichTextLine*) NULL;
3085
3086 wxPoint linePos;
3087 int lineHeight wxDUMMY_INITIALIZE(0);
3088 if (line)
3089 {
3090 lineHeight = line->GetSize().y;
3091 linePos = line->GetPosition() + GetPosition();
3092 }
3093 else
3094 {
3095 wxFont font;
3096 if (bulletAttr.HasFont() && GetBuffer())
3097 font = GetBuffer()->GetFontTable().FindFont(bulletAttr);
3098 else
3099 font = (*wxNORMAL_FONT);
3100
3101 wxCheckSetFont(dc, font);
3102
3103 lineHeight = dc.GetCharHeight();
3104 linePos = GetPosition();
3105 linePos.y += spaceBeforePara;
3106 }
3107
3108 wxRect bulletRect(GetPosition().x + leftIndent, linePos.y, linePos.x - (GetPosition().x + leftIndent), lineHeight);
3109
3110 if (attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP)
3111 {
3112 if (wxRichTextBuffer::GetRenderer())
3113 wxRichTextBuffer::GetRenderer()->DrawBitmapBullet(this, dc, bulletAttr, bulletRect);
3114 }
3115 else if (attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_STANDARD)
3116 {
3117 if (wxRichTextBuffer::GetRenderer())
3118 wxRichTextBuffer::GetRenderer()->DrawStandardBullet(this, dc, bulletAttr, bulletRect);
3119 }
3120 else
3121 {
3122 wxString bulletText = GetBulletText();
3123
3124 if (!bulletText.empty() && wxRichTextBuffer::GetRenderer())
3125 wxRichTextBuffer::GetRenderer()->DrawTextBullet(this, dc, bulletAttr, bulletRect, bulletText);
3126 }
3127 }
3128 }
3129
3130 // Draw the range for each line, one object at a time.
3131
3132 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetFirst();
3133 while (node)
3134 {
3135 wxRichTextLine* line = node->GetData();
3136 wxRichTextRange lineRange = line->GetAbsoluteRange();
3137
3138 int maxDescent = line->GetDescent();
3139
3140 // Lines are specified relative to the paragraph
3141
3142 wxPoint linePosition = line->GetPosition() + GetPosition();
3143 wxPoint objectPosition = linePosition;
3144
3145 // Loop through objects until we get to the one within range
3146 wxRichTextObjectList::compatibility_iterator node2 = m_children.GetFirst();
3147 while (node2)
3148 {
3149 wxRichTextObject* child = node2->GetData();
3150
3151 if (!child->GetRange().IsOutside(lineRange) && !lineRange.IsOutside(range))
3152 {
3153 // Draw this part of the line at the correct position
3154 wxRichTextRange objectRange(child->GetRange());
3155 objectRange.LimitTo(lineRange);
3156
3157 wxSize objectSize;
3158 int descent = 0;
3159 child->GetRangeSize(objectRange, objectSize, descent, dc, wxRICHTEXT_UNFORMATTED, objectPosition);
3160
3161 // Use the child object's width, but the whole line's height
3162 wxRect childRect(objectPosition, wxSize(objectSize.x, line->GetSize().y));
3163 child->Draw(dc, objectRange, selectionRange, childRect, maxDescent, style);
3164
3165 objectPosition.x += objectSize.x;
3166 }
3167 else if (child->GetRange().GetStart() > lineRange.GetEnd())
3168 // Can break out of inner loop now since we've passed this line's range
3169 break;
3170
3171 node2 = node2->GetNext();
3172 }
3173
3174 node = node->GetNext();
3175 }
3176
3177 return true;
3178}
3179
3180/// Lay the item out
3181bool wxRichTextParagraph::Layout(wxDC& dc, const wxRect& rect, int style)
3182{
3183 wxTextAttr attr = GetCombinedAttributes();
3184
3185 // ClearLines();
3186
3187 // Increase the size of the paragraph due to spacing
3188 int spaceBeforePara = ConvertTenthsMMToPixels(dc, attr.GetParagraphSpacingBefore());
3189 int spaceAfterPara = ConvertTenthsMMToPixels(dc, attr.GetParagraphSpacingAfter());
3190 int leftIndent = ConvertTenthsMMToPixels(dc, attr.GetLeftIndent());
3191 int leftSubIndent = ConvertTenthsMMToPixels(dc, attr.GetLeftSubIndent());
3192 int rightIndent = ConvertTenthsMMToPixels(dc, attr.GetRightIndent());
3193
3194 int lineSpacing = 0;
3195
3196 // Let's assume line spacing of 10 is normal, 15 is 1.5, 20 is 2, etc.
3197 if (attr.GetLineSpacing() != 10 && GetBuffer())
3198 {
3199 wxFont font(GetBuffer()->GetFontTable().FindFont(attr));
3200 wxCheckSetFont(dc, font);
3201 lineSpacing = (ConvertTenthsMMToPixels(dc, dc.GetCharHeight()) * attr.GetLineSpacing())/10;
3202 }
3203
3204 // Available space for text on each line differs.
3205 int availableTextSpaceFirstLine = rect.GetWidth() - leftIndent - rightIndent;
3206
3207 // Bullets start the text at the same position as subsequent lines
3208 if (attr.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE)
3209 availableTextSpaceFirstLine -= leftSubIndent;
3210
3211 int availableTextSpaceSubsequentLines = rect.GetWidth() - leftIndent - rightIndent - leftSubIndent;
3212
3213 // Start position for each line relative to the paragraph
3214 int startPositionFirstLine = leftIndent;
3215 int startPositionSubsequentLines = leftIndent + leftSubIndent;
3216
3217 // If we have a bullet in this paragraph, the start position for the first line's text
3218 // is actually leftIndent + leftSubIndent.
3219 if (attr.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE)
3220 startPositionFirstLine = startPositionSubsequentLines;
3221
3222 long lastEndPos = GetRange().GetStart()-1;
3223 long lastCompletedEndPos = lastEndPos;
3224
3225 int currentWidth = 0;
3226 SetPosition(rect.GetPosition());
3227
3228 wxPoint currentPosition(0, spaceBeforePara); // We will calculate lines relative to paragraph
3229 int lineHeight = 0;
3230 int maxWidth = 0;
3231 int maxDescent = 0;
3232
3233 int lineCount = 0;
3234
3235 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
3236 while (node)
3237 {
3238 wxRichTextObject* child = node->GetData();
3239
3240 child->SetCachedSize(wxDefaultSize);
3241 child->Layout(dc, rect, style);
3242
3243 node = node->GetNext();
3244 }
3245
3246 // Split up lines
3247
3248 // We may need to go back to a previous child, in which case create the new line,
3249 // find the child corresponding to the start position of the string, and
3250 // continue.
3251
3252 node = m_children.GetFirst();
3253 while (node)
3254 {
3255 wxRichTextObject* child = node->GetData();
3256
3257 // If this is e.g. a composite text box, it will need to be laid out itself.
3258 // But if just a text fragment or image, for example, this will
3259 // do nothing. NB: won't we need to set the position after layout?
3260 // since for example if position is dependent on vertical line size, we
3261 // can't tell the position until the size is determined. So possibly introduce
3262 // another layout phase.
3263
3264 // Available width depends on whether we're on the first or subsequent lines
3265 int availableSpaceForText = (lineCount == 0 ? availableTextSpaceFirstLine : availableTextSpaceSubsequentLines);
3266
3267 currentPosition.x = (lineCount == 0 ? startPositionFirstLine : startPositionSubsequentLines);
3268
3269 // We may only be looking at part of a child, if we searched back for wrapping
3270 // and found a suitable point some way into the child. So get the size for the fragment
3271 // if necessary.
3272
3273 long nextBreakPos = GetFirstLineBreakPosition(lastEndPos+1);
3274 long lastPosToUse = child->GetRange().GetEnd();
3275 bool lineBreakInThisObject = (nextBreakPos > -1 && nextBreakPos <= child->GetRange().GetEnd());
3276
3277 if (lineBreakInThisObject)
3278 lastPosToUse = nextBreakPos;
3279
3280 wxSize childSize;
3281 int childDescent = 0;
3282
3283 if ((nextBreakPos == -1) && (lastEndPos == child->GetRange().GetStart() - 1)) // i.e. we want to get the whole thing
3284 {
3285 childSize = child->GetCachedSize();
3286 childDescent = child->GetDescent();
3287 }
3288 else
3289 GetRangeSize(wxRichTextRange(lastEndPos+1, lastPosToUse), childSize, childDescent, dc, wxRICHTEXT_UNFORMATTED, rect.GetPosition());
3290
3291 // Cases:
3292 // 1) There was a line break BEFORE the natural break
3293 // 2) There was a line break AFTER the natural break
3294 // 3) The child still fits (carry on)
3295
3296 if ((lineBreakInThisObject && (childSize.x + currentWidth <= availableSpaceForText)) ||
3297 (childSize.x + currentWidth > availableSpaceForText))
3298 {
3299 long wrapPosition = 0;
3300
3301 // Find a place to wrap. This may walk back to previous children,
3302 // for example if a word spans several objects.
3303 if (!FindWrapPosition(wxRichTextRange(lastCompletedEndPos+1, child->GetRange().GetEnd()), dc, availableSpaceForText, wrapPosition))
3304 {
3305 // If the function failed, just cut it off at the end of this child.
3306 wrapPosition = child->GetRange().GetEnd();
3307 }
3308
3309 // FindWrapPosition can still return a value that will put us in an endless wrapping loop
3310 if (wrapPosition <= lastCompletedEndPos)
3311 wrapPosition = wxMax(lastCompletedEndPos+1,child->GetRange().GetEnd());
3312
3313 // wxLogDebug(wxT("Split at %ld"), wrapPosition);
3314
3315 // Let's find the actual size of the current line now
3316 wxSize actualSize;
3317 wxRichTextRange actualRange(lastCompletedEndPos+1, wrapPosition);
3318 GetRangeSize(actualRange, actualSize, childDescent, dc, wxRICHTEXT_UNFORMATTED);
3319 currentWidth = actualSize.x;
3320 lineHeight = wxMax(lineHeight, actualSize.y);
3321 maxDescent = wxMax(childDescent, maxDescent);
3322
3323 // Add a new line
3324 wxRichTextLine* line = AllocateLine(lineCount);
3325
3326 // Set relative range so we won't have to change line ranges when paragraphs are moved
3327 line->SetRange(wxRichTextRange(actualRange.GetStart() - GetRange().GetStart(), actualRange.GetEnd() - GetRange().GetStart()));
3328 line->SetPosition(currentPosition);
3329 line->SetSize(wxSize(currentWidth, lineHeight));
3330 line->SetDescent(maxDescent);
3331
3332 // Now move down a line. TODO: add margins, spacing
3333 currentPosition.y += lineHeight;
3334 currentPosition.y += lineSpacing;
3335 currentWidth = 0;
3336 maxDescent = 0;
3337 maxWidth = wxMax(maxWidth, currentWidth);
3338
3339 lineCount ++;
3340
3341 // TODO: account for zero-length objects, such as fields
3342 wxASSERT(wrapPosition > lastCompletedEndPos);
3343
3344 lastEndPos = wrapPosition;
3345 lastCompletedEndPos = lastEndPos;
3346
3347 lineHeight = 0;
3348
3349 // May need to set the node back to a previous one, due to searching back in wrapping
3350 wxRichTextObject* childAfterWrapPosition = FindObjectAtPosition(wrapPosition+1);
3351 if (childAfterWrapPosition)
3352 node = m_children.Find(childAfterWrapPosition);
3353 else
3354 node = node->GetNext();
3355 }
3356 else
3357 {
3358 // We still fit, so don't add a line, and keep going
3359 currentWidth += childSize.x;
3360 lineHeight = wxMax(lineHeight, childSize.y);
3361 maxDescent = wxMax(childDescent, maxDescent);
3362
3363 maxWidth = wxMax(maxWidth, currentWidth);
3364 lastEndPos = child->GetRange().GetEnd();
3365
3366 node = node->GetNext();
3367 }
3368 }
3369
3370 // Add the last line - it's the current pos -> last para pos
3371 // Substract -1 because the last position is always the end-paragraph position.
3372 if (lastCompletedEndPos <= GetRange().GetEnd()-1)
3373 {
3374 currentPosition.x = (lineCount == 0 ? startPositionFirstLine : startPositionSubsequentLines);
3375
3376 wxRichTextLine* line = AllocateLine(lineCount);
3377
3378 wxRichTextRange actualRange(lastCompletedEndPos+1, GetRange().GetEnd()-1);
3379
3380 // Set relative range so we won't have to change line ranges when paragraphs are moved
3381 line->SetRange(wxRichTextRange(actualRange.GetStart() - GetRange().GetStart(), actualRange.GetEnd() - GetRange().GetStart()));
3382
3383 line->SetPosition(currentPosition);
3384
3385 if (lineHeight == 0 && GetBuffer())
3386 {
3387 wxFont font(GetBuffer()->GetFontTable().FindFont(attr));
3388 wxCheckSetFont(dc, font);
3389 lineHeight = dc.GetCharHeight();
3390 }
3391 if (maxDescent == 0)
3392 {
3393 int w, h;
3394 dc.GetTextExtent(wxT("X"), & w, &h, & maxDescent);
3395 }
3396
3397 line->SetSize(wxSize(currentWidth, lineHeight));
3398 line->SetDescent(maxDescent);
3399 currentPosition.y += lineHeight;
3400 currentPosition.y += lineSpacing;
3401 lineCount ++;
3402 }
3403
3404 // Remove remaining unused line objects, if any
3405 ClearUnusedLines(lineCount);
3406
3407 // Apply styles to wrapped lines
3408 ApplyParagraphStyle(attr, rect);
3409
3410 SetCachedSize(wxSize(maxWidth, currentPosition.y + spaceBeforePara + spaceAfterPara));
3411
3412 m_dirty = false;
3413
3414 return true;
3415}
3416
3417/// Apply paragraph styles, such as centering, to wrapped lines
3418void wxRichTextParagraph::ApplyParagraphStyle(const wxTextAttr& attr, const wxRect& rect)
3419{
3420 if (!attr.HasAlignment())
3421 return;
3422
3423 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetFirst();
3424 while (node)
3425 {
3426 wxRichTextLine* line = node->GetData();
3427
3428 wxPoint pos = line->GetPosition();
3429 wxSize size = line->GetSize();
3430
3431 // centering, right-justification
3432 if (attr.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_CENTRE)
3433 {
3434 pos.x = (rect.GetWidth() - size.x)/2 + pos.x;
3435 line->SetPosition(pos);
3436 }
3437 else if (attr.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_RIGHT)
3438 {
3439 pos.x = pos.x + rect.GetWidth() - size.x;
3440 line->SetPosition(pos);
3441 }
3442
3443 node = node->GetNext();
3444 }
3445}
3446
3447/// Insert text at the given position
3448bool wxRichTextParagraph::InsertText(long pos, const wxString& text)
3449{
3450 wxRichTextObject* childToUse = NULL;
3451 wxRichTextObjectList::compatibility_iterator nodeToUse = wxRichTextObjectList::compatibility_iterator();
3452
3453 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
3454 while (node)
3455 {
3456 wxRichTextObject* child = node->GetData();
3457 if (child->GetRange().Contains(pos) && child->GetRange().GetLength() > 0)
3458 {
3459 childToUse = child;
3460 nodeToUse = node;
3461 break;
3462 }
3463
3464 node = node->GetNext();
3465 }
3466
3467 if (childToUse)
3468 {
3469 wxRichTextPlainText* textObject = wxDynamicCast(childToUse, wxRichTextPlainText);
3470 if (textObject)
3471 {
3472 int posInString = pos - textObject->GetRange().GetStart();
3473
3474 wxString newText = textObject->GetText().Mid(0, posInString) +
3475 text + textObject->GetText().Mid(posInString);
3476 textObject->SetText(newText);
3477
3478 int textLength = text.length();
3479
3480 textObject->SetRange(wxRichTextRange(textObject->GetRange().GetStart(),
3481 textObject->GetRange().GetEnd() + textLength));
3482
3483 // Increment the end range of subsequent fragments in this paragraph.
3484 // We'll set the paragraph range itself at a higher level.
3485
3486 wxRichTextObjectList::compatibility_iterator node = nodeToUse->GetNext();
3487 while (node)
3488 {
3489 wxRichTextObject* child = node->GetData();
3490 child->SetRange(wxRichTextRange(textObject->GetRange().GetStart() + textLength,
3491 textObject->GetRange().GetEnd() + textLength));
3492
3493 node = node->GetNext();
3494 }
3495
3496 return true;
3497 }
3498 else
3499 {
3500 // TODO: if not a text object, insert at closest position, e.g. in front of it
3501 }
3502 }
3503 else
3504 {
3505 // Add at end.
3506 // Don't pass parent initially to suppress auto-setting of parent range.
3507 // We'll do that at a higher level.
3508 wxRichTextPlainText* textObject = new wxRichTextPlainText(text, this);
3509
3510 AppendChild(textObject);
3511 return true;
3512 }
3513
3514 return false;
3515}
3516
3517void wxRichTextParagraph::Copy(const wxRichTextParagraph& obj)
3518{
3519 wxRichTextBox::Copy(obj);
3520}
3521
3522/// Clear the cached lines
3523void wxRichTextParagraph::ClearLines()
3524{
3525 WX_CLEAR_LIST(wxRichTextLineList, m_cachedLines);
3526}
3527
3528/// Get/set the object size for the given range. Returns false if the range
3529/// is invalid for this object.
3530bool wxRichTextParagraph::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, int flags, wxPoint position) const
3531{
3532 if (!range.IsWithin(GetRange()))
3533 return false;
3534
3535 if (flags & wxRICHTEXT_UNFORMATTED)
3536 {
3537 // Just use unformatted data, assume no line breaks
3538 // TODO: take into account line breaks
3539
3540 wxSize sz;
3541
3542 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
3543 while (node)
3544 {
3545 wxRichTextObject* child = node->GetData();
3546 if (!child->GetRange().IsOutside(range))
3547 {
3548 wxSize childSize;
3549
3550 wxRichTextRange rangeToUse = range;
3551 rangeToUse.LimitTo(child->GetRange());
3552 int childDescent = 0;
3553
3554 if (child->GetRangeSize(rangeToUse, childSize, childDescent, dc, flags, wxPoint(position.x + sz.x, position.y)))
3555 {
3556 sz.y = wxMax(sz.y, childSize.y);
3557 sz.x += childSize.x;
3558 descent = wxMax(descent, childDescent);
3559 }
3560 }
3561
3562 node = node->GetNext();
3563 }
3564 size = sz;
3565 }
3566 else
3567 {
3568 // Use formatted data, with line breaks
3569 wxSize sz;
3570
3571 // We're going to loop through each line, and then for each line,
3572 // call GetRangeSize for the fragment that comprises that line.
3573 // Only we have to do that multiple times within the line, because
3574 // the line may be broken into pieces. For now ignore line break commands
3575 // (so we can assume that getting the unformatted size for a fragment
3576 // within a line is the actual size)
3577
3578 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetFirst();
3579 while (node)
3580 {
3581 wxRichTextLine* line = node->GetData();
3582 wxRichTextRange lineRange = line->GetAbsoluteRange();
3583 if (!lineRange.IsOutside(range))
3584 {
3585 wxSize lineSize;
3586
3587 wxRichTextObjectList::compatibility_iterator node2 = m_children.GetFirst();
3588 while (node2)
3589 {
3590 wxRichTextObject* child = node2->GetData();
3591
3592 if (!child->GetRange().IsOutside(lineRange))
3593 {
3594 wxRichTextRange rangeToUse = lineRange;
3595 rangeToUse.LimitTo(child->GetRange());
3596
3597 wxSize childSize;
3598 int childDescent = 0;
3599 if (child->GetRangeSize(rangeToUse, childSize, childDescent, dc, flags, wxPoint(position.x + sz.x, position.y)))
3600 {
3601 lineSize.y = wxMax(lineSize.y, childSize.y);
3602 lineSize.x += childSize.x;
3603 }
3604 descent = wxMax(descent, childDescent);
3605 }
3606
3607 node2 = node2->GetNext();
3608 }
3609
3610 // Increase size by a line (TODO: paragraph spacing)
3611 sz.y += lineSize.y;
3612 sz.x = wxMax(sz.x, lineSize.x);
3613 }
3614 node = node->GetNext();
3615 }
3616 size = sz;
3617 }
3618 return true;
3619}
3620
3621/// Finds the absolute position and row height for the given character position
3622bool wxRichTextParagraph::FindPosition(wxDC& dc, long index, wxPoint& pt, int* height, bool forceLineStart)
3623{
3624 if (index == -1)
3625 {
3626 wxRichTextLine* line = ((wxRichTextParagraphLayoutBox*)GetParent())->GetLineAtPosition(0);
3627 if (line)
3628 *height = line->GetSize().y;
3629 else
3630 *height = dc.GetCharHeight();
3631
3632 // -1 means 'the start of the buffer'.
3633 pt = GetPosition();
3634 if (line)
3635 pt = pt + line->GetPosition();
3636
3637 return true;
3638 }
3639
3640 // The final position in a paragraph is taken to mean the position
3641 // at the start of the next paragraph.
3642 if (index == GetRange().GetEnd())
3643 {
3644 wxRichTextParagraphLayoutBox* parent = wxDynamicCast(GetParent(), wxRichTextParagraphLayoutBox);
3645 wxASSERT( parent != NULL );
3646
3647 // Find the height at the next paragraph, if any
3648 wxRichTextLine* line = parent->GetLineAtPosition(index + 1);
3649 if (line)
3650 {
3651 *height = line->GetSize().y;
3652 pt = line->GetAbsolutePosition();
3653 }
3654 else
3655 {
3656 *height = dc.GetCharHeight();
3657 int indent = ConvertTenthsMMToPixels(dc, m_attributes.GetLeftIndent());
3658 pt = wxPoint(indent, GetCachedSize().y);
3659 }
3660
3661 return true;
3662 }
3663
3664 if (index < GetRange().GetStart() || index > GetRange().GetEnd())
3665 return false;
3666
3667 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetFirst();
3668 while (node)
3669 {
3670 wxRichTextLine* line = node->GetData();
3671 wxRichTextRange lineRange = line->GetAbsoluteRange();
3672 if (index >= lineRange.GetStart() && index <= lineRange.GetEnd())
3673 {
3674 // If this is the last point in the line, and we're forcing the
3675 // returned value to be the start of the next line, do the required
3676 // thing.
3677 if (index == lineRange.GetEnd() && forceLineStart)
3678 {
3679 if (node->GetNext())
3680 {
3681 wxRichTextLine* nextLine = node->GetNext()->GetData();
3682 *height = nextLine->GetSize().y;
3683 pt = nextLine->GetAbsolutePosition();
3684 return true;
3685 }
3686 }
3687
3688 pt.y = line->GetPosition().y + GetPosition().y;
3689
3690 wxRichTextRange r(lineRange.GetStart(), index);
3691 wxSize rangeSize;
3692 int descent = 0;
3693
3694 // We find the size of the line up to this point,
3695 // then we can add this size to the line start position and
3696 // paragraph start position to find the actual position.
3697
3698 if (GetRangeSize(r, rangeSize, descent, dc, wxRICHTEXT_UNFORMATTED, line->GetPosition()+ GetPosition()))
3699 {
3700 pt.x = line->GetPosition().x + GetPosition().x + rangeSize.x;
3701 *height = line->GetSize().y;
3702
3703 return true;
3704 }
3705
3706 }
3707
3708 node = node->GetNext();
3709 }
3710
3711 return false;
3712}
3713
3714/// Hit-testing: returns a flag indicating hit test details, plus
3715/// information about position
3716int wxRichTextParagraph::HitTest(wxDC& dc, const wxPoint& pt, long& textPosition)
3717{
3718 wxPoint paraPos = GetPosition();
3719
3720 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetFirst();
3721 while (node)
3722 {
3723 wxRichTextLine* line = node->GetData();
3724 wxPoint linePos = paraPos + line->GetPosition();
3725 wxSize lineSize = line->GetSize();
3726 wxRichTextRange lineRange = line->GetAbsoluteRange();
3727
3728 if (pt.y >= linePos.y && pt.y <= linePos.y + lineSize.y)
3729 {
3730 if (pt.x < linePos.x)
3731 {
3732 textPosition = lineRange.GetStart();
3733 return wxRICHTEXT_HITTEST_BEFORE|wxRICHTEXT_HITTEST_OUTSIDE;
3734 }
3735 else if (pt.x >= (linePos.x + lineSize.x))
3736 {
3737 textPosition = lineRange.GetEnd();
3738 return wxRICHTEXT_HITTEST_AFTER|wxRICHTEXT_HITTEST_OUTSIDE;
3739 }
3740 else
3741 {
3742 long i;
3743 int lastX = linePos.x;
3744 for (i = lineRange.GetStart(); i <= lineRange.GetEnd(); i++)
3745 {
3746 wxSize childSize;
3747 int descent = 0;
3748
3749 wxRichTextRange rangeToUse(lineRange.GetStart(), i);
3750
3751 GetRangeSize(rangeToUse, childSize, descent, dc, wxRICHTEXT_UNFORMATTED, linePos);
3752
3753 int nextX = childSize.x + linePos.x;
3754
3755 if (pt.x >= lastX && pt.x <= nextX)
3756 {
3757 textPosition = i;
3758
3759 // So now we know it's between i-1 and i.
3760 // Let's see if we can be more precise about
3761 // which side of the position it's on.
3762
3763 int midPoint = (nextX - lastX)/2 + lastX;
3764 if (pt.x >= midPoint)
3765 return wxRICHTEXT_HITTEST_AFTER;
3766 else
3767 return wxRICHTEXT_HITTEST_BEFORE;
3768 }
3769 else
3770 {
3771 lastX = nextX;
3772 }
3773 }
3774 }
3775 }
3776
3777 node = node->GetNext();
3778 }
3779
3780 return wxRICHTEXT_HITTEST_NONE;
3781}
3782
3783/// Split an object at this position if necessary, and return
3784/// the previous object, or NULL if inserting at beginning.
3785wxRichTextObject* wxRichTextParagraph::SplitAt(long pos, wxRichTextObject** previousObject)
3786{
3787 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
3788 while (node)
3789 {
3790 wxRichTextObject* child = node->GetData();
3791
3792 if (pos == child->GetRange().GetStart())
3793 {
3794 if (previousObject)
3795 {
3796 if (node->GetPrevious())
3797 *previousObject = node->GetPrevious()->GetData();
3798 else
3799 *previousObject = NULL;
3800 }
3801
3802 return child;
3803 }
3804
3805 if (child->GetRange().Contains(pos))
3806 {
3807 // This should create a new object, transferring part of
3808 // the content to the old object and the rest to the new object.
3809 wxRichTextObject* newObject = child->DoSplit(pos);
3810
3811 // If we couldn't split this object, just insert in front of it.
3812 if (!newObject)
3813 {
3814 // Maybe this is an empty string, try the next one
3815 // return child;
3816 }
3817 else
3818 {
3819 // Insert the new object after 'child'
3820 if (node->GetNext())
3821 m_children.Insert(node->GetNext(), newObject);
3822 else
3823 m_children.Append(newObject);
3824 newObject->SetParent(this);
3825
3826 if (previousObject)
3827 *previousObject = child;
3828
3829 return newObject;
3830 }
3831 }
3832
3833 node = node->GetNext();
3834 }
3835 if (previousObject)
3836 *previousObject = NULL;
3837 return NULL;
3838}
3839
3840/// Move content to a list from obj on
3841void wxRichTextParagraph::MoveToList(wxRichTextObject* obj, wxList& list)
3842{
3843 wxRichTextObjectList::compatibility_iterator node = m_children.Find(obj);
3844 while (node)
3845 {
3846 wxRichTextObject* child = node->GetData();
3847 list.Append(child);
3848
3849 wxRichTextObjectList::compatibility_iterator oldNode = node;
3850
3851 node = node->GetNext();
3852
3853 m_children.DeleteNode(oldNode);
3854 }
3855}
3856
3857/// Add content back from list
3858void wxRichTextParagraph::MoveFromList(wxList& list)
3859{
3860 for (wxList::compatibility_iterator node = list.GetFirst(); node; node = node->GetNext())
3861 {
3862 AppendChild((wxRichTextObject*) node->GetData());
3863 }
3864}
3865
3866/// Calculate range
3867void wxRichTextParagraph::CalculateRange(long start, long& end)
3868{
3869 wxRichTextCompositeObject::CalculateRange(start, end);
3870
3871 // Add one for end of paragraph
3872 end ++;
3873
3874 m_range.SetRange(start, end);
3875}
3876
3877/// Find the object at the given position
3878wxRichTextObject* wxRichTextParagraph::FindObjectAtPosition(long position)
3879{
3880 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
3881 while (node)
3882 {
3883 wxRichTextObject* obj = node->GetData();
3884 if (obj->GetRange().Contains(position))
3885 return obj;
3886
3887 node = node->GetNext();
3888 }
3889 return NULL;
3890}
3891
3892/// Get the plain text searching from the start or end of the range.
3893/// The resulting string may be shorter than the range given.
3894bool wxRichTextParagraph::GetContiguousPlainText(wxString& text, const wxRichTextRange& range, bool fromStart)
3895{
3896 text = wxEmptyString;
3897
3898 if (fromStart)
3899 {
3900 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
3901 while (node)
3902 {
3903 wxRichTextObject* obj = node->GetData();
3904 if (!obj->GetRange().IsOutside(range))
3905 {
3906 wxRichTextPlainText* textObj = wxDynamicCast(obj, wxRichTextPlainText);
3907 if (textObj)
3908 {
3909 text += textObj->GetTextForRange(range);
3910 }
3911 else
3912 return true;
3913 }
3914
3915 node = node->GetNext();
3916 }
3917 }
3918 else
3919 {
3920 wxRichTextObjectList::compatibility_iterator node = m_children.GetLast();
3921 while (node)
3922 {
3923 wxRichTextObject* obj = node->GetData();
3924 if (!obj->GetRange().IsOutside(range))
3925 {
3926 wxRichTextPlainText* textObj = wxDynamicCast(obj, wxRichTextPlainText);
3927 if (textObj)
3928 {
3929 text = textObj->GetTextForRange(range) + text;
3930 }
3931 else
3932 return true;
3933 }
3934
3935 node = node->GetPrevious();
3936 }
3937 }
3938
3939 return true;
3940}
3941
3942/// Find a suitable wrap position.
3943bool wxRichTextParagraph::FindWrapPosition(const wxRichTextRange& range, wxDC& dc, int availableSpace, long& wrapPosition)
3944{
3945 // Find the first position where the line exceeds the available space.
3946 wxSize sz;
3947 long breakPosition = range.GetEnd();
3948
3949 // Binary chop for speed
3950 long minPos = range.GetStart();
3951 long maxPos = range.GetEnd();
3952 while (true)
3953 {
3954 if (minPos == maxPos)
3955 {
3956 int descent = 0;
3957 GetRangeSize(wxRichTextRange(range.GetStart(), minPos), sz, descent, dc, wxRICHTEXT_UNFORMATTED);
3958
3959 if (sz.x > availableSpace)
3960 breakPosition = minPos - 1;
3961 break;
3962 }
3963 else if ((maxPos - minPos) == 1)
3964 {
3965 int descent = 0;
3966 GetRangeSize(wxRichTextRange(range.GetStart(), minPos), sz, descent, dc, wxRICHTEXT_UNFORMATTED);
3967
3968 if (sz.x > availableSpace)
3969 breakPosition = minPos - 1;
3970 else
3971 {
3972 GetRangeSize(wxRichTextRange(range.GetStart(), maxPos), sz, descent, dc, wxRICHTEXT_UNFORMATTED);
3973 if (sz.x > availableSpace)
3974 breakPosition = maxPos-1;
3975 }
3976 break;
3977 }
3978 else
3979 {
3980 long nextPos = minPos + ((maxPos - minPos) / 2);
3981
3982 int descent = 0;
3983 GetRangeSize(wxRichTextRange(range.GetStart(), nextPos), sz, descent, dc, wxRICHTEXT_UNFORMATTED);
3984
3985 if (sz.x > availableSpace)
3986 {
3987 maxPos = nextPos;
3988 }
3989 else
3990 {
3991 minPos = nextPos;
3992 }
3993 }
3994 }
3995
3996 // Now we know the last position on the line.
3997 // Let's try to find a word break.
3998
3999 wxString plainText;
4000 if (GetContiguousPlainText(plainText, wxRichTextRange(range.GetStart(), breakPosition), false))
4001 {
4002 int newLinePos = plainText.Find(wxRichTextLineBreakChar);
4003 if (newLinePos != wxNOT_FOUND)
4004 {
4005 breakPosition = wxMax(0, range.GetStart() + newLinePos);
4006 }
4007 else
4008 {
4009 int spacePos = plainText.Find(wxT(' '), true);
4010 int tabPos = plainText.Find(wxT('\t'), true);
4011 int pos = wxMax(spacePos, tabPos);
4012 if (pos != wxNOT_FOUND)
4013 {
4014 int positionsFromEndOfString = plainText.length() - pos - 1;
4015 breakPosition = breakPosition - positionsFromEndOfString;
4016 }
4017 }
4018 }
4019
4020 wrapPosition = breakPosition;
4021
4022 return true;
4023}
4024
4025/// Get the bullet text for this paragraph.
4026wxString wxRichTextParagraph::GetBulletText()
4027{
4028 if (GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE ||
4029 (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP))
4030 return wxEmptyString;
4031
4032 int number = GetAttributes().GetBulletNumber();
4033
4034 wxString text;
4035 if ((GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ARABIC) || (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE))
4036 {
4037 text.Printf(wxT("%d"), number);
4038 }
4039 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER)
4040 {
4041 // TODO: Unicode, and also check if number > 26
4042 text.Printf(wxT("%c"), (wxChar) (number+64));
4043 }
4044 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER)
4045 {
4046 // TODO: Unicode, and also check if number > 26
4047 text.Printf(wxT("%c"), (wxChar) (number+96));
4048 }
4049 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER)
4050 {
4051 text = wxRichTextDecimalToRoman(number);
4052 }
4053 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER)
4054 {
4055 text = wxRichTextDecimalToRoman(number);
4056 text.MakeLower();
4057 }
4058 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL)
4059 {
4060 text = GetAttributes().GetBulletText();
4061 }
4062
4063 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE)
4064 {
4065 // The outline style relies on the text being computed statically,
4066 // since it depends on other levels points (e.g. 1.2.1.1). So normally the bullet text
4067 // should be stored in the attributes; if not, just use the number for this
4068 // level, as previously computed.
4069 if (!GetAttributes().GetBulletText().IsEmpty())
4070 text = GetAttributes().GetBulletText();
4071 }
4072
4073 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PARENTHESES)
4074 {
4075 text = wxT("(") + text + wxT(")");
4076 }
4077 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS)
4078 {
4079 text = text + wxT(")");
4080 }
4081
4082 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PERIOD)
4083 {
4084 text += wxT(".");
4085 }
4086
4087 return text;
4088}
4089
4090/// Allocate or reuse a line object
4091wxRichTextLine* wxRichTextParagraph::AllocateLine(int pos)
4092{
4093 if (pos < (int) m_cachedLines.GetCount())
4094 {
4095 wxRichTextLine* line = m_cachedLines.Item(pos)->GetData();
4096 line->Init(this);
4097 return line;
4098 }
4099 else
4100 {
4101 wxRichTextLine* line = new wxRichTextLine(this);
4102 m_cachedLines.Append(line);
4103 return line;
4104 }
4105}
4106
4107/// Clear remaining unused line objects, if any
4108bool wxRichTextParagraph::ClearUnusedLines(int lineCount)
4109{
4110 int cachedLineCount = m_cachedLines.GetCount();
4111 if ((int) cachedLineCount > lineCount)
4112 {
4113 for (int i = 0; i < (int) (cachedLineCount - lineCount); i ++)
4114 {
4115 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetLast();
4116 wxRichTextLine* line = node->GetData();
4117 m_cachedLines.Erase(node);
4118 delete line;
4119 }
4120 }
4121 return true;
4122}
4123
4124/// Get combined attributes of the base style, paragraph style and character style. We use this to dynamically
4125/// retrieve the actual style.
4126wxTextAttr wxRichTextParagraph::GetCombinedAttributes(const wxTextAttr& contentStyle) const
4127{
4128 wxTextAttr attr;
4129 wxRichTextBuffer* buf = wxDynamicCast(GetParent(), wxRichTextBuffer);
4130 if (buf)
4131 {
4132 attr = buf->GetBasicStyle();
4133 wxRichTextApplyStyle(attr, GetAttributes());
4134 }
4135 else
4136 attr = GetAttributes();
4137
4138 wxRichTextApplyStyle(attr, contentStyle);
4139 return attr;
4140}
4141
4142/// Get combined attributes of the base style and paragraph style.
4143wxTextAttr wxRichTextParagraph::GetCombinedAttributes() const
4144{
4145 wxTextAttr attr;
4146 wxRichTextBuffer* buf = wxDynamicCast(GetParent(), wxRichTextBuffer);
4147 if (buf)
4148 {
4149 attr = buf->GetBasicStyle();
4150 wxRichTextApplyStyle(attr, GetAttributes());
4151 }
4152 else
4153 attr = GetAttributes();
4154
4155 return attr;
4156}
4157
4158/// Create default tabstop array
4159void wxRichTextParagraph::InitDefaultTabs()
4160{
4161 // create a default tab list at 10 mm each.
4162 for (int i = 0; i < 20; ++i)
4163 {
4164 sm_defaultTabs.Add(i*100);
4165 }
4166}
4167
4168/// Clear default tabstop array
4169void wxRichTextParagraph::ClearDefaultTabs()
4170{
4171 sm_defaultTabs.Clear();
4172}
4173
4174/// Get the first position from pos that has a line break character.
4175long wxRichTextParagraph::GetFirstLineBreakPosition(long pos)
4176{
4177 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
4178 while (node)
4179 {
4180 wxRichTextObject* obj = node->GetData();
4181 if (pos >= obj->GetRange().GetStart() && pos <= obj->GetRange().GetEnd())
4182 {
4183 wxRichTextPlainText* textObj = wxDynamicCast(obj, wxRichTextPlainText);
4184 if (textObj)
4185 {
4186 long breakPos = textObj->GetFirstLineBreakPosition(pos);
4187 if (breakPos > -1)
4188 return breakPos;
4189 }
4190 }
4191 node = node->GetNext();
4192 }
4193 return -1;
4194}
4195
4196/*!
4197 * wxRichTextLine
4198 * This object represents a line in a paragraph, and stores
4199 * offsets from the start of the paragraph representing the
4200 * start and end positions of the line.
4201 */
4202
4203wxRichTextLine::wxRichTextLine(wxRichTextParagraph* parent)
4204{
4205 Init(parent);
4206}
4207
4208/// Initialisation
4209void wxRichTextLine::Init(wxRichTextParagraph* parent)
4210{
4211 m_parent = parent;
4212 m_range.SetRange(-1, -1);
4213 m_pos = wxPoint(0, 0);
4214 m_size = wxSize(0, 0);
4215 m_descent = 0;
4216}
4217
4218/// Copy
4219void wxRichTextLine::Copy(const wxRichTextLine& obj)
4220{
4221 m_range = obj.m_range;
4222}
4223
4224/// Get the absolute object position
4225wxPoint wxRichTextLine::GetAbsolutePosition() const
4226{
4227 return m_parent->GetPosition() + m_pos;
4228}
4229
4230/// Get the absolute range
4231wxRichTextRange wxRichTextLine::GetAbsoluteRange() const
4232{
4233 wxRichTextRange range(m_range.GetStart() + m_parent->GetRange().GetStart(), 0);
4234 range.SetEnd(range.GetStart() + m_range.GetLength()-1);
4235 return range;
4236}
4237
4238/*!
4239 * wxRichTextPlainText
4240 * This object represents a single piece of text.
4241 */
4242
4243IMPLEMENT_DYNAMIC_CLASS(wxRichTextPlainText, wxRichTextObject)
4244
4245wxRichTextPlainText::wxRichTextPlainText(const wxString& text, wxRichTextObject* parent, wxTextAttr* style):
4246 wxRichTextObject(parent)
4247{
4248 if (style)
4249 SetAttributes(*style);
4250
4251 m_text = text;
4252}
4253
4254#define USE_KERNING_FIX 1
4255
4256// If insufficient tabs are defined, this is the tab width used
4257#define WIDTH_FOR_DEFAULT_TABS 50
4258
4259/// Draw the item
4260bool wxRichTextPlainText::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextRange& selectionRange, const wxRect& rect, int descent, int WXUNUSED(style))
4261{
4262 wxRichTextParagraph* para = wxDynamicCast(GetParent(), wxRichTextParagraph);
4263 wxASSERT (para != NULL);
4264
4265 wxTextAttr textAttr(para ? para->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4266
4267 int offset = GetRange().GetStart();
4268
4269 // Replace line break characters with spaces
4270 wxString str = m_text;
4271 wxString toRemove = wxRichTextLineBreakChar;
4272 str.Replace(toRemove, wxT(" "));
4273 if (textAttr.HasTextEffects() && (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS))
4274 str.MakeUpper();
4275
4276 long len = range.GetLength();
4277 wxString stringChunk = str.Mid(range.GetStart() - offset, (size_t) len);
4278
4279 int charHeight = dc.GetCharHeight();
4280
4281 int x = rect.x;
4282 int y = rect.y + (rect.height - charHeight - (descent - m_descent));
4283
4284 // Test for the optimized situations where all is selected, or none
4285 // is selected.
4286
4287 wxFont font(GetBuffer()->GetFontTable().FindFont(textAttr));
4288 wxCheckSetFont(dc, font);
4289
4290 // (a) All selected.
4291 if (selectionRange.GetStart() <= range.GetStart() && selectionRange.GetEnd() >= range.GetEnd())
4292 {
4293 DrawTabbedString(dc, textAttr, rect, stringChunk, x, y, true);
4294 }
4295 // (b) None selected.
4296 else if (selectionRange.GetEnd() < range.GetStart() || selectionRange.GetStart() > range.GetEnd())
4297 {
4298 // Draw all unselected
4299 DrawTabbedString(dc, textAttr, rect, stringChunk, x, y, false);
4300 }
4301 else
4302 {
4303 // (c) Part selected, part not
4304 // Let's draw unselected chunk, selected chunk, then unselected chunk.
4305
4306 dc.SetBackgroundMode(wxTRANSPARENT);
4307
4308 // 1. Initial unselected chunk, if any, up until start of selection.
4309 if (selectionRange.GetStart() > range.GetStart() && selectionRange.GetStart() <= range.GetEnd())
4310 {
4311 int r1 = range.GetStart();
4312 int s1 = selectionRange.GetStart()-1;
4313 int fragmentLen = s1 - r1 + 1;
4314 if (fragmentLen < 0)
4315 wxLogDebug(wxT("Mid(%d, %d"), (int)(r1 - offset), (int)fragmentLen);
4316 wxString stringFragment = str.Mid(r1 - offset, fragmentLen);
4317
4318 DrawTabbedString(dc, textAttr, rect, stringFragment, x, y, false);
4319
4320#if USE_KERNING_FIX
4321 if (stringChunk.Find(wxT("\t")) == wxNOT_FOUND)
4322 {
4323 // Compensate for kerning difference
4324 wxString stringFragment2(str.Mid(r1 - offset, fragmentLen+1));
4325 wxString stringFragment3(str.Mid(r1 - offset + fragmentLen, 1));
4326
4327 wxCoord w1, h1, w2, h2, w3, h3;
4328 dc.GetTextExtent(stringFragment, & w1, & h1);
4329 dc.GetTextExtent(stringFragment2, & w2, & h2);
4330 dc.GetTextExtent(stringFragment3, & w3, & h3);
4331
4332 int kerningDiff = (w1 + w3) - w2;
4333 x = x - kerningDiff;
4334 }
4335#endif
4336 }
4337
4338 // 2. Selected chunk, if any.
4339 if (selectionRange.GetEnd() >= range.GetStart())
4340 {
4341 int s1 = wxMax(selectionRange.GetStart(), range.GetStart());
4342 int s2 = wxMin(selectionRange.GetEnd(), range.GetEnd());
4343
4344 int fragmentLen = s2 - s1 + 1;
4345 if (fragmentLen < 0)
4346 wxLogDebug(wxT("Mid(%d, %d"), (int)(s1 - offset), (int)fragmentLen);
4347 wxString stringFragment = str.Mid(s1 - offset, fragmentLen);
4348
4349 DrawTabbedString(dc, textAttr, rect, stringFragment, x, y, true);
4350
4351#if USE_KERNING_FIX
4352 if (stringChunk.Find(wxT("\t")) == wxNOT_FOUND)
4353 {
4354 // Compensate for kerning difference
4355 wxString stringFragment2(str.Mid(s1 - offset, fragmentLen+1));
4356 wxString stringFragment3(str.Mid(s1 - offset + fragmentLen, 1));
4357
4358 wxCoord w1, h1, w2, h2, w3, h3;
4359 dc.GetTextExtent(stringFragment, & w1, & h1);
4360 dc.GetTextExtent(stringFragment2, & w2, & h2);
4361 dc.GetTextExtent(stringFragment3, & w3, & h3);
4362
4363 int kerningDiff = (w1 + w3) - w2;
4364 x = x - kerningDiff;
4365 }
4366#endif
4367 }
4368
4369 // 3. Remaining unselected chunk, if any
4370 if (selectionRange.GetEnd() < range.GetEnd())
4371 {
4372 int s2 = wxMin(selectionRange.GetEnd()+1, range.GetEnd());
4373 int r2 = range.GetEnd();
4374
4375 int fragmentLen = r2 - s2 + 1;
4376 if (fragmentLen < 0)
4377 wxLogDebug(wxT("Mid(%d, %d"), (int)(s2 - offset), (int)fragmentLen);
4378 wxString stringFragment = str.Mid(s2 - offset, fragmentLen);
4379
4380 DrawTabbedString(dc, textAttr, rect, stringFragment, x, y, false);
4381 }
4382 }
4383
4384 return true;
4385}
4386
4387bool wxRichTextPlainText::DrawTabbedString(wxDC& dc, const wxTextAttr& attr, const wxRect& rect,wxString& str, wxCoord& x, wxCoord& y, bool selected)
4388{
4389 bool hasTabs = (str.Find(wxT('\t')) != wxNOT_FOUND);
4390
4391 wxArrayInt tabArray;
4392 int tabCount;
4393 if (hasTabs)
4394 {
4395 if (attr.GetTabs().IsEmpty())
4396 tabArray = wxRichTextParagraph::GetDefaultTabs();
4397 else
4398 tabArray = attr.GetTabs();
4399 tabCount = tabArray.GetCount();
4400
4401 for (int i = 0; i < tabCount; ++i)
4402 {
4403 int pos = tabArray[i];
4404 pos = ConvertTenthsMMToPixels(dc, pos);
4405 tabArray[i] = pos;
4406 }
4407 }
4408 else
4409 tabCount = 0;
4410
4411 int nextTabPos = -1;
4412 int tabPos = -1;
4413 wxCoord w, h;
4414
4415 if (selected)
4416 {
4417 wxColour highlightColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT));
4418 wxColour highlightTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT));
4419
4420 wxCheckSetBrush(dc, wxBrush(highlightColour));
4421 wxCheckSetPen(dc, wxPen(highlightColour));
4422 dc.SetTextForeground(highlightTextColour);
4423 dc.SetBackgroundMode(wxTRANSPARENT);
4424 }
4425 else
4426 {
4427 dc.SetTextForeground(attr.GetTextColour());
4428
4429 if (attr.HasFlag(wxTEXT_ATTR_BACKGROUND_COLOUR) && attr.GetBackgroundColour().IsOk())
4430 {
4431 dc.SetBackgroundMode(wxSOLID);
4432 dc.SetTextBackground(attr.GetBackgroundColour());
4433 }
4434 else
4435 dc.SetBackgroundMode(wxTRANSPARENT);
4436 }
4437
4438 while (hasTabs)
4439 {
4440 // the string has a tab
4441 // break up the string at the Tab
4442 wxString stringChunk = str.BeforeFirst(wxT('\t'));
4443 str = str.AfterFirst(wxT('\t'));
4444 dc.GetTextExtent(stringChunk, & w, & h);
4445 tabPos = x + w;
4446 bool not_found = true;
4447 for (int i = 0; i < tabCount && not_found; ++i)
4448 {
4449 nextTabPos = tabArray.Item(i);
4450
4451 // Find the next tab position.
4452 // Even if we're at the end of the tab array, we must still draw the chunk.
4453
4454 if (nextTabPos > tabPos || (i == (tabCount - 1)))
4455 {
4456 if (nextTabPos <= tabPos)
4457 {
4458 int defaultTabWidth = ConvertTenthsMMToPixels(dc, WIDTH_FOR_DEFAULT_TABS);
4459 nextTabPos = tabPos + defaultTabWidth;
4460 }
4461
4462 not_found = false;
4463 if (selected)
4464 {
4465 w = nextTabPos - x;
4466 wxRect selRect(x, rect.y, w, rect.GetHeight());
4467 dc.DrawRectangle(selRect);
4468 }
4469 dc.DrawText(stringChunk, x, y);
4470
4471 if (attr.HasTextEffects() && (attr.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH))
4472 {
4473 wxPen oldPen = dc.GetPen();
4474 wxCheckSetPen(dc, wxPen(attr.GetTextColour(), 1));
4475 dc.DrawLine(x, (int) (y+(h/2)+0.5), x+w, (int) (y+(h/2)+0.5));
4476 wxCheckSetPen(dc, oldPen);
4477 }
4478
4479 x = nextTabPos;
4480 }
4481 }
4482 hasTabs = (str.Find(wxT('\t')) != wxNOT_FOUND);
4483 }
4484
4485 if (!str.IsEmpty())
4486 {
4487 dc.GetTextExtent(str, & w, & h);
4488 if (selected)
4489 {
4490 wxRect selRect(x, rect.y, w, rect.GetHeight());
4491 dc.DrawRectangle(selRect);
4492 }
4493 dc.DrawText(str, x, y);
4494
4495 if (attr.HasTextEffects() && (attr.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH))
4496 {
4497 wxPen oldPen = dc.GetPen();
4498 wxCheckSetPen(dc, wxPen(attr.GetTextColour(), 1));
4499 dc.DrawLine(x, (int) (y+(h/2)+0.5), x+w, (int) (y+(h/2)+0.5));
4500 wxCheckSetPen(dc, oldPen);
4501 }
4502
4503 x += w;
4504 }
4505 return true;
4506
4507}
4508
4509/// Lay the item out
4510bool wxRichTextPlainText::Layout(wxDC& dc, const wxRect& WXUNUSED(rect), int WXUNUSED(style))
4511{
4512 // Only lay out if we haven't already cached the size
4513 if (m_size.x == -1)
4514 GetRangeSize(GetRange(), m_size, m_descent, dc, 0, wxPoint(0, 0));
4515
4516 return true;
4517}
4518
4519/// Copy
4520void wxRichTextPlainText::Copy(const wxRichTextPlainText& obj)
4521{
4522 wxRichTextObject::Copy(obj);
4523
4524 m_text = obj.m_text;
4525}
4526
4527/// Get/set the object size for the given range. Returns false if the range
4528/// is invalid for this object.
4529bool wxRichTextPlainText::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, int WXUNUSED(flags), wxPoint position) const
4530{
4531 if (!range.IsWithin(GetRange()))
4532 return false;
4533
4534 wxRichTextParagraph* para = wxDynamicCast(GetParent(), wxRichTextParagraph);
4535 wxASSERT (para != NULL);
4536
4537 wxTextAttr textAttr(para ? para->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4538
4539 // Always assume unformatted text, since at this level we have no knowledge
4540 // of line breaks - and we don't need it, since we'll calculate size within
4541 // formatted text by doing it in chunks according to the line ranges
4542
4543 wxFont font(GetBuffer()->GetFontTable().FindFont(textAttr));
4544 wxCheckSetFont(dc, font);
4545
4546 int startPos = range.GetStart() - GetRange().GetStart();
4547 long len = range.GetLength();
4548
4549 wxString str(m_text);
4550 wxString toReplace = wxRichTextLineBreakChar;
4551 str.Replace(toReplace, wxT(" "));
4552
4553 wxString stringChunk = str.Mid(startPos, (size_t) len);
4554
4555 if (textAttr.HasTextEffects() && (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS))
4556 stringChunk.MakeUpper();
4557
4558 wxCoord w, h;
4559 int width = 0;
4560 if (stringChunk.Find(wxT('\t')) != wxNOT_FOUND)
4561 {
4562 // the string has a tab
4563 wxArrayInt tabArray;
4564 if (textAttr.GetTabs().IsEmpty())
4565 tabArray = wxRichTextParagraph::GetDefaultTabs();
4566 else
4567 tabArray = textAttr.GetTabs();
4568
4569 int tabCount = tabArray.GetCount();
4570
4571 for (int i = 0; i < tabCount; ++i)
4572 {
4573 int pos = tabArray[i];
4574 pos = ((wxRichTextPlainText*) this)->ConvertTenthsMMToPixels(dc, pos);
4575 tabArray[i] = pos;
4576 }
4577
4578 int nextTabPos = -1;
4579
4580 while (stringChunk.Find(wxT('\t')) >= 0)
4581 {
4582 // the string has a tab
4583 // break up the string at the Tab
4584 wxString stringFragment = stringChunk.BeforeFirst(wxT('\t'));
4585 stringChunk = stringChunk.AfterFirst(wxT('\t'));
4586 dc.GetTextExtent(stringFragment, & w, & h);
4587 width += w;
4588 int absoluteWidth = width + position.x;
4589
4590 bool notFound = true;
4591 for (int i = 0; i < tabCount && notFound; ++i)
4592 {
4593 nextTabPos = tabArray.Item(i);
4594
4595 // Find the next tab position.
4596 // Even if we're at the end of the tab array, we must still process the chunk.
4597
4598 if (nextTabPos > absoluteWidth || (i == (tabCount - 1)))
4599 {
4600 if (nextTabPos <= absoluteWidth)
4601 {
4602 int defaultTabWidth = ((wxRichTextPlainText*) this)->ConvertTenthsMMToPixels(dc, WIDTH_FOR_DEFAULT_TABS);
4603 nextTabPos = absoluteWidth + defaultTabWidth;
4604 }
4605
4606 notFound = false;
4607 width = nextTabPos - position.x;
4608 }
4609 }
4610 }
4611 }
4612 dc.GetTextExtent(stringChunk, & w, & h, & descent);
4613 width += w;
4614 size = wxSize(width, dc.GetCharHeight());
4615
4616 return true;
4617}
4618
4619/// Do a split, returning an object containing the second part, and setting
4620/// the first part in 'this'.
4621wxRichTextObject* wxRichTextPlainText::DoSplit(long pos)
4622{
4623 long index = pos - GetRange().GetStart();
4624
4625 if (index < 0 || index >= (int) m_text.length())
4626 return NULL;
4627
4628 wxString firstPart = m_text.Mid(0, index);
4629 wxString secondPart = m_text.Mid(index);
4630
4631 m_text = firstPart;
4632
4633 wxRichTextPlainText* newObject = new wxRichTextPlainText(secondPart);
4634 newObject->SetAttributes(GetAttributes());
4635
4636 newObject->SetRange(wxRichTextRange(pos, GetRange().GetEnd()));
4637 GetRange().SetEnd(pos-1);
4638
4639 return newObject;
4640}
4641
4642/// Calculate range
4643void wxRichTextPlainText::CalculateRange(long start, long& end)
4644{
4645 end = start + m_text.length() - 1;
4646 m_range.SetRange(start, end);
4647}
4648
4649/// Delete range
4650bool wxRichTextPlainText::DeleteRange(const wxRichTextRange& range)
4651{
4652 wxRichTextRange r = range;
4653
4654 r.LimitTo(GetRange());
4655
4656 if (r.GetStart() == GetRange().GetStart() && r.GetEnd() == GetRange().GetEnd())
4657 {
4658 m_text.Empty();
4659 return true;
4660 }
4661
4662 long startIndex = r.GetStart() - GetRange().GetStart();
4663 long len = r.GetLength();
4664
4665 m_text = m_text.Mid(0, startIndex) + m_text.Mid(startIndex+len);
4666 return true;
4667}
4668
4669/// Get text for the given range.
4670wxString wxRichTextPlainText::GetTextForRange(const wxRichTextRange& range) const
4671{
4672 wxRichTextRange r = range;
4673
4674 r.LimitTo(GetRange());
4675
4676 long startIndex = r.GetStart() - GetRange().GetStart();
4677 long len = r.GetLength();
4678
4679 return m_text.Mid(startIndex, len);
4680}
4681
4682/// Returns true if this object can merge itself with the given one.
4683bool wxRichTextPlainText::CanMerge(wxRichTextObject* object) const
4684{
4685 return object->GetClassInfo() == CLASSINFO(wxRichTextPlainText) &&
4686 (m_text.empty() || wxTextAttrEq(GetAttributes(), object->GetAttributes()));
4687}
4688
4689/// Returns true if this object merged itself with the given one.
4690/// The calling code will then delete the given object.
4691bool wxRichTextPlainText::Merge(wxRichTextObject* object)
4692{
4693 wxRichTextPlainText* textObject = wxDynamicCast(object, wxRichTextPlainText);
4694 wxASSERT( textObject != NULL );
4695
4696 if (textObject)
4697 {
4698 m_text += textObject->GetText();
4699 wxRichTextApplyStyle(m_attributes, textObject->GetAttributes());
4700 return true;
4701 }
4702 else
4703 return false;
4704}
4705
4706/// Dump to output stream for debugging
4707void wxRichTextPlainText::Dump(wxTextOutputStream& stream)
4708{
4709 wxRichTextObject::Dump(stream);
4710 stream << m_text << wxT("\n");
4711}
4712
4713/// Get the first position from pos that has a line break character.
4714long wxRichTextPlainText::GetFirstLineBreakPosition(long pos)
4715{
4716 int i;
4717 int len = m_text.length();
4718 int startPos = pos - m_range.GetStart();
4719 for (i = startPos; i < len; i++)
4720 {
4721 wxChar ch = m_text[i];
4722 if (ch == wxRichTextLineBreakChar)
4723 {
4724 return i + m_range.GetStart();
4725 }
4726 }
4727 return -1;
4728}
4729
4730/*!
4731 * wxRichTextBuffer
4732 * This is a kind of box, used to represent the whole buffer
4733 */
4734
4735IMPLEMENT_DYNAMIC_CLASS(wxRichTextBuffer, wxRichTextParagraphLayoutBox)
4736
4737wxList wxRichTextBuffer::sm_handlers;
4738wxRichTextRenderer* wxRichTextBuffer::sm_renderer = NULL;
4739int wxRichTextBuffer::sm_bulletRightMargin = 20;
4740float wxRichTextBuffer::sm_bulletProportion = (float) 0.3;
4741
4742/// Initialisation
4743void wxRichTextBuffer::Init()
4744{
4745 m_commandProcessor = new wxCommandProcessor;
4746 m_styleSheet = NULL;
4747 m_modified = false;
4748 m_batchedCommandDepth = 0;
4749 m_batchedCommand = NULL;
4750 m_suppressUndo = 0;
4751 m_handlerFlags = 0;
4752 m_scale = 1.0;
4753}
4754
4755/// Initialisation
4756wxRichTextBuffer::~wxRichTextBuffer()
4757{
4758 delete m_commandProcessor;
4759 delete m_batchedCommand;
4760
4761 ClearStyleStack();
4762 ClearEventHandlers();
4763}
4764
4765void wxRichTextBuffer::ResetAndClearCommands()
4766{
4767 Reset();
4768
4769 GetCommandProcessor()->ClearCommands();
4770
4771 Modify(false);
4772 Invalidate(wxRICHTEXT_ALL);
4773}
4774
4775void wxRichTextBuffer::Copy(const wxRichTextBuffer& obj)
4776{
4777 wxRichTextParagraphLayoutBox::Copy(obj);
4778
4779 m_styleSheet = obj.m_styleSheet;
4780 m_modified = obj.m_modified;
4781 m_batchedCommandDepth = obj.m_batchedCommandDepth;
4782 m_batchedCommand = obj.m_batchedCommand;
4783 m_suppressUndo = obj.m_suppressUndo;
4784}
4785
4786/// Push style sheet to top of stack
4787bool wxRichTextBuffer::PushStyleSheet(wxRichTextStyleSheet* styleSheet)
4788{
4789 if (m_styleSheet)
4790 styleSheet->InsertSheet(m_styleSheet);
4791
4792 SetStyleSheet(styleSheet);
4793
4794 return true;
4795}
4796
4797/// Pop style sheet from top of stack
4798wxRichTextStyleSheet* wxRichTextBuffer::PopStyleSheet()
4799{
4800 if (m_styleSheet)
4801 {
4802 wxRichTextStyleSheet* oldSheet = m_styleSheet;
4803 m_styleSheet = oldSheet->GetNextSheet();
4804 oldSheet->Unlink();
4805
4806 return oldSheet;
4807 }
4808 else
4809 return NULL;
4810}
4811
4812/// Submit command to insert paragraphs
4813bool wxRichTextBuffer::InsertParagraphsWithUndo(long pos, const wxRichTextParagraphLayoutBox& paragraphs, wxRichTextCtrl* ctrl, int flags)
4814{
4815 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Text"), wxRICHTEXT_INSERT, this, ctrl, false);
4816
4817 wxTextAttr attr(GetDefaultStyle());
4818
4819 wxTextAttr* p = NULL;
4820 wxTextAttr paraAttr;
4821 if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
4822 {
4823 paraAttr = GetStyleForNewParagraph(pos);
4824 if (!paraAttr.IsDefault())
4825 p = & paraAttr;
4826 }
4827 else
4828 p = & attr;
4829
4830 action->GetNewParagraphs() = paragraphs;
4831
4832 action->SetPosition(pos);
4833
4834 wxRichTextRange range = wxRichTextRange(pos, pos + paragraphs.GetRange().GetEnd() - 1);
4835 if (!paragraphs.GetPartialParagraph())
4836 range.SetEnd(range.GetEnd()+1);
4837
4838 // Set the range we'll need to delete in Undo
4839 action->SetRange(range);
4840
4841 SubmitAction(action);
4842
4843 return true;
4844}
4845
4846/// Submit command to insert the given text
4847bool wxRichTextBuffer::InsertTextWithUndo(long pos, const wxString& text, wxRichTextCtrl* ctrl, int flags)
4848{
4849 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Text"), wxRICHTEXT_INSERT, this, ctrl, false);
4850
4851 wxTextAttr* p = NULL;
4852 wxTextAttr paraAttr;
4853 if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
4854 {
4855 // Get appropriate paragraph style
4856 paraAttr = GetStyleForNewParagraph(pos, false, false);
4857 if (!paraAttr.IsDefault())
4858 p = & paraAttr;
4859 }
4860
4861 action->GetNewParagraphs().AddParagraphs(text, p);
4862
4863 int length = action->GetNewParagraphs().GetRange().GetLength();
4864
4865 if (text.length() > 0 && text.Last() != wxT('\n'))
4866 {
4867 // Don't count the newline when undoing
4868 length --;
4869 action->GetNewParagraphs().SetPartialParagraph(true);
4870 }
4871 else if (text.length() > 0 && text.Last() == wxT('\n'))
4872 length --;
4873
4874 action->SetPosition(pos);
4875
4876 // Set the range we'll need to delete in Undo
4877 action->SetRange(wxRichTextRange(pos, pos + length - 1));
4878
4879 SubmitAction(action);
4880
4881 return true;
4882}
4883
4884/// Submit command to insert the given text
4885bool wxRichTextBuffer::InsertNewlineWithUndo(long pos, wxRichTextCtrl* ctrl, int flags)
4886{
4887 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Text"), wxRICHTEXT_INSERT, this, ctrl, false);
4888
4889 wxTextAttr* p = NULL;
4890 wxTextAttr paraAttr;
4891 if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
4892 {
4893 paraAttr = GetStyleForNewParagraph(pos, false, true /* look for next paragraph style */);
4894 if (!paraAttr.IsDefault())
4895 p = & paraAttr;
4896 }
4897
4898 wxTextAttr attr(GetDefaultStyle());
4899
4900 wxRichTextParagraph* newPara = new wxRichTextParagraph(wxEmptyString, this, & attr);
4901 action->GetNewParagraphs().AppendChild(newPara);
4902 action->GetNewParagraphs().UpdateRanges();
4903 action->GetNewParagraphs().SetPartialParagraph(false);
4904 wxRichTextParagraph* para = GetParagraphAtPosition(pos, false);
4905 long pos1 = pos;
4906
4907 if (flags & wxRICHTEXT_INSERT_INTERACTIVE)
4908 {
4909 if (para && para->GetRange().GetEnd() == pos)
4910 pos1 ++;
4911 }
4912
4913 action->SetPosition(pos);
4914
4915 if (p)
4916 newPara->SetAttributes(*p);
4917
4918 // Use the default character style
4919 // Use the default character style
4920 if (!GetDefaultStyle().IsDefault() && newPara->GetChildren().GetFirst())
4921 {
4922 // Check whether the default style merely reflects the paragraph/basic style,
4923 // in which case don't apply it.
4924 wxTextAttrEx defaultStyle(GetDefaultStyle());
4925 wxTextAttrEx toApply;
4926 if (para)
4927 {
4928 wxRichTextAttr combinedAttr = para->GetCombinedAttributes();
4929 wxTextAttrEx newAttr;
4930 // This filters out attributes that are accounted for by the current
4931 // paragraph/basic style
4932 wxRichTextApplyStyle(toApply, defaultStyle, & combinedAttr);
4933 }
4934 else
4935 toApply = defaultStyle;
4936
4937 if (!toApply.IsDefault())
4938 newPara->GetChildren().GetFirst()->GetData()->SetAttributes(toApply);
4939 }
4940
4941 // Set the range we'll need to delete in Undo
4942 action->SetRange(wxRichTextRange(pos1, pos1));
4943
4944 SubmitAction(action);
4945
4946 return true;
4947}
4948
4949/// Submit command to insert the given image
4950bool wxRichTextBuffer::InsertImageWithUndo(long pos, const wxRichTextImageBlock& imageBlock, wxRichTextCtrl* ctrl, int flags)
4951{
4952 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Image"), wxRICHTEXT_INSERT, this, ctrl, false);
4953
4954 wxTextAttr* p = NULL;
4955 wxTextAttr paraAttr;
4956 if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
4957 {
4958 paraAttr = GetStyleForNewParagraph(pos);
4959 if (!paraAttr.IsDefault())
4960 p = & paraAttr;
4961 }
4962
4963 wxTextAttr attr(GetDefaultStyle());
4964
4965 wxRichTextParagraph* newPara = new wxRichTextParagraph(this, & attr);
4966 if (p)
4967 newPara->SetAttributes(*p);
4968
4969 wxRichTextImage* imageObject = new wxRichTextImage(imageBlock, newPara);
4970 newPara->AppendChild(imageObject);
4971 action->GetNewParagraphs().AppendChild(newPara);
4972 action->GetNewParagraphs().UpdateRanges();
4973
4974 action->GetNewParagraphs().SetPartialParagraph(true);
4975
4976 action->SetPosition(pos);
4977
4978 // Set the range we'll need to delete in Undo
4979 action->SetRange(wxRichTextRange(pos, pos));
4980
4981 SubmitAction(action);
4982
4983 return true;
4984}
4985
4986/// Get the style that is appropriate for a new paragraph at this position.
4987/// If the previous paragraph has a paragraph style name, look up the next-paragraph
4988/// style.
4989wxTextAttr wxRichTextBuffer::GetStyleForNewParagraph(long pos, bool caretPosition, bool lookUpNewParaStyle) const
4990{
4991 wxRichTextParagraph* para = GetParagraphAtPosition(pos, caretPosition);
4992 if (para)
4993 {
4994 wxTextAttr attr;
4995 bool foundAttributes = false;
4996
4997 // Look for a matching paragraph style
4998 if (lookUpNewParaStyle && !para->GetAttributes().GetParagraphStyleName().IsEmpty() && GetStyleSheet())
4999 {
5000 wxRichTextParagraphStyleDefinition* paraDef = GetStyleSheet()->FindParagraphStyle(para->GetAttributes().GetParagraphStyleName());
5001 if (paraDef)
5002 {
5003 // If we're not at the end of the paragraph, then we apply THIS style, and not the designated next style.
5004 if (para->GetRange().GetEnd() == pos && !paraDef->GetNextStyle().IsEmpty())
5005 {
5006 wxRichTextParagraphStyleDefinition* nextParaDef = GetStyleSheet()->FindParagraphStyle(paraDef->GetNextStyle());
5007 if (nextParaDef)
5008 {
5009 foundAttributes = true;
5010 attr = nextParaDef->GetStyleMergedWithBase(GetStyleSheet());
5011 }
5012 }
5013
5014 // If we didn't find the 'next style', use this style instead.
5015 if (!foundAttributes)
5016 {
5017 foundAttributes = true;
5018 attr = paraDef->GetStyleMergedWithBase(GetStyleSheet());
5019 }
5020 }
5021 }
5022 if (!foundAttributes)
5023 {
5024 attr = para->GetAttributes();
5025 int flags = attr.GetFlags();
5026
5027 // Eliminate character styles
5028 flags &= ( (~ wxTEXT_ATTR_FONT) |
5029 (~ wxTEXT_ATTR_TEXT_COLOUR) |
5030 (~ wxTEXT_ATTR_BACKGROUND_COLOUR) );
5031 attr.SetFlags(flags);
5032 }
5033
5034 // Now see if we need to number the paragraph.
5035 if (attr.HasBulletStyle())
5036 {
5037 wxTextAttr numberingAttr;
5038 if (FindNextParagraphNumber(para, numberingAttr))
5039 wxRichTextApplyStyle(attr, (const wxTextAttr&) numberingAttr);
5040 }
5041
5042 return attr;
5043 }
5044 else
5045 return wxTextAttr();
5046}
5047
5048/// Submit command to delete this range
5049bool wxRichTextBuffer::DeleteRangeWithUndo(const wxRichTextRange& range, wxRichTextCtrl* ctrl)
5050{
5051 wxRichTextAction* action = new wxRichTextAction(NULL, _("Delete"), wxRICHTEXT_DELETE, this, ctrl);
5052
5053 action->SetPosition(ctrl->GetCaretPosition());
5054
5055 // Set the range to delete
5056 action->SetRange(range);
5057
5058 // Copy the fragment that we'll need to restore in Undo
5059 CopyFragment(range, action->GetOldParagraphs());
5060
5061 // Special case: if there is only one (non-partial) paragraph,
5062 // we must save the *next* paragraph's style, because that
5063 // is the style we must apply when inserting the content back
5064 // when undoing the delete. (This is because we're merging the
5065 // paragraph with the previous paragraph and throwing away
5066 // the style, and we need to restore it.)
5067 if (!action->GetOldParagraphs().GetPartialParagraph() && action->GetOldParagraphs().GetChildCount() == 1)
5068 {
5069 wxRichTextParagraph* lastPara = GetParagraphAtPosition(range.GetStart());
5070 if (lastPara)
5071 {
5072 wxRichTextParagraph* nextPara = GetParagraphAtPosition(range.GetEnd()+1);
5073 if (nextPara)
5074 {
5075 wxRichTextParagraph* para = (wxRichTextParagraph*) action->GetOldParagraphs().GetChild(0);
5076 para->SetAttributes(nextPara->GetAttributes());
5077 }
5078 }
5079 }
5080
5081 SubmitAction(action);
5082
5083 return true;
5084}
5085
5086/// Collapse undo/redo commands
5087bool wxRichTextBuffer::BeginBatchUndo(const wxString& cmdName)
5088{
5089 if (m_batchedCommandDepth == 0)
5090 {
5091 wxASSERT(m_batchedCommand == NULL);
5092 if (m_batchedCommand)
5093 {
5094 GetCommandProcessor()->Submit(m_batchedCommand);
5095 }
5096 m_batchedCommand = new wxRichTextCommand(cmdName);
5097 }
5098
5099 m_batchedCommandDepth ++;
5100
5101 return true;
5102}
5103
5104/// Collapse undo/redo commands
5105bool wxRichTextBuffer::EndBatchUndo()
5106{
5107 m_batchedCommandDepth --;
5108
5109 wxASSERT(m_batchedCommandDepth >= 0);
5110 wxASSERT(m_batchedCommand != NULL);
5111
5112 if (m_batchedCommandDepth == 0)
5113 {
5114 GetCommandProcessor()->Submit(m_batchedCommand);
5115 m_batchedCommand = NULL;
5116 }
5117
5118 return true;
5119}
5120
5121/// Submit immediately, or delay according to whether collapsing is on
5122bool wxRichTextBuffer::SubmitAction(wxRichTextAction* action)
5123{
5124 if (BatchingUndo() && m_batchedCommand && !SuppressingUndo())
5125 m_batchedCommand->AddAction(action);
5126 else
5127 {
5128 wxRichTextCommand* cmd = new wxRichTextCommand(action->GetName());
5129 cmd->AddAction(action);
5130
5131 // Only store it if we're not suppressing undo.
5132 return GetCommandProcessor()->Submit(cmd, !SuppressingUndo());
5133 }
5134
5135 return true;
5136}
5137
5138/// Begin suppressing undo/redo commands.
5139bool wxRichTextBuffer::BeginSuppressUndo()
5140{
5141 m_suppressUndo ++;
5142
5143 return true;
5144}
5145
5146/// End suppressing undo/redo commands.
5147bool wxRichTextBuffer::EndSuppressUndo()
5148{
5149 m_suppressUndo --;
5150
5151 return true;
5152}
5153
5154/// Begin using a style
5155bool wxRichTextBuffer::BeginStyle(const wxTextAttr& style)
5156{
5157 wxTextAttr newStyle(GetDefaultStyle());
5158
5159 // Save the old default style
5160 m_attributeStack.Append((wxObject*) new wxTextAttr(GetDefaultStyle()));
5161
5162 wxRichTextApplyStyle(newStyle, style);
5163 newStyle.SetFlags(style.GetFlags()|newStyle.GetFlags());
5164
5165 SetDefaultStyle(newStyle);
5166
5167 // wxLogDebug("Default style size = %d", GetDefaultStyle().GetFont().GetPointSize());
5168
5169 return true;
5170}
5171
5172/// End the style
5173bool wxRichTextBuffer::EndStyle()
5174{
5175 if (!m_attributeStack.GetFirst())
5176 {
5177 wxLogDebug(_("Too many EndStyle calls!"));
5178 return false;
5179 }
5180
5181 wxList::compatibility_iterator node = m_attributeStack.GetLast();
5182 wxTextAttr* attr = (wxTextAttr*)node->GetData();
5183 m_attributeStack.Erase(node);
5184
5185 SetDefaultStyle(*attr);
5186
5187 delete attr;
5188 return true;
5189}
5190
5191/// End all styles
5192bool wxRichTextBuffer::EndAllStyles()
5193{
5194 while (m_attributeStack.GetCount() != 0)
5195 EndStyle();
5196 return true;
5197}
5198
5199/// Clear the style stack
5200void wxRichTextBuffer::ClearStyleStack()
5201{
5202 for (wxList::compatibility_iterator node = m_attributeStack.GetFirst(); node; node = node->GetNext())
5203 delete (wxTextAttr*) node->GetData();
5204 m_attributeStack.Clear();
5205}
5206
5207/// Begin using bold
5208bool wxRichTextBuffer::BeginBold()
5209{
5210 wxTextAttr attr;
5211 attr.SetFontWeight(wxBOLD);
5212
5213 return BeginStyle(attr);
5214}
5215
5216/// Begin using italic
5217bool wxRichTextBuffer::BeginItalic()
5218{
5219 wxTextAttr attr;
5220 attr.SetFontStyle(wxITALIC);
5221
5222 return BeginStyle(attr);
5223}
5224
5225/// Begin using underline
5226bool wxRichTextBuffer::BeginUnderline()
5227{
5228 wxTextAttr attr;
5229 attr.SetFontUnderlined(true);
5230
5231 return BeginStyle(attr);
5232}
5233
5234/// Begin using point size
5235bool wxRichTextBuffer::BeginFontSize(int pointSize)
5236{
5237 wxTextAttr attr;
5238 attr.SetFontSize(pointSize);
5239
5240 return BeginStyle(attr);
5241}
5242
5243/// Begin using this font
5244bool wxRichTextBuffer::BeginFont(const wxFont& font)
5245{
5246 wxTextAttr attr;
5247 attr.SetFont(font);
5248
5249 return BeginStyle(attr);
5250}
5251
5252/// Begin using this colour
5253bool wxRichTextBuffer::BeginTextColour(const wxColour& colour)
5254{
5255 wxTextAttr attr;
5256 attr.SetFlags(wxTEXT_ATTR_TEXT_COLOUR);
5257 attr.SetTextColour(colour);
5258
5259 return BeginStyle(attr);
5260}
5261
5262/// Begin using alignment
5263bool wxRichTextBuffer::BeginAlignment(wxTextAttrAlignment alignment)
5264{
5265 wxTextAttr attr;
5266 attr.SetFlags(wxTEXT_ATTR_ALIGNMENT);
5267 attr.SetAlignment(alignment);
5268
5269 return BeginStyle(attr);
5270}
5271
5272/// Begin left indent
5273bool wxRichTextBuffer::BeginLeftIndent(int leftIndent, int leftSubIndent)
5274{
5275 wxTextAttr attr;
5276 attr.SetFlags(wxTEXT_ATTR_LEFT_INDENT);
5277 attr.SetLeftIndent(leftIndent, leftSubIndent);
5278
5279 return BeginStyle(attr);
5280}
5281
5282/// Begin right indent
5283bool wxRichTextBuffer::BeginRightIndent(int rightIndent)
5284{
5285 wxTextAttr attr;
5286 attr.SetFlags(wxTEXT_ATTR_RIGHT_INDENT);
5287 attr.SetRightIndent(rightIndent);
5288
5289 return BeginStyle(attr);
5290}
5291
5292/// Begin paragraph spacing
5293bool wxRichTextBuffer::BeginParagraphSpacing(int before, int after)
5294{
5295 long flags = 0;
5296 if (before != 0)
5297 flags |= wxTEXT_ATTR_PARA_SPACING_BEFORE;
5298 if (after != 0)
5299 flags |= wxTEXT_ATTR_PARA_SPACING_AFTER;
5300
5301 wxTextAttr attr;
5302 attr.SetFlags(flags);
5303 attr.SetParagraphSpacingBefore(before);
5304 attr.SetParagraphSpacingAfter(after);
5305
5306 return BeginStyle(attr);
5307}
5308
5309/// Begin line spacing
5310bool wxRichTextBuffer::BeginLineSpacing(int lineSpacing)
5311{
5312 wxTextAttr attr;
5313 attr.SetFlags(wxTEXT_ATTR_LINE_SPACING);
5314 attr.SetLineSpacing(lineSpacing);
5315
5316 return BeginStyle(attr);
5317}
5318
5319/// Begin numbered bullet
5320bool wxRichTextBuffer::BeginNumberedBullet(int bulletNumber, int leftIndent, int leftSubIndent, int bulletStyle)
5321{
5322 wxTextAttr attr;
5323 attr.SetFlags(wxTEXT_ATTR_BULLET_STYLE|wxTEXT_ATTR_LEFT_INDENT);
5324 attr.SetBulletStyle(bulletStyle);
5325 attr.SetBulletNumber(bulletNumber);
5326 attr.SetLeftIndent(leftIndent, leftSubIndent);
5327
5328 return BeginStyle(attr);
5329}
5330
5331/// Begin symbol bullet
5332bool wxRichTextBuffer::BeginSymbolBullet(const wxString& symbol, int leftIndent, int leftSubIndent, int bulletStyle)
5333{
5334 wxTextAttr attr;
5335 attr.SetFlags(wxTEXT_ATTR_BULLET_STYLE|wxTEXT_ATTR_LEFT_INDENT);
5336 attr.SetBulletStyle(bulletStyle);
5337 attr.SetLeftIndent(leftIndent, leftSubIndent);
5338 attr.SetBulletText(symbol);
5339
5340 return BeginStyle(attr);
5341}
5342
5343/// Begin standard bullet
5344bool wxRichTextBuffer::BeginStandardBullet(const wxString& bulletName, int leftIndent, int leftSubIndent, int bulletStyle)
5345{
5346 wxTextAttr attr;
5347 attr.SetFlags(wxTEXT_ATTR_BULLET_STYLE|wxTEXT_ATTR_LEFT_INDENT);
5348 attr.SetBulletStyle(bulletStyle);
5349 attr.SetLeftIndent(leftIndent, leftSubIndent);
5350 attr.SetBulletName(bulletName);
5351
5352 return BeginStyle(attr);
5353}
5354
5355/// Begin named character style
5356bool wxRichTextBuffer::BeginCharacterStyle(const wxString& characterStyle)
5357{
5358 if (GetStyleSheet())
5359 {
5360 wxRichTextCharacterStyleDefinition* def = GetStyleSheet()->FindCharacterStyle(characterStyle);
5361 if (def)
5362 {
5363 wxTextAttr attr = def->GetStyleMergedWithBase(GetStyleSheet());
5364 return BeginStyle(attr);
5365 }
5366 }
5367 return false;
5368}
5369
5370/// Begin named paragraph style
5371bool wxRichTextBuffer::BeginParagraphStyle(const wxString& paragraphStyle)
5372{
5373 if (GetStyleSheet())
5374 {
5375 wxRichTextParagraphStyleDefinition* def = GetStyleSheet()->FindParagraphStyle(paragraphStyle);
5376 if (def)
5377 {
5378 wxTextAttr attr = def->GetStyleMergedWithBase(GetStyleSheet());
5379 return BeginStyle(attr);
5380 }
5381 }
5382 return false;
5383}
5384
5385/// Begin named list style
5386bool wxRichTextBuffer::BeginListStyle(const wxString& listStyle, int level, int number)
5387{
5388 if (GetStyleSheet())
5389 {
5390 wxRichTextListStyleDefinition* def = GetStyleSheet()->FindListStyle(listStyle);
5391 if (def)
5392 {
5393 wxTextAttr attr(def->GetCombinedStyleForLevel(level));
5394
5395 attr.SetBulletNumber(number);
5396
5397 return BeginStyle(attr);
5398 }
5399 }
5400 return false;
5401}
5402
5403/// Begin URL
5404bool wxRichTextBuffer::BeginURL(const wxString& url, const wxString& characterStyle)
5405{
5406 wxTextAttr attr;
5407
5408 if (!characterStyle.IsEmpty() && GetStyleSheet())
5409 {
5410 wxRichTextCharacterStyleDefinition* def = GetStyleSheet()->FindCharacterStyle(characterStyle);
5411 if (def)
5412 {
5413 attr = def->GetStyleMergedWithBase(GetStyleSheet());
5414 }
5415 }
5416 attr.SetURL(url);
5417
5418 return BeginStyle(attr);
5419}
5420
5421/// Adds a handler to the end
5422void wxRichTextBuffer::AddHandler(wxRichTextFileHandler *handler)
5423{
5424 sm_handlers.Append(handler);
5425}
5426
5427/// Inserts a handler at the front
5428void wxRichTextBuffer::InsertHandler(wxRichTextFileHandler *handler)
5429{
5430 sm_handlers.Insert( handler );
5431}
5432
5433/// Removes a handler
5434bool wxRichTextBuffer::RemoveHandler(const wxString& name)
5435{
5436 wxRichTextFileHandler *handler = FindHandler(name);
5437 if (handler)
5438 {
5439 sm_handlers.DeleteObject(handler);
5440 delete handler;
5441 return true;
5442 }
5443 else
5444 return false;
5445}
5446
5447/// Finds a handler by filename or, if supplied, type
5448wxRichTextFileHandler *wxRichTextBuffer::FindHandlerFilenameOrType(const wxString& filename, int imageType)
5449{
5450 if (imageType != wxRICHTEXT_TYPE_ANY)
5451 return FindHandler(imageType);
5452 else if (!filename.IsEmpty())
5453 {
5454 wxString path, file, ext;
5455 wxSplitPath(filename, & path, & file, & ext);
5456 return FindHandler(ext, imageType);
5457 }
5458 else
5459 return NULL;
5460}
5461
5462
5463/// Finds a handler by name
5464wxRichTextFileHandler* wxRichTextBuffer::FindHandler(const wxString& name)
5465{
5466 wxList::compatibility_iterator node = sm_handlers.GetFirst();
5467 while (node)
5468 {
5469 wxRichTextFileHandler *handler = (wxRichTextFileHandler*)node->GetData();
5470 if (handler->GetName().Lower() == name.Lower()) return handler;
5471
5472 node = node->GetNext();
5473 }
5474 return NULL;
5475}
5476
5477/// Finds a handler by extension and type
5478wxRichTextFileHandler* wxRichTextBuffer::FindHandler(const wxString& extension, int type)
5479{
5480 wxList::compatibility_iterator node = sm_handlers.GetFirst();
5481 while (node)
5482 {
5483 wxRichTextFileHandler *handler = (wxRichTextFileHandler*)node->GetData();
5484 if ( handler->GetExtension().Lower() == extension.Lower() &&
5485 (type == wxRICHTEXT_TYPE_ANY || handler->GetType() == type) )
5486 return handler;
5487 node = node->GetNext();
5488 }
5489 return 0;
5490}
5491
5492/// Finds a handler by type
5493wxRichTextFileHandler* wxRichTextBuffer::FindHandler(int type)
5494{
5495 wxList::compatibility_iterator node = sm_handlers.GetFirst();
5496 while (node)
5497 {
5498 wxRichTextFileHandler *handler = (wxRichTextFileHandler *)node->GetData();
5499 if (handler->GetType() == type) return handler;
5500 node = node->GetNext();
5501 }
5502 return NULL;
5503}
5504
5505void wxRichTextBuffer::InitStandardHandlers()
5506{
5507 if (!FindHandler(wxRICHTEXT_TYPE_TEXT))
5508 AddHandler(new wxRichTextPlainTextHandler);
5509}
5510
5511void wxRichTextBuffer::CleanUpHandlers()
5512{
5513 wxList::compatibility_iterator node = sm_handlers.GetFirst();
5514 while (node)
5515 {
5516 wxRichTextFileHandler* handler = (wxRichTextFileHandler*)node->GetData();
5517 wxList::compatibility_iterator next = node->GetNext();
5518 delete handler;
5519 node = next;
5520 }
5521
5522 sm_handlers.Clear();
5523}
5524
5525wxString wxRichTextBuffer::GetExtWildcard(bool combine, bool save, wxArrayInt* types)
5526{
5527 if (types)
5528 types->Clear();
5529
5530 wxString wildcard;
5531
5532 wxList::compatibility_iterator node = GetHandlers().GetFirst();
5533 int count = 0;
5534 while (node)
5535 {
5536 wxRichTextFileHandler* handler = (wxRichTextFileHandler*) node->GetData();
5537 if (handler->IsVisible() && ((save && handler->CanSave()) || !save && handler->CanLoad()))
5538 {
5539 if (combine)
5540 {
5541 if (count > 0)
5542 wildcard += wxT(";");
5543 wildcard += wxT("*.") + handler->GetExtension();
5544 }
5545 else
5546 {
5547 if (count > 0)
5548 wildcard += wxT("|");
5549 wildcard += handler->GetName();
5550 wildcard += wxT(" ");
5551 wildcard += _("files");
5552 wildcard += wxT(" (*.");
5553 wildcard += handler->GetExtension();
5554 wildcard += wxT(")|*.");
5555 wildcard += handler->GetExtension();
5556 if (types)
5557 types->Add(handler->GetType());
5558 }
5559 count ++;
5560 }
5561
5562 node = node->GetNext();
5563 }
5564
5565 if (combine)
5566 wildcard = wxT("(") + wildcard + wxT(")|") + wildcard;
5567 return wildcard;
5568}
5569
5570/// Load a file
5571bool wxRichTextBuffer::LoadFile(const wxString& filename, int type)
5572{
5573 wxRichTextFileHandler* handler = FindHandlerFilenameOrType(filename, type);
5574 if (handler)
5575 {
5576 SetDefaultStyle(wxTextAttr());
5577 handler->SetFlags(GetHandlerFlags());
5578 bool success = handler->LoadFile(this, filename);
5579 Invalidate(wxRICHTEXT_ALL);
5580 return success;
5581 }
5582 else
5583 return false;
5584}
5585
5586/// Save a file
5587bool wxRichTextBuffer::SaveFile(const wxString& filename, int type)
5588{
5589 wxRichTextFileHandler* handler = FindHandlerFilenameOrType(filename, type);
5590 if (handler)
5591 {
5592 handler->SetFlags(GetHandlerFlags());
5593 return handler->SaveFile(this, filename);
5594 }
5595 else
5596 return false;
5597}
5598
5599/// Load from a stream
5600bool wxRichTextBuffer::LoadFile(wxInputStream& stream, int type)
5601{
5602 wxRichTextFileHandler* handler = FindHandler(type);
5603 if (handler)
5604 {
5605 SetDefaultStyle(wxTextAttr());
5606 handler->SetFlags(GetHandlerFlags());
5607 bool success = handler->LoadFile(this, stream);
5608 Invalidate(wxRICHTEXT_ALL);
5609 return success;
5610 }
5611 else
5612 return false;
5613}
5614
5615/// Save to a stream
5616bool wxRichTextBuffer::SaveFile(wxOutputStream& stream, int type)
5617{
5618 wxRichTextFileHandler* handler = FindHandler(type);
5619 if (handler)
5620 {
5621 handler->SetFlags(GetHandlerFlags());
5622 return handler->SaveFile(this, stream);
5623 }
5624 else
5625 return false;
5626}
5627
5628/// Copy the range to the clipboard
5629bool wxRichTextBuffer::CopyToClipboard(const wxRichTextRange& range)
5630{
5631 bool success = false;
5632#if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5633
5634 if (!wxTheClipboard->IsOpened() && wxTheClipboard->Open())
5635 {
5636 wxTheClipboard->Clear();
5637
5638 // Add composite object
5639
5640 wxDataObjectComposite* compositeObject = new wxDataObjectComposite();
5641
5642 {
5643 wxString text = GetTextForRange(range);
5644
5645#ifdef __WXMSW__
5646 text = wxTextFile::Translate(text, wxTextFileType_Dos);
5647#endif
5648
5649 compositeObject->Add(new wxTextDataObject(text), false /* not preferred */);
5650 }
5651
5652 // Add rich text buffer data object. This needs the XML handler to be present.
5653
5654 if (FindHandler(wxRICHTEXT_TYPE_XML))
5655 {
5656 wxRichTextBuffer* richTextBuf = new wxRichTextBuffer;
5657 CopyFragment(range, *richTextBuf);
5658
5659 compositeObject->Add(new wxRichTextBufferDataObject(richTextBuf), true /* preferred */);
5660 }
5661
5662 if (wxTheClipboard->SetData(compositeObject))
5663 success = true;
5664
5665 wxTheClipboard->Close();
5666 }
5667
5668#else
5669 wxUnusedVar(range);
5670#endif
5671 return success;
5672}
5673
5674/// Paste the clipboard content to the buffer
5675bool wxRichTextBuffer::PasteFromClipboard(long position)
5676{
5677 bool success = false;
5678#if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5679 if (CanPasteFromClipboard())
5680 {
5681 if (wxTheClipboard->Open())
5682 {
5683 if (wxTheClipboard->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())))
5684 {
5685 wxRichTextBufferDataObject data;
5686 wxTheClipboard->GetData(data);
5687 wxRichTextBuffer* richTextBuffer = data.GetRichTextBuffer();
5688 if (richTextBuffer)
5689 {
5690 InsertParagraphsWithUndo(position+1, *richTextBuffer, GetRichTextCtrl(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE);
5691 delete richTextBuffer;
5692 }
5693 }
5694 else if (wxTheClipboard->IsSupported(wxDF_TEXT) || wxTheClipboard->IsSupported(wxDF_UNICODETEXT))
5695 {
5696 wxTextDataObject data;
5697 wxTheClipboard->GetData(data);
5698 wxString text(data.GetText());
5699#ifdef __WXMSW__
5700 wxString text2;
5701 text2.Alloc(text.Length()+1);
5702 size_t i;
5703 for (i = 0; i < text.Length(); i++)
5704 {
5705 wxChar ch = text[i];
5706 if (ch != wxT('\r'))
5707 text2 += ch;
5708 }
5709#else
5710 wxString text2 = text;
5711#endif
5712 InsertTextWithUndo(position+1, text2, GetRichTextCtrl());
5713
5714 success = true;
5715 }
5716 else if (wxTheClipboard->IsSupported(wxDF_BITMAP))
5717 {
5718 wxBitmapDataObject data;
5719 wxTheClipboard->GetData(data);
5720 wxBitmap bitmap(data.GetBitmap());
5721 wxImage image(bitmap.ConvertToImage());
5722
5723 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Image"), wxRICHTEXT_INSERT, this, GetRichTextCtrl(), false);
5724
5725 action->GetNewParagraphs().AddImage(image);
5726
5727 if (action->GetNewParagraphs().GetChildCount() == 1)
5728 action->GetNewParagraphs().SetPartialParagraph(true);
5729
5730 action->SetPosition(position);
5731
5732 // Set the range we'll need to delete in Undo
5733 action->SetRange(wxRichTextRange(position, position));
5734
5735 SubmitAction(action);
5736
5737 success = true;
5738 }
5739 wxTheClipboard->Close();
5740 }
5741 }
5742#else
5743 wxUnusedVar(position);
5744#endif
5745 return success;
5746}
5747
5748/// Can we paste from the clipboard?
5749bool wxRichTextBuffer::CanPasteFromClipboard() const
5750{
5751 bool canPaste = false;
5752#if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
5753 if (!wxTheClipboard->IsOpened() && wxTheClipboard->Open())
5754 {
5755 if (wxTheClipboard->IsSupported(wxDF_TEXT) || wxTheClipboard->IsSupported(wxDF_UNICODETEXT) ||
5756 wxTheClipboard->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())) ||
5757 wxTheClipboard->IsSupported(wxDF_BITMAP))
5758 {
5759 canPaste = true;
5760 }
5761 wxTheClipboard->Close();
5762 }
5763#endif
5764 return canPaste;
5765}
5766
5767/// Dumps contents of buffer for debugging purposes
5768void wxRichTextBuffer::Dump()
5769{
5770 wxString text;
5771 {
5772 wxStringOutputStream stream(& text);
5773 wxTextOutputStream textStream(stream);
5774 Dump(textStream);
5775 }
5776
5777 wxLogDebug(text);
5778}
5779
5780/// Add an event handler
5781bool wxRichTextBuffer::AddEventHandler(wxEvtHandler* handler)
5782{
5783 m_eventHandlers.Append(handler);
5784 return true;
5785}
5786
5787/// Remove an event handler
5788bool wxRichTextBuffer::RemoveEventHandler(wxEvtHandler* handler, bool deleteHandler)
5789{
5790 wxList::compatibility_iterator node = m_eventHandlers.Find(handler);
5791 if (node)
5792 {
5793 m_eventHandlers.Erase(node);
5794 if (deleteHandler)
5795 delete handler;
5796
5797 return true;
5798 }
5799 else
5800 return false;
5801}
5802
5803/// Clear event handlers
5804void wxRichTextBuffer::ClearEventHandlers()
5805{
5806 m_eventHandlers.Clear();
5807}
5808
5809/// Send event to event handlers. If sendToAll is true, will send to all event handlers,
5810/// otherwise will stop at the first successful one.
5811bool wxRichTextBuffer::SendEvent(wxEvent& event, bool sendToAll)
5812{
5813 bool success = false;
5814 for (wxList::compatibility_iterator node = m_eventHandlers.GetFirst(); node; node = node->GetNext())
5815 {
5816 wxEvtHandler* handler = (wxEvtHandler*) node->GetData();
5817 if (handler->ProcessEvent(event))
5818 {
5819 success = true;
5820 if (!sendToAll)
5821 return true;
5822 }
5823 }
5824 return success;
5825}
5826
5827/// Set style sheet and notify of the change
5828bool wxRichTextBuffer::SetStyleSheetAndNotify(wxRichTextStyleSheet* sheet)
5829{
5830 wxRichTextStyleSheet* oldSheet = GetStyleSheet();
5831
5832 wxWindowID id = wxID_ANY;
5833 if (GetRichTextCtrl())
5834 id = GetRichTextCtrl()->GetId();
5835
5836 wxRichTextEvent event(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING, id);
5837 event.SetEventObject(GetRichTextCtrl());
5838 event.SetOldStyleSheet(oldSheet);
5839 event.SetNewStyleSheet(sheet);
5840 event.Allow();
5841
5842 if (SendEvent(event) && !event.IsAllowed())
5843 {
5844 if (sheet != oldSheet)
5845 delete sheet;
5846
5847 return false;
5848 }
5849
5850 if (oldSheet && oldSheet != sheet)
5851 delete oldSheet;
5852
5853 SetStyleSheet(sheet);
5854
5855 event.SetEventType(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED);
5856 event.SetOldStyleSheet(NULL);
5857 event.Allow();
5858
5859 return SendEvent(event);
5860}
5861
5862/// Set renderer, deleting old one
5863void wxRichTextBuffer::SetRenderer(wxRichTextRenderer* renderer)
5864{
5865 if (sm_renderer)
5866 delete sm_renderer;
5867 sm_renderer = renderer;
5868}
5869
5870bool wxRichTextStdRenderer::DrawStandardBullet(wxRichTextParagraph* paragraph, wxDC& dc, const wxTextAttr& bulletAttr, const wxRect& rect)
5871{
5872 if (bulletAttr.GetTextColour().Ok())
5873 {
5874 wxCheckSetPen(dc, wxPen(bulletAttr.GetTextColour()));
5875 wxCheckSetBrush(dc, wxBrush(bulletAttr.GetTextColour()));
5876 }
5877 else
5878 {
5879 wxCheckSetPen(dc, *wxBLACK_PEN);
5880 wxCheckSetBrush(dc, *wxBLACK_BRUSH);
5881 }
5882
5883 wxFont font;
5884 if (bulletAttr.HasFont())
5885 {
5886 font = paragraph->GetBuffer()->GetFontTable().FindFont(bulletAttr);
5887 }
5888 else
5889 font = (*wxNORMAL_FONT);
5890
5891 wxCheckSetFont(dc, font);
5892
5893 int charHeight = dc.GetCharHeight();
5894
5895 int bulletWidth = (int) (((float) charHeight) * wxRichTextBuffer::GetBulletProportion());
5896 int bulletHeight = bulletWidth;
5897
5898 int x = rect.x;
5899
5900 // Calculate the top position of the character (as opposed to the whole line height)
5901 int y = rect.y + (rect.height - charHeight);
5902
5903 // Calculate where the bullet should be positioned
5904 y = y + (charHeight+1)/2 - (bulletHeight+1)/2;
5905
5906 // The margin between a bullet and text.
5907 int margin = paragraph->ConvertTenthsMMToPixels(dc, wxRichTextBuffer::GetBulletRightMargin());
5908
5909 if (bulletAttr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT)
5910 x = rect.x + rect.width - bulletWidth - margin;
5911 else if (bulletAttr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE)
5912 x = x + (rect.width)/2 - bulletWidth/2;
5913
5914 if (bulletAttr.GetBulletName() == wxT("standard/square"))
5915 {
5916 dc.DrawRectangle(x, y, bulletWidth, bulletHeight);
5917 }
5918 else if (bulletAttr.GetBulletName() == wxT("standard/diamond"))
5919 {
5920 wxPoint pts[5];
5921 pts[0].x = x; pts[0].y = y + bulletHeight/2;
5922 pts[1].x = x + bulletWidth/2; pts[1].y = y;
5923 pts[2].x = x + bulletWidth; pts[2].y = y + bulletHeight/2;
5924 pts[3].x = x + bulletWidth/2; pts[3].y = y + bulletHeight;
5925
5926 dc.DrawPolygon(4, pts);
5927 }
5928 else if (bulletAttr.GetBulletName() == wxT("standard/triangle"))
5929 {
5930 wxPoint pts[3];
5931 pts[0].x = x; pts[0].y = y;
5932 pts[1].x = x + bulletWidth; pts[1].y = y + bulletHeight/2;
5933 pts[2].x = x; pts[2].y = y + bulletHeight;
5934
5935 dc.DrawPolygon(3, pts);
5936 }
5937 else // "standard/circle", and catch-all
5938 {
5939 dc.DrawEllipse(x, y, bulletWidth, bulletHeight);
5940 }
5941
5942 return true;
5943}
5944
5945bool wxRichTextStdRenderer::DrawTextBullet(wxRichTextParagraph* paragraph, wxDC& dc, const wxTextAttr& attr, const wxRect& rect, const wxString& text)
5946{
5947 if (!text.empty())
5948 {
5949 wxFont font;
5950 if ((attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL) && !attr.GetBulletFont().IsEmpty() && attr.HasFont())
5951 {
5952 wxTextAttr fontAttr;
5953 fontAttr.SetFontSize(attr.GetFontSize());
5954 fontAttr.SetFontStyle(attr.GetFontStyle());
5955 fontAttr.SetFontWeight(attr.GetFontWeight());
5956 fontAttr.SetFontUnderlined(attr.GetFontUnderlined());
5957 fontAttr.SetFontFaceName(attr.GetBulletFont());
5958 font = paragraph->GetBuffer()->GetFontTable().FindFont(fontAttr);
5959 }
5960 else if (attr.HasFont())
5961 font = paragraph->GetBuffer()->GetFontTable().FindFont(attr);
5962 else
5963 font = (*wxNORMAL_FONT);
5964
5965 wxCheckSetFont(dc, font);
5966
5967 if (attr.GetTextColour().Ok())
5968 dc.SetTextForeground(attr.GetTextColour());
5969
5970 dc.SetBackgroundMode(wxTRANSPARENT);
5971
5972 int charHeight = dc.GetCharHeight();
5973 wxCoord tw, th;
5974 dc.GetTextExtent(text, & tw, & th);
5975
5976 int x = rect.x;
5977
5978 // Calculate the top position of the character (as opposed to the whole line height)
5979 int y = rect.y + (rect.height - charHeight);
5980
5981 // The margin between a bullet and text.
5982 int margin = paragraph->ConvertTenthsMMToPixels(dc, wxRichTextBuffer::GetBulletRightMargin());
5983
5984 if (attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT)
5985 x = (rect.x + rect.width) - tw - margin;
5986 else if (attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE)
5987 x = x + (rect.width)/2 - tw/2;
5988
5989 dc.DrawText(text, x, y);
5990
5991 return true;
5992 }
5993 else
5994 return false;
5995}
5996
5997bool wxRichTextStdRenderer::DrawBitmapBullet(wxRichTextParagraph* WXUNUSED(paragraph), wxDC& WXUNUSED(dc), const wxTextAttr& WXUNUSED(attr), const wxRect& WXUNUSED(rect))
5998{
5999 // Currently unimplemented. The intention is to store bitmaps by name in a media store associated
6000 // with the buffer. The store will allow retrieval from memory, disk or other means.
6001 return false;
6002}
6003
6004/// Enumerate the standard bullet names currently supported
6005bool wxRichTextStdRenderer::EnumerateStandardBulletNames(wxArrayString& bulletNames)
6006{
6007 bulletNames.Add(wxT("standard/circle"));
6008 bulletNames.Add(wxT("standard/square"));
6009 bulletNames.Add(wxT("standard/diamond"));
6010 bulletNames.Add(wxT("standard/triangle"));
6011
6012 return true;
6013}
6014
6015/*
6016 * Module to initialise and clean up handlers
6017 */
6018
6019class wxRichTextModule: public wxModule
6020{
6021DECLARE_DYNAMIC_CLASS(wxRichTextModule)
6022public:
6023 wxRichTextModule() {}
6024 bool OnInit()
6025 {
6026 wxRichTextBuffer::SetRenderer(new wxRichTextStdRenderer);
6027 wxRichTextBuffer::InitStandardHandlers();
6028 wxRichTextParagraph::InitDefaultTabs();
6029 return true;
6030 }
6031 void OnExit()
6032 {
6033 wxRichTextBuffer::CleanUpHandlers();
6034 wxRichTextDecimalToRoman(-1);
6035 wxRichTextParagraph::ClearDefaultTabs();
6036 wxRichTextCtrl::ClearAvailableFontNames();
6037 wxRichTextBuffer::SetRenderer(NULL);
6038 }
6039};
6040
6041IMPLEMENT_DYNAMIC_CLASS(wxRichTextModule, wxModule)
6042
6043
6044// If the richtext lib is dynamically loaded after the app has already started
6045// (such as from wxPython) then the built-in module system will not init this
6046// module. Provide this function to do it manually.
6047void wxRichTextModuleInit()
6048{
6049 wxModule* module = new wxRichTextModule;
6050 module->Init();
6051 wxModule::RegisterModule(module);
6052}
6053
6054
6055/*!
6056 * Commands for undo/redo
6057 *
6058 */
6059
6060wxRichTextCommand::wxRichTextCommand(const wxString& name, wxRichTextCommandId id, wxRichTextBuffer* buffer,
6061 wxRichTextCtrl* ctrl, bool ignoreFirstTime): wxCommand(true, name)
6062{
6063 /* wxRichTextAction* action = */ new wxRichTextAction(this, name, id, buffer, ctrl, ignoreFirstTime);
6064}
6065
6066wxRichTextCommand::wxRichTextCommand(const wxString& name): wxCommand(true, name)
6067{
6068}
6069
6070wxRichTextCommand::~wxRichTextCommand()
6071{
6072 ClearActions();
6073}
6074
6075void wxRichTextCommand::AddAction(wxRichTextAction* action)
6076{
6077 if (!m_actions.Member(action))
6078 m_actions.Append(action);
6079}
6080
6081bool wxRichTextCommand::Do()
6082{
6083 for (wxList::compatibility_iterator node = m_actions.GetFirst(); node; node = node->GetNext())
6084 {
6085 wxRichTextAction* action = (wxRichTextAction*) node->GetData();
6086 action->Do();
6087 }
6088
6089 return true;
6090}
6091
6092bool wxRichTextCommand::Undo()
6093{
6094 for (wxList::compatibility_iterator node = m_actions.GetLast(); node; node = node->GetPrevious())
6095 {
6096 wxRichTextAction* action = (wxRichTextAction*) node->GetData();
6097 action->Undo();
6098 }
6099
6100 return true;
6101}
6102
6103void wxRichTextCommand::ClearActions()
6104{
6105 WX_CLEAR_LIST(wxList, m_actions);
6106}
6107
6108/*!
6109 * Individual action
6110 *
6111 */
6112
6113wxRichTextAction::wxRichTextAction(wxRichTextCommand* cmd, const wxString& name, wxRichTextCommandId id, wxRichTextBuffer* buffer,
6114 wxRichTextCtrl* ctrl, bool ignoreFirstTime)
6115{
6116 m_buffer = buffer;
6117 m_ignoreThis = ignoreFirstTime;
6118 m_cmdId = id;
6119 m_position = -1;
6120 m_ctrl = ctrl;
6121 m_name = name;
6122 m_newParagraphs.SetDefaultStyle(buffer->GetDefaultStyle());
6123 m_newParagraphs.SetBasicStyle(buffer->GetBasicStyle());
6124 if (cmd)
6125 cmd->AddAction(this);
6126}
6127
6128wxRichTextAction::~wxRichTextAction()
6129{
6130}
6131
6132bool wxRichTextAction::Do()
6133{
6134 m_buffer->Modify(true);
6135
6136 switch (m_cmdId)
6137 {
6138 case wxRICHTEXT_INSERT:
6139 {
6140 // Store a list of line start character and y positions so we can figure out which area
6141 // we need to refresh
6142 wxArrayInt optimizationLineCharPositions;
6143 wxArrayInt optimizationLineYPositions;
6144
6145#if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6146 // NOTE: we're assuming that the buffer is laid out correctly at this point.
6147 // If we had several actions, which only invalidate and leave layout until the
6148 // paint handler is called, then this might not be true. So we may need to switch
6149 // optimisation on only when we're simply adding text and not simultaneously
6150 // deleting a selection, for example. Or, we make sure the buffer is laid out correctly
6151 // first, but of course this means we'll be doing it twice.
6152 if (!m_buffer->GetDirty() && m_ctrl) // can only do optimisation if the buffer is already laid out correctly
6153 {
6154 wxSize clientSize = m_ctrl->GetClientSize();
6155 wxPoint firstVisiblePt = m_ctrl->GetFirstVisiblePoint();
6156 int lastY = firstVisiblePt.y + clientSize.y;
6157
6158 wxRichTextParagraph* para = m_buffer->GetParagraphAtPosition(GetRange().GetStart());
6159 wxRichTextObjectList::compatibility_iterator node = m_buffer->GetChildren().Find(para);
6160 while (node)
6161 {
6162 wxRichTextParagraph* child = (wxRichTextParagraph*) node->GetData();
6163 wxRichTextLineList::compatibility_iterator node2 = child->GetLines().GetFirst();
6164 while (node2)
6165 {
6166 wxRichTextLine* line = node2->GetData();
6167 wxPoint pt = line->GetAbsolutePosition();
6168 wxRichTextRange range = line->GetAbsoluteRange();
6169
6170 if (pt.y > lastY)
6171 {
6172 node2 = wxRichTextLineList::compatibility_iterator();
6173 node = wxRichTextObjectList::compatibility_iterator();
6174 }
6175 else if (range.GetStart() > GetPosition() && pt.y >= firstVisiblePt.y)
6176 {
6177 optimizationLineCharPositions.Add(range.GetStart());
6178 optimizationLineYPositions.Add(pt.y);
6179 }
6180
6181 if (node2)
6182 node2 = node2->GetNext();
6183 }
6184
6185 if (node)
6186 node = node->GetNext();
6187 }
6188 }
6189#endif
6190
6191 m_buffer->InsertFragment(GetRange().GetStart(), m_newParagraphs);
6192 m_buffer->UpdateRanges();
6193 m_buffer->Invalidate(wxRichTextRange(GetRange().GetStart()-1, GetRange().GetEnd()));
6194
6195 long newCaretPosition = GetPosition() + m_newParagraphs.GetRange().GetLength();
6196
6197 // Character position to caret position
6198 newCaretPosition --;
6199
6200 // Don't take into account the last newline
6201 if (m_newParagraphs.GetPartialParagraph())
6202 newCaretPosition --;
6203 else
6204 if (m_newParagraphs.GetChildren().GetCount() > 1)
6205 {
6206 wxRichTextObject* p = (wxRichTextObject*) m_newParagraphs.GetChildren().GetLast()->GetData();
6207 if (p->GetRange().GetLength() == 1)
6208 newCaretPosition --;
6209 }
6210
6211 newCaretPosition = wxMin(newCaretPosition, (m_buffer->GetRange().GetEnd()-1));
6212
6213 if (optimizationLineCharPositions.GetCount() > 0)
6214 UpdateAppearance(newCaretPosition, true /* send update event */, & optimizationLineCharPositions, & optimizationLineYPositions);
6215 else
6216 UpdateAppearance(newCaretPosition, true /* send update event */);
6217
6218 wxRichTextEvent cmdEvent(
6219 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED,
6220 m_ctrl ? m_ctrl->GetId() : -1);
6221 cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
6222 cmdEvent.SetRange(GetRange());
6223 cmdEvent.SetPosition(GetRange().GetStart());
6224
6225 m_buffer->SendEvent(cmdEvent);
6226
6227 break;
6228 }
6229 case wxRICHTEXT_DELETE:
6230 {
6231 m_buffer->DeleteRange(GetRange());
6232 m_buffer->UpdateRanges();
6233 m_buffer->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6234
6235 UpdateAppearance(GetRange().GetStart()-1, true /* send update event */);
6236
6237 wxRichTextEvent cmdEvent(
6238 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED,
6239 m_ctrl ? m_ctrl->GetId() : -1);
6240 cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
6241 cmdEvent.SetRange(GetRange());
6242 cmdEvent.SetPosition(GetRange().GetStart());
6243
6244 m_buffer->SendEvent(cmdEvent);
6245
6246 break;
6247 }
6248 case wxRICHTEXT_CHANGE_STYLE:
6249 {
6250 ApplyParagraphs(GetNewParagraphs());
6251 m_buffer->Invalidate(GetRange());
6252
6253 UpdateAppearance(GetPosition());
6254
6255 wxRichTextEvent cmdEvent(
6256 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED,
6257 m_ctrl ? m_ctrl->GetId() : -1);
6258 cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
6259 cmdEvent.SetRange(GetRange());
6260 cmdEvent.SetPosition(GetRange().GetStart());
6261
6262 m_buffer->SendEvent(cmdEvent);
6263
6264 break;
6265 }
6266 default:
6267 break;
6268 }
6269
6270 return true;
6271}
6272
6273bool wxRichTextAction::Undo()
6274{
6275 m_buffer->Modify(true);
6276
6277 switch (m_cmdId)
6278 {
6279 case wxRICHTEXT_INSERT:
6280 {
6281 m_buffer->DeleteRange(GetRange());
6282 m_buffer->UpdateRanges();
6283 m_buffer->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6284
6285 long newCaretPosition = GetPosition() - 1;
6286
6287 UpdateAppearance(newCaretPosition, true /* send update event */);
6288
6289 wxRichTextEvent cmdEvent(
6290 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED,
6291 m_ctrl ? m_ctrl->GetId() : -1);
6292 cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
6293 cmdEvent.SetRange(GetRange());
6294 cmdEvent.SetPosition(GetRange().GetStart());
6295
6296 m_buffer->SendEvent(cmdEvent);
6297
6298 break;
6299 }
6300 case wxRICHTEXT_DELETE:
6301 {
6302 m_buffer->InsertFragment(GetRange().GetStart(), m_oldParagraphs);
6303 m_buffer->UpdateRanges();
6304 m_buffer->Invalidate(GetRange());
6305
6306 UpdateAppearance(GetPosition(), true /* send update event */);
6307
6308 wxRichTextEvent cmdEvent(
6309 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED,
6310 m_ctrl ? m_ctrl->GetId() : -1);
6311 cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
6312 cmdEvent.SetRange(GetRange());
6313 cmdEvent.SetPosition(GetRange().GetStart());
6314
6315 m_buffer->SendEvent(cmdEvent);
6316
6317 break;
6318 }
6319 case wxRICHTEXT_CHANGE_STYLE:
6320 {
6321 ApplyParagraphs(GetOldParagraphs());
6322 m_buffer->Invalidate(GetRange());
6323
6324 UpdateAppearance(GetPosition());
6325
6326 wxRichTextEvent cmdEvent(
6327 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED,
6328 m_ctrl ? m_ctrl->GetId() : -1);
6329 cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
6330 cmdEvent.SetRange(GetRange());
6331 cmdEvent.SetPosition(GetRange().GetStart());
6332
6333 m_buffer->SendEvent(cmdEvent);
6334
6335 break;
6336 }
6337 default:
6338 break;
6339 }
6340
6341 return true;
6342}
6343
6344/// Update the control appearance
6345void wxRichTextAction::UpdateAppearance(long caretPosition, bool sendUpdateEvent, wxArrayInt* optimizationLineCharPositions, wxArrayInt* optimizationLineYPositions)
6346{
6347 if (m_ctrl)
6348 {
6349 m_ctrl->SetCaretPosition(caretPosition);
6350 if (!m_ctrl->IsFrozen())
6351 {
6352 m_ctrl->LayoutContent();
6353 m_ctrl->PositionCaret();
6354
6355#if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6356 // Find refresh rectangle if we are in a position to optimise refresh
6357 if (m_cmdId == wxRICHTEXT_INSERT && optimizationLineCharPositions && optimizationLineCharPositions->GetCount() > 0)
6358 {
6359 size_t i;
6360
6361 wxSize clientSize = m_ctrl->GetClientSize();
6362 wxPoint firstVisiblePt = m_ctrl->GetFirstVisiblePoint();
6363
6364 // Start/end positions
6365 int firstY = 0;
6366 int lastY = firstVisiblePt.y + clientSize.y;
6367
6368 bool foundStart = false;
6369 bool foundEnd = false;
6370
6371 // position offset - how many characters were inserted
6372 int positionOffset = GetRange().GetLength();
6373
6374 // find the first line which is being drawn at the same position as it was
6375 // before. Since we're talking about a simple insertion, we can assume
6376 // that the rest of the window does not need to be redrawn.
6377
6378 wxRichTextParagraph* para = m_buffer->GetParagraphAtPosition(GetPosition());
6379 wxRichTextObjectList::compatibility_iterator node = m_buffer->GetChildren().Find(para);
6380 while (node)
6381 {
6382 wxRichTextParagraph* child = (wxRichTextParagraph*) node->GetData();
6383 wxRichTextLineList::compatibility_iterator node2 = child->GetLines().GetFirst();
6384 while (node2)
6385 {
6386 wxRichTextLine* line = node2->GetData();
6387 wxPoint pt = line->GetAbsolutePosition();
6388 wxRichTextRange range = line->GetAbsoluteRange();
6389
6390 // we want to find the first line that is in the same position
6391 // as before. This will mean we're at the end of the changed text.
6392
6393 if (pt.y > lastY) // going past the end of the window, no more info
6394 {
6395 node2 = wxRichTextLineList::compatibility_iterator();
6396 node = wxRichTextObjectList::compatibility_iterator();
6397 }
6398 else
6399 {
6400 if (!foundStart)
6401 {
6402 firstY = pt.y - firstVisiblePt.y;
6403 foundStart = true;
6404 }
6405
6406 // search for this line being at the same position as before
6407 for (i = 0; i < optimizationLineCharPositions->GetCount(); i++)
6408 {
6409 if (((*optimizationLineCharPositions)[i] + positionOffset == range.GetStart()) &&
6410 ((*optimizationLineYPositions)[i] == pt.y))
6411 {
6412 // Stop, we're now the same as we were
6413 foundEnd = true;
6414 lastY = pt.y - firstVisiblePt.y;
6415
6416 node2 = wxRichTextLineList::compatibility_iterator();
6417 node = wxRichTextObjectList::compatibility_iterator();
6418
6419 break;
6420 }
6421 }
6422 }
6423
6424 if (node2)
6425 node2 = node2->GetNext();
6426 }
6427
6428 if (node)
6429 node = node->GetNext();
6430 }
6431
6432 if (!foundStart)
6433 firstY = firstVisiblePt.y;
6434 if (!foundEnd)
6435 lastY = firstVisiblePt.y + clientSize.y;
6436
6437 wxRect rect(firstVisiblePt.x, firstY, firstVisiblePt.x + clientSize.x, lastY - firstY);
6438 m_ctrl->RefreshRect(rect);
6439
6440 // TODO: we need to make sure that lines are only drawn if in the update region. The rect
6441 // passed to Draw is currently used in different ways (to pass the position the content should
6442 // be drawn at as well as the relevant region).
6443 }
6444 else
6445#endif
6446 m_ctrl->Refresh(false);
6447
6448 if (sendUpdateEvent)
6449 wxTextCtrl::SendTextUpdatedEvent(m_ctrl);
6450 }
6451 }
6452}
6453
6454/// Replace the buffer paragraphs with the new ones.
6455void wxRichTextAction::ApplyParagraphs(const wxRichTextParagraphLayoutBox& fragment)
6456{
6457 wxRichTextObjectList::compatibility_iterator node = fragment.GetChildren().GetFirst();
6458 while (node)
6459 {
6460 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
6461 wxASSERT (para != NULL);
6462
6463 // We'll replace the existing paragraph by finding the paragraph at this position,
6464 // delete its node data, and setting a copy as the new node data.
6465 // TODO: make more efficient by simply swapping old and new paragraph objects.
6466
6467 wxRichTextParagraph* existingPara = m_buffer->GetParagraphAtPosition(para->GetRange().GetStart());
6468 if (existingPara)
6469 {
6470 wxRichTextObjectList::compatibility_iterator bufferParaNode = m_buffer->GetChildren().Find(existingPara);
6471 if (bufferParaNode)
6472 {
6473 wxRichTextParagraph* newPara = new wxRichTextParagraph(*para);
6474 newPara->SetParent(m_buffer);
6475
6476 bufferParaNode->SetData(newPara);
6477
6478 delete existingPara;
6479 }
6480 }
6481
6482 node = node->GetNext();
6483 }
6484}
6485
6486
6487/*!
6488 * wxRichTextRange
6489 * This stores beginning and end positions for a range of data.
6490 */
6491
6492/// Limit this range to be within 'range'
6493bool wxRichTextRange::LimitTo(const wxRichTextRange& range)
6494{
6495 if (m_start < range.m_start)
6496 m_start = range.m_start;
6497
6498 if (m_end > range.m_end)
6499 m_end = range.m_end;
6500
6501 return true;
6502}
6503
6504/*!
6505 * wxRichTextImage implementation
6506 * This object represents an image.
6507 */
6508
6509IMPLEMENT_DYNAMIC_CLASS(wxRichTextImage, wxRichTextObject)
6510
6511wxRichTextImage::wxRichTextImage(const wxImage& image, wxRichTextObject* parent, wxTextAttr* charStyle):
6512 wxRichTextObject(parent)
6513{
6514 m_image = image;
6515 if (charStyle)
6516 SetAttributes(*charStyle);
6517}
6518
6519wxRichTextImage::wxRichTextImage(const wxRichTextImageBlock& imageBlock, wxRichTextObject* parent, wxTextAttr* charStyle):
6520 wxRichTextObject(parent)
6521{
6522 m_imageBlock = imageBlock;
6523 m_imageBlock.Load(m_image);
6524 if (charStyle)
6525 SetAttributes(*charStyle);
6526}
6527
6528/// Load wxImage from the block
6529bool wxRichTextImage::LoadFromBlock()
6530{
6531 m_imageBlock.Load(m_image);
6532 return m_imageBlock.Ok();
6533}
6534
6535/// Make block from the wxImage
6536bool wxRichTextImage::MakeBlock()
6537{
6538 if (m_imageBlock.GetImageType() == wxBITMAP_TYPE_ANY || m_imageBlock.GetImageType() == -1)
6539 m_imageBlock.SetImageType(wxBITMAP_TYPE_PNG);
6540
6541 m_imageBlock.MakeImageBlock(m_image, m_imageBlock.GetImageType());
6542 return m_imageBlock.Ok();
6543}
6544
6545
6546/// Draw the item
6547bool wxRichTextImage::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextRange& selectionRange, const wxRect& rect, int WXUNUSED(descent), int WXUNUSED(style))
6548{
6549 if (!m_image.Ok() && m_imageBlock.Ok())
6550 LoadFromBlock();
6551
6552 if (!m_image.Ok())
6553 return false;
6554
6555 if (m_image.Ok() && !m_bitmap.Ok())
6556 m_bitmap = wxBitmap(m_image);
6557
6558 int y = rect.y + (rect.height - m_image.GetHeight());
6559
6560 if (m_bitmap.Ok())
6561 dc.DrawBitmap(m_bitmap, rect.x, y, true);
6562
6563 if (selectionRange.Contains(range.GetStart()))
6564 {
6565 wxCheckSetBrush(dc, *wxBLACK_BRUSH);
6566 wxCheckSetPen(dc, *wxBLACK_PEN);
6567 dc.SetLogicalFunction(wxINVERT);
6568 dc.DrawRectangle(rect);
6569 dc.SetLogicalFunction(wxCOPY);
6570 }
6571
6572 return true;
6573}
6574
6575/// Lay the item out
6576bool wxRichTextImage::Layout(wxDC& WXUNUSED(dc), const wxRect& rect, int WXUNUSED(style))
6577{
6578 if (!m_image.Ok())
6579 LoadFromBlock();
6580
6581 if (m_image.Ok())
6582 {
6583 SetCachedSize(wxSize(m_image.GetWidth(), m_image.GetHeight()));
6584 SetPosition(rect.GetPosition());
6585 }
6586
6587 return true;
6588}
6589
6590/// Get/set the object size for the given range. Returns false if the range
6591/// is invalid for this object.
6592bool wxRichTextImage::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& WXUNUSED(descent), wxDC& WXUNUSED(dc), int WXUNUSED(flags), wxPoint WXUNUSED(position)) const
6593{
6594 if (!range.IsWithin(GetRange()))
6595 return false;
6596
6597 if (!m_image.Ok())
6598 return false;
6599
6600 size.x = m_image.GetWidth();
6601 size.y = m_image.GetHeight();
6602
6603 return true;
6604}
6605
6606/// Copy
6607void wxRichTextImage::Copy(const wxRichTextImage& obj)
6608{
6609 wxRichTextObject::Copy(obj);
6610
6611 m_image = obj.m_image;
6612 m_imageBlock = obj.m_imageBlock;
6613}
6614
6615/*!
6616 * Utilities
6617 *
6618 */
6619
6620/// Compare two attribute objects
6621bool wxTextAttrEq(const wxTextAttr& attr1, const wxTextAttr& attr2)
6622{
6623 return (attr1 == attr2);
6624}
6625
6626// Partial equality test taking flags into account
6627bool wxTextAttrEqPartial(const wxTextAttr& attr1, const wxTextAttr& attr2, int flags)
6628{
6629 return attr1.EqPartial(attr2, flags);
6630}
6631
6632/// Compare tabs
6633bool wxRichTextTabsEq(const wxArrayInt& tabs1, const wxArrayInt& tabs2)
6634{
6635 if (tabs1.GetCount() != tabs2.GetCount())
6636 return false;
6637
6638 size_t i;
6639 for (i = 0; i < tabs1.GetCount(); i++)
6640 {
6641 if (tabs1[i] != tabs2[i])
6642 return false;
6643 }
6644 return true;
6645}
6646
6647bool wxRichTextApplyStyle(wxTextAttr& destStyle, const wxTextAttr& style, wxTextAttr* compareWith)
6648{
6649 return destStyle.Apply(style, compareWith);
6650}
6651
6652// Remove attributes
6653bool wxRichTextRemoveStyle(wxTextAttr& destStyle, const wxTextAttr& style)
6654{
6655 return wxTextAttr::RemoveStyle(destStyle, style);
6656}
6657
6658/// Combine two bitlists, specifying the bits of interest with separate flags.
6659bool wxRichTextCombineBitlists(int& valueA, int valueB, int& flagsA, int flagsB)
6660{
6661 return wxTextAttr::CombineBitlists(valueA, valueB, flagsA, flagsB);
6662}
6663
6664/// Compare two bitlists
6665bool wxRichTextBitlistsEqPartial(int valueA, int valueB, int flags)
6666{
6667 return wxTextAttr::BitlistsEqPartial(valueA, valueB, flags);
6668}
6669
6670/// Split into paragraph and character styles
6671bool wxRichTextSplitParaCharStyles(const wxTextAttr& style, wxTextAttr& parStyle, wxTextAttr& charStyle)
6672{
6673 return wxTextAttr::SplitParaCharStyles(style, parStyle, charStyle);
6674}
6675
6676/// Convert a decimal to Roman numerals
6677wxString wxRichTextDecimalToRoman(long n)
6678{
6679 static wxArrayInt decimalNumbers;
6680 static wxArrayString romanNumbers;
6681
6682 // Clean up arrays
6683 if (n == -1)
6684 {
6685 decimalNumbers.Clear();
6686 romanNumbers.Clear();
6687 return wxEmptyString;
6688 }
6689
6690 if (decimalNumbers.GetCount() == 0)
6691 {
6692 #define wxRichTextAddDecRom(n, r) decimalNumbers.Add(n); romanNumbers.Add(r);
6693
6694 wxRichTextAddDecRom(1000, wxT("M"));
6695 wxRichTextAddDecRom(900, wxT("CM"));
6696 wxRichTextAddDecRom(500, wxT("D"));
6697 wxRichTextAddDecRom(400, wxT("CD"));
6698 wxRichTextAddDecRom(100, wxT("C"));
6699 wxRichTextAddDecRom(90, wxT("XC"));
6700 wxRichTextAddDecRom(50, wxT("L"));
6701 wxRichTextAddDecRom(40, wxT("XL"));
6702 wxRichTextAddDecRom(10, wxT("X"));
6703 wxRichTextAddDecRom(9, wxT("IX"));
6704 wxRichTextAddDecRom(5, wxT("V"));
6705 wxRichTextAddDecRom(4, wxT("IV"));
6706 wxRichTextAddDecRom(1, wxT("I"));
6707 }
6708
6709 int i = 0;
6710 wxString roman;
6711
6712 while (n > 0 && i < 13)
6713 {
6714 if (n >= decimalNumbers[i])
6715 {
6716 n -= decimalNumbers[i];
6717 roman += romanNumbers[i];
6718 }
6719 else
6720 {
6721 i ++;
6722 }
6723 }
6724 if (roman.IsEmpty())
6725 roman = wxT("0");
6726 return roman;
6727}
6728
6729/*!
6730 * wxRichTextFileHandler
6731 * Base class for file handlers
6732 */
6733
6734IMPLEMENT_CLASS(wxRichTextFileHandler, wxObject)
6735
6736#if wxUSE_FFILE && wxUSE_STREAMS
6737bool wxRichTextFileHandler::LoadFile(wxRichTextBuffer *buffer, const wxString& filename)
6738{
6739 wxFFileInputStream stream(filename);
6740 if (stream.Ok())
6741 return LoadFile(buffer, stream);
6742
6743 return false;
6744}
6745
6746bool wxRichTextFileHandler::SaveFile(wxRichTextBuffer *buffer, const wxString& filename)
6747{
6748 wxFFileOutputStream stream(filename);
6749 if (stream.Ok())
6750 return SaveFile(buffer, stream);
6751
6752 return false;
6753}
6754#endif // wxUSE_FFILE && wxUSE_STREAMS
6755
6756/// Can we handle this filename (if using files)? By default, checks the extension.
6757bool wxRichTextFileHandler::CanHandle(const wxString& filename) const
6758{
6759 wxString path, file, ext;
6760 wxSplitPath(filename, & path, & file, & ext);
6761
6762 return (ext.Lower() == GetExtension());
6763}
6764
6765/*!
6766 * wxRichTextTextHandler
6767 * Plain text handler
6768 */
6769
6770IMPLEMENT_CLASS(wxRichTextPlainTextHandler, wxRichTextFileHandler)
6771
6772#if wxUSE_STREAMS
6773bool wxRichTextPlainTextHandler::DoLoadFile(wxRichTextBuffer *buffer, wxInputStream& stream)
6774{
6775 if (!stream.IsOk())
6776 return false;
6777
6778 wxString str;
6779 int lastCh = 0;
6780
6781 while (!stream.Eof())
6782 {
6783 int ch = stream.GetC();
6784
6785 if (!stream.Eof())
6786 {
6787 if (ch == 10 && lastCh != 13)
6788 str += wxT('\n');
6789
6790 if (ch > 0 && ch != 10)
6791 str += wxChar(ch);
6792
6793 lastCh = ch;
6794 }
6795 }
6796
6797 buffer->ResetAndClearCommands();
6798 buffer->Clear();
6799 buffer->AddParagraphs(str);
6800 buffer->UpdateRanges();
6801
6802 return true;
6803}
6804
6805bool wxRichTextPlainTextHandler::DoSaveFile(wxRichTextBuffer *buffer, wxOutputStream& stream)
6806{
6807 if (!stream.IsOk())
6808 return false;
6809
6810 wxString text = buffer->GetText();
6811
6812 wxString newLine = wxRichTextLineBreakChar;
6813 text.Replace(newLine, wxT("\n"));
6814
6815 wxCharBuffer buf = text.ToAscii();
6816
6817 stream.Write((const char*) buf, text.length());
6818 return true;
6819}
6820#endif // wxUSE_STREAMS
6821
6822/*
6823 * Stores information about an image, in binary in-memory form
6824 */
6825
6826wxRichTextImageBlock::wxRichTextImageBlock()
6827{
6828 Init();
6829}
6830
6831wxRichTextImageBlock::wxRichTextImageBlock(const wxRichTextImageBlock& block):wxObject()
6832{
6833 Init();
6834 Copy(block);
6835}
6836
6837wxRichTextImageBlock::~wxRichTextImageBlock()
6838{
6839 if (m_data)
6840 {
6841 delete[] m_data;
6842 m_data = NULL;
6843 }
6844}
6845
6846void wxRichTextImageBlock::Init()
6847{
6848 m_data = NULL;
6849 m_dataSize = 0;
6850 m_imageType = -1;
6851}
6852
6853void wxRichTextImageBlock::Clear()
6854{
6855 delete[] m_data;
6856 m_data = NULL;
6857 m_dataSize = 0;
6858 m_imageType = -1;
6859}
6860
6861
6862// Load the original image into a memory block.
6863// If the image is not a JPEG, we must convert it into a JPEG
6864// to conserve space.
6865// If it's not a JPEG we can make use of 'image', already scaled, so we don't have to
6866// load the image a 2nd time.
6867
6868bool wxRichTextImageBlock::MakeImageBlock(const wxString& filename, int imageType, wxImage& image, bool convertToJPEG)
6869{
6870 m_imageType = imageType;
6871
6872 wxString filenameToRead(filename);
6873 bool removeFile = false;
6874
6875 if (imageType == -1)
6876 return false; // Could not determine image type
6877
6878 if ((imageType != wxBITMAP_TYPE_JPEG) && convertToJPEG)
6879 {
6880 wxString tempFile;
6881 bool success = wxGetTempFileName(_("image"), tempFile) ;
6882
6883 wxASSERT(success);
6884
6885 wxUnusedVar(success);
6886
6887 image.SaveFile(tempFile, wxBITMAP_TYPE_JPEG);
6888 filenameToRead = tempFile;
6889 removeFile = true;
6890
6891 m_imageType = wxBITMAP_TYPE_JPEG;
6892 }
6893 wxFile file;
6894 if (!file.Open(filenameToRead))
6895 return false;
6896
6897 m_dataSize = (size_t) file.Length();
6898 file.Close();
6899
6900 if (m_data)
6901 delete[] m_data;
6902 m_data = ReadBlock(filenameToRead, m_dataSize);
6903
6904 if (removeFile)
6905 wxRemoveFile(filenameToRead);
6906
6907 return (m_data != NULL);
6908}
6909
6910// Make an image block from the wxImage in the given
6911// format.
6912bool wxRichTextImageBlock::MakeImageBlock(wxImage& image, int imageType, int quality)
6913{
6914 m_imageType = imageType;
6915 image.SetOption(wxT("quality"), quality);
6916
6917 if (imageType == -1)
6918 return false; // Could not determine image type
6919
6920 wxString tempFile;
6921 bool success = wxGetTempFileName(_("image"), tempFile) ;
6922
6923 wxASSERT(success);
6924 wxUnusedVar(success);
6925
6926 if (!image.SaveFile(tempFile, m_imageType))
6927 {
6928 if (wxFileExists(tempFile))
6929 wxRemoveFile(tempFile);
6930 return false;
6931 }
6932
6933 wxFile file;
6934 if (!file.Open(tempFile))
6935 return false;
6936
6937 m_dataSize = (size_t) file.Length();
6938 file.Close();
6939
6940 if (m_data)
6941 delete[] m_data;
6942 m_data = ReadBlock(tempFile, m_dataSize);
6943
6944 wxRemoveFile(tempFile);
6945
6946 return (m_data != NULL);
6947}
6948
6949
6950// Write to a file
6951bool wxRichTextImageBlock::Write(const wxString& filename)
6952{
6953 return WriteBlock(filename, m_data, m_dataSize);
6954}
6955
6956void wxRichTextImageBlock::Copy(const wxRichTextImageBlock& block)
6957{
6958 m_imageType = block.m_imageType;
6959 if (m_data)
6960 {
6961 delete[] m_data;
6962 m_data = NULL;
6963 }
6964 m_dataSize = block.m_dataSize;
6965 if (m_dataSize == 0)
6966 return;
6967
6968 m_data = new unsigned char[m_dataSize];
6969 unsigned int i;
6970 for (i = 0; i < m_dataSize; i++)
6971 m_data[i] = block.m_data[i];
6972}
6973
6974//// Operators
6975void wxRichTextImageBlock::operator=(const wxRichTextImageBlock& block)
6976{
6977 Copy(block);
6978}
6979
6980// Load a wxImage from the block
6981bool wxRichTextImageBlock::Load(wxImage& image)
6982{
6983 if (!m_data)
6984 return false;
6985
6986 // Read in the image.
6987#if wxUSE_STREAMS
6988 wxMemoryInputStream mstream(m_data, m_dataSize);
6989 bool success = image.LoadFile(mstream, GetImageType());
6990#else
6991 wxString tempFile;
6992 bool success = wxGetTempFileName(_("image"), tempFile) ;
6993 wxASSERT(success);
6994
6995 if (!WriteBlock(tempFile, m_data, m_dataSize))
6996 {
6997 return false;
6998 }
6999 success = image.LoadFile(tempFile, GetImageType());
7000 wxRemoveFile(tempFile);
7001#endif
7002
7003 return success;
7004}
7005
7006// Write data in hex to a stream
7007bool wxRichTextImageBlock::WriteHex(wxOutputStream& stream)
7008{
7009 const int bufSize = 512;
7010 char buf[bufSize+1];
7011
7012 int left = m_dataSize;
7013 int n, i, j;
7014 j = 0;
7015 while (left > 0)
7016 {
7017 if (left*2 > bufSize)
7018 {
7019 n = bufSize; left -= (bufSize/2);
7020 }
7021 else
7022 {
7023 n = left*2; left = 0;
7024 }
7025
7026 char* b = buf;
7027 for (i = 0; i < (n/2); i++)
7028 {
7029 wxDecToHex(m_data[j], b, b+1);
7030 b += 2; j ++;
7031 }
7032
7033 buf[n] = 0;
7034 stream.Write((const char*) buf, n);
7035 }
7036 return true;
7037}
7038
7039// Read data in hex from a stream
7040bool wxRichTextImageBlock::ReadHex(wxInputStream& stream, int length, int imageType)
7041{
7042 int dataSize = length/2;
7043
7044 if (m_data)
7045 delete[] m_data;
7046
7047 wxChar str[2];
7048 m_data = new unsigned char[dataSize];
7049 int i;
7050 for (i = 0; i < dataSize; i ++)
7051 {
7052 str[0] = (char)stream.GetC();
7053 str[1] = (char)stream.GetC();
7054
7055 m_data[i] = (unsigned char)wxHexToDec(str);
7056 }
7057
7058 m_dataSize = dataSize;
7059 m_imageType = imageType;
7060
7061 return true;
7062}
7063
7064// Allocate and read from stream as a block of memory
7065unsigned char* wxRichTextImageBlock::ReadBlock(wxInputStream& stream, size_t size)
7066{
7067 unsigned char* block = new unsigned char[size];
7068 if (!block)
7069 return NULL;
7070
7071 stream.Read(block, size);
7072
7073 return block;
7074}
7075
7076unsigned char* wxRichTextImageBlock::ReadBlock(const wxString& filename, size_t size)
7077{
7078 wxFileInputStream stream(filename);
7079 if (!stream.Ok())
7080 return NULL;
7081
7082 return ReadBlock(stream, size);
7083}
7084
7085// Write memory block to stream
7086bool wxRichTextImageBlock::WriteBlock(wxOutputStream& stream, unsigned char* block, size_t size)
7087{
7088 stream.Write((void*) block, size);
7089 return stream.IsOk();
7090
7091}
7092
7093// Write memory block to file
7094bool wxRichTextImageBlock::WriteBlock(const wxString& filename, unsigned char* block, size_t size)
7095{
7096 wxFileOutputStream outStream(filename);
7097 if (!outStream.Ok())
7098 return false;
7099
7100 return WriteBlock(outStream, block, size);
7101}
7102
7103// Gets the extension for the block's type
7104wxString wxRichTextImageBlock::GetExtension() const
7105{
7106 wxImageHandler* handler = wxImage::FindHandler(GetImageType());
7107 if (handler)
7108 return handler->GetExtension();
7109 else
7110 return wxEmptyString;
7111}
7112
7113#if wxUSE_DATAOBJ
7114
7115/*!
7116 * The data object for a wxRichTextBuffer
7117 */
7118
7119const wxChar *wxRichTextBufferDataObject::ms_richTextBufferFormatId = wxT("wxShape");
7120
7121wxRichTextBufferDataObject::wxRichTextBufferDataObject(wxRichTextBuffer* richTextBuffer)
7122{
7123 m_richTextBuffer = richTextBuffer;
7124
7125 // this string should uniquely identify our format, but is otherwise
7126 // arbitrary
7127 m_formatRichTextBuffer.SetId(GetRichTextBufferFormatId());
7128
7129 SetFormat(m_formatRichTextBuffer);
7130}
7131
7132wxRichTextBufferDataObject::~wxRichTextBufferDataObject()
7133{
7134 delete m_richTextBuffer;
7135}
7136
7137// after a call to this function, the richTextBuffer is owned by the caller and it
7138// is responsible for deleting it!
7139wxRichTextBuffer* wxRichTextBufferDataObject::GetRichTextBuffer()
7140{
7141 wxRichTextBuffer* richTextBuffer = m_richTextBuffer;
7142 m_richTextBuffer = NULL;
7143
7144 return richTextBuffer;
7145}
7146
7147wxDataFormat wxRichTextBufferDataObject::GetPreferredFormat(Direction WXUNUSED(dir)) const
7148{
7149 return m_formatRichTextBuffer;
7150}
7151
7152size_t wxRichTextBufferDataObject::GetDataSize() const
7153{
7154 if (!m_richTextBuffer)
7155 return 0;
7156
7157 wxString bufXML;
7158
7159 {
7160 wxStringOutputStream stream(& bufXML);
7161 if (!m_richTextBuffer->SaveFile(stream, wxRICHTEXT_TYPE_XML))
7162 {
7163 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
7164 return 0;
7165 }
7166 }
7167
7168#if wxUSE_UNICODE
7169 wxCharBuffer buffer = bufXML.mb_str(wxConvUTF8);
7170 return strlen(buffer) + 1;
7171#else
7172 return bufXML.Length()+1;
7173#endif
7174}
7175
7176bool wxRichTextBufferDataObject::GetDataHere(void *pBuf) const
7177{
7178 if (!pBuf || !m_richTextBuffer)
7179 return false;
7180
7181 wxString bufXML;
7182
7183 {
7184 wxStringOutputStream stream(& bufXML);
7185 if (!m_richTextBuffer->SaveFile(stream, wxRICHTEXT_TYPE_XML))
7186 {
7187 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
7188 return 0;
7189 }
7190 }
7191
7192#if wxUSE_UNICODE
7193 wxCharBuffer buffer = bufXML.mb_str(wxConvUTF8);
7194 size_t len = strlen(buffer);
7195 memcpy((char*) pBuf, (const char*) buffer, len);
7196 ((char*) pBuf)[len] = 0;
7197#else
7198 size_t len = bufXML.Length();
7199 memcpy((char*) pBuf, (const char*) bufXML.c_str(), len);
7200 ((char*) pBuf)[len] = 0;
7201#endif
7202
7203 return true;
7204}
7205
7206bool wxRichTextBufferDataObject::SetData(size_t WXUNUSED(len), const void *buf)
7207{
7208 delete m_richTextBuffer;
7209 m_richTextBuffer = NULL;
7210
7211 wxString bufXML((const char*) buf, wxConvUTF8);
7212
7213 m_richTextBuffer = new wxRichTextBuffer;
7214
7215 wxStringInputStream stream(bufXML);
7216 if (!m_richTextBuffer->LoadFile(stream, wxRICHTEXT_TYPE_XML))
7217 {
7218 wxLogError(wxT("Could not read the buffer from an XML stream.\nYou may have forgotten to add the XML file handler."));
7219
7220 delete m_richTextBuffer;
7221 m_richTextBuffer = NULL;
7222
7223 return false;
7224 }
7225 return true;
7226}
7227
7228#endif
7229 // wxUSE_DATAOBJ
7230
7231
7232/*
7233 * wxRichTextFontTable
7234 * Manages quick access to a pool of fonts for rendering rich text
7235 */
7236
7237WX_DECLARE_STRING_HASH_MAP_WITH_DECL(wxFont, wxRichTextFontTableHashMap, class WXDLLIMPEXP_RICHTEXT);
7238
7239class wxRichTextFontTableData: public wxObjectRefData
7240{
7241public:
7242 wxRichTextFontTableData() {}
7243
7244 wxFont FindFont(const wxTextAttr& fontSpec);
7245
7246 wxRichTextFontTableHashMap m_hashMap;
7247};
7248
7249wxFont wxRichTextFontTableData::FindFont(const wxTextAttr& fontSpec)
7250{
7251 wxString facename(fontSpec.GetFontFaceName());
7252 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()));
7253 wxRichTextFontTableHashMap::iterator entry = m_hashMap.find(spec);
7254
7255 if ( entry == m_hashMap.end() )
7256 {
7257 wxFont font(fontSpec.GetFontSize(), wxDEFAULT, fontSpec.GetFontStyle(), fontSpec.GetFontWeight(), fontSpec.GetFontUnderlined(), facename.c_str());
7258 m_hashMap[spec] = font;
7259 return font;
7260 }
7261 else
7262 {
7263 return entry->second;
7264 }
7265}
7266
7267IMPLEMENT_DYNAMIC_CLASS(wxRichTextFontTable, wxObject)
7268
7269wxRichTextFontTable::wxRichTextFontTable()
7270{
7271 m_refData = new wxRichTextFontTableData;
7272}
7273
7274wxRichTextFontTable::wxRichTextFontTable(const wxRichTextFontTable& table)
7275{
7276 (*this) = table;
7277}
7278
7279wxRichTextFontTable::~wxRichTextFontTable()
7280{
7281 UnRef();
7282}
7283
7284bool wxRichTextFontTable::operator == (const wxRichTextFontTable& table) const
7285{
7286 return (m_refData == table.m_refData);
7287}
7288
7289void wxRichTextFontTable::operator= (const wxRichTextFontTable& table)
7290{
7291 Ref(table);
7292}
7293
7294wxFont wxRichTextFontTable::FindFont(const wxTextAttr& fontSpec)
7295{
7296 wxRichTextFontTableData* data = (wxRichTextFontTableData*) m_refData;
7297 if (data)
7298 return data->FindFont(fontSpec);
7299 else
7300 return wxFont();
7301}
7302
7303void wxRichTextFontTable::Clear()
7304{
7305 wxRichTextFontTableData* data = (wxRichTextFontTableData*) m_refData;
7306 if (data)
7307 data->m_hashMap.clear();
7308}
7309
7310#endif
7311 // wxUSE_RICHTEXT