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