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