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