]> git.saurik.com Git - wxWidgets.git/blob - src/richtext/richtextbuffer.cpp
Add wxDataViewCtrl::GTKPathToItem() function and use it.
[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 int outline = -1;
2658 int num = -1;
2659 if (para->GetAttributes().HasOutlineLevel())
2660 outline = para->GetAttributes().GetOutlineLevel();
2661 if (para->GetAttributes().HasBulletNumber())
2662 num = para->GetAttributes().GetBulletNumber();
2663
2664 if (!para->GetAttributes().GetParagraphStyleName().IsEmpty() && !para->GetAttributes().GetListStyleName().IsEmpty())
2665 {
2666 int currentIndent = para->GetAttributes().GetLeftIndent();
2667
2668 wxRichTextParagraphStyleDefinition* paraDef = styleSheet->FindParagraphStyle(para->GetAttributes().GetParagraphStyleName());
2669 wxRichTextListStyleDefinition* listDef = styleSheet->FindListStyle(para->GetAttributes().GetListStyleName());
2670 if (paraDef && !listDef)
2671 {
2672 para->GetAttributes() = paraDef->GetStyleMergedWithBase(styleSheet);
2673 foundCount ++;
2674 }
2675 else if (listDef && !paraDef)
2676 {
2677 // Set overall style defined for the list style definition
2678 para->GetAttributes() = listDef->GetStyleMergedWithBase(styleSheet);
2679
2680 // Apply the style for this level
2681 wxRichTextApplyStyle(para->GetAttributes(), * listDef->GetLevelAttributes(listDef->FindLevelForIndent(currentIndent)));
2682 foundCount ++;
2683 }
2684 else if (listDef && paraDef)
2685 {
2686 // Combines overall list style, style for level, and paragraph style
2687 para->GetAttributes() = listDef->CombineWithParagraphStyle(currentIndent, paraDef->GetStyleMergedWithBase(styleSheet));
2688 foundCount ++;
2689 }
2690 }
2691 else if (para->GetAttributes().GetParagraphStyleName().IsEmpty() && !para->GetAttributes().GetListStyleName().IsEmpty())
2692 {
2693 int currentIndent = para->GetAttributes().GetLeftIndent();
2694
2695 wxRichTextListStyleDefinition* listDef = styleSheet->FindListStyle(para->GetAttributes().GetListStyleName());
2696
2697 // Overall list definition style
2698 para->GetAttributes() = listDef->GetStyleMergedWithBase(styleSheet);
2699
2700 // Style for this level
2701 wxRichTextApplyStyle(para->GetAttributes(), * listDef->GetLevelAttributes(listDef->FindLevelForIndent(currentIndent)));
2702
2703 foundCount ++;
2704 }
2705 else if (!para->GetAttributes().GetParagraphStyleName().IsEmpty() && para->GetAttributes().GetListStyleName().IsEmpty())
2706 {
2707 wxRichTextParagraphStyleDefinition* def = styleSheet->FindParagraphStyle(para->GetAttributes().GetParagraphStyleName());
2708 if (def)
2709 {
2710 para->GetAttributes() = def->GetStyleMergedWithBase(styleSheet);
2711 foundCount ++;
2712 }
2713 }
2714
2715 if (outline != -1)
2716 para->GetAttributes().SetOutlineLevel(outline);
2717 if (num != -1)
2718 para->GetAttributes().SetBulletNumber(num);
2719 }
2720
2721 node = node->GetNext();
2722 }
2723 return foundCount != 0;
2724 }
2725
2726 /// Set list style
2727 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags, int startFrom, int specifiedLevel)
2728 {
2729 wxRichTextStyleSheet* styleSheet = GetStyleSheet();
2730
2731 bool withUndo = ((flags & wxRICHTEXT_SETSTYLE_WITH_UNDO) != 0);
2732 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2733 bool specifyLevel = ((flags & wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL) != 0);
2734 bool renumber = ((flags & wxRICHTEXT_SETSTYLE_RENUMBER) != 0);
2735
2736 // Current number, if numbering
2737 int n = startFrom;
2738
2739 wxASSERT (!specifyLevel || (specifyLevel && (specifiedLevel >= 0)));
2740
2741 // If we are associated with a control, make undoable; otherwise, apply immediately
2742 // to the data.
2743
2744 bool haveControl = (GetRichTextCtrl() != NULL);
2745
2746 wxRichTextAction* action = NULL;
2747
2748 if (haveControl && withUndo)
2749 {
2750 action = new wxRichTextAction(NULL, _("Change List Style"), wxRICHTEXT_CHANGE_STYLE, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2751 action->SetRange(range);
2752 action->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2753 }
2754
2755 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
2756 while (node)
2757 {
2758 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
2759 wxASSERT (para != NULL);
2760
2761 if (para && para->GetChildCount() > 0)
2762 {
2763 // Stop searching if we're beyond the range of interest
2764 if (para->GetRange().GetStart() > range.GetEnd())
2765 break;
2766
2767 if (!para->GetRange().IsOutside(range))
2768 {
2769 // We'll be using a copy of the paragraph to make style changes,
2770 // not updating the buffer directly.
2771 wxRichTextParagraph* newPara wxDUMMY_INITIALIZE(NULL);
2772
2773 if (haveControl && withUndo)
2774 {
2775 newPara = new wxRichTextParagraph(*para);
2776 action->GetNewParagraphs().AppendChild(newPara);
2777
2778 // Also store the old ones for Undo
2779 action->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para));
2780 }
2781 else
2782 newPara = para;
2783
2784 if (def)
2785 {
2786 int thisIndent = newPara->GetAttributes().GetLeftIndent();
2787 int thisLevel = specifyLevel ? specifiedLevel : def->FindLevelForIndent(thisIndent);
2788
2789 // How is numbering going to work?
2790 // If we are renumbering, or numbering for the first time, we need to keep
2791 // track of the number for each level. But we might be simply applying a different
2792 // list style.
2793 // In Word, applying a style to several paragraphs, even if at different levels,
2794 // reverts the level back to the same one. So we could do the same here.
2795 // Renumbering will need to be done when we promote/demote a paragraph.
2796
2797 // Apply the overall list style, and item style for this level
2798 wxTextAttr listStyle(def->GetCombinedStyleForLevel(thisLevel, styleSheet));
2799 wxRichTextApplyStyle(newPara->GetAttributes(), listStyle);
2800
2801 // Now we need to do numbering
2802 if (renumber)
2803 {
2804 newPara->GetAttributes().SetBulletNumber(n);
2805 }
2806
2807 n ++;
2808 }
2809 else if (!newPara->GetAttributes().GetListStyleName().IsEmpty())
2810 {
2811 // if def is NULL, remove list style, applying any associated paragraph style
2812 // to restore the attributes
2813
2814 newPara->GetAttributes().SetListStyleName(wxEmptyString);
2815 newPara->GetAttributes().SetLeftIndent(0, 0);
2816 newPara->GetAttributes().SetBulletText(wxEmptyString);
2817
2818 // Eliminate the main list-related attributes
2819 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);
2820
2821 if (styleSheet && !newPara->GetAttributes().GetParagraphStyleName().IsEmpty())
2822 {
2823 wxRichTextParagraphStyleDefinition* def = styleSheet->FindParagraphStyle(newPara->GetAttributes().GetParagraphStyleName());
2824 if (def)
2825 {
2826 newPara->GetAttributes() = def->GetStyleMergedWithBase(styleSheet);
2827 }
2828 }
2829 }
2830 }
2831 }
2832
2833 node = node->GetNext();
2834 }
2835
2836 // Do action, or delay it until end of batch.
2837 if (haveControl && withUndo)
2838 GetRichTextCtrl()->GetBuffer().SubmitAction(action);
2839
2840 return true;
2841 }
2842
2843 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange& range, const wxString& defName, int flags, int startFrom, int specifiedLevel)
2844 {
2845 if (GetStyleSheet())
2846 {
2847 wxRichTextListStyleDefinition* def = GetStyleSheet()->FindListStyle(defName);
2848 if (def)
2849 return SetListStyle(range, def, flags, startFrom, specifiedLevel);
2850 }
2851 return false;
2852 }
2853
2854 /// Clear list for given range
2855 bool wxRichTextParagraphLayoutBox::ClearListStyle(const wxRichTextRange& range, int flags)
2856 {
2857 return SetListStyle(range, NULL, flags);
2858 }
2859
2860 /// Number/renumber any list elements in the given range
2861 bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags, int startFrom, int specifiedLevel)
2862 {
2863 return DoNumberList(range, range, 0, def, flags, startFrom, specifiedLevel);
2864 }
2865
2866 /// Number/renumber any list elements in the given range. Also do promotion or demotion of items, if specified
2867 bool wxRichTextParagraphLayoutBox::DoNumberList(const wxRichTextRange& range, const wxRichTextRange& promotionRange, int promoteBy,
2868 wxRichTextListStyleDefinition* def, int flags, int startFrom, int specifiedLevel)
2869 {
2870 wxRichTextStyleSheet* styleSheet = GetStyleSheet();
2871
2872 bool withUndo = ((flags & wxRICHTEXT_SETSTYLE_WITH_UNDO) != 0);
2873 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2874 #if wxDEBUG_LEVEL
2875 bool specifyLevel = ((flags & wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL) != 0);
2876 #endif
2877
2878 bool renumber = ((flags & wxRICHTEXT_SETSTYLE_RENUMBER) != 0);
2879
2880 // Max number of levels
2881 const int maxLevels = 10;
2882
2883 // The level we're looking at now
2884 int currentLevel = -1;
2885
2886 // The item number for each level
2887 int levels[maxLevels];
2888 int i;
2889
2890 // Reset all numbering
2891 for (i = 0; i < maxLevels; i++)
2892 {
2893 if (startFrom != -1)
2894 levels[i] = startFrom-1;
2895 else if (renumber) // start again
2896 levels[i] = 0;
2897 else
2898 levels[i] = -1; // start from the number we found, if any
2899 }
2900
2901 wxASSERT(!specifyLevel || (specifyLevel && (specifiedLevel >= 0)));
2902
2903 // If we are associated with a control, make undoable; otherwise, apply immediately
2904 // to the data.
2905
2906 bool haveControl = (GetRichTextCtrl() != NULL);
2907
2908 wxRichTextAction* action = NULL;
2909
2910 if (haveControl && withUndo)
2911 {
2912 action = new wxRichTextAction(NULL, _("Renumber List"), wxRICHTEXT_CHANGE_STYLE, & GetRichTextCtrl()->GetBuffer(), GetRichTextCtrl());
2913 action->SetRange(range);
2914 action->SetPosition(GetRichTextCtrl()->GetCaretPosition());
2915 }
2916
2917 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
2918 while (node)
2919 {
2920 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
2921 wxASSERT (para != NULL);
2922
2923 if (para && para->GetChildCount() > 0)
2924 {
2925 // Stop searching if we're beyond the range of interest
2926 if (para->GetRange().GetStart() > range.GetEnd())
2927 break;
2928
2929 if (!para->GetRange().IsOutside(range))
2930 {
2931 // We'll be using a copy of the paragraph to make style changes,
2932 // not updating the buffer directly.
2933 wxRichTextParagraph* newPara wxDUMMY_INITIALIZE(NULL);
2934
2935 if (haveControl && withUndo)
2936 {
2937 newPara = new wxRichTextParagraph(*para);
2938 action->GetNewParagraphs().AppendChild(newPara);
2939
2940 // Also store the old ones for Undo
2941 action->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para));
2942 }
2943 else
2944 newPara = para;
2945
2946 wxRichTextListStyleDefinition* defToUse = def;
2947 if (!defToUse)
2948 {
2949 if (styleSheet && !newPara->GetAttributes().GetListStyleName().IsEmpty())
2950 defToUse = styleSheet->FindListStyle(newPara->GetAttributes().GetListStyleName());
2951 }
2952
2953 if (defToUse)
2954 {
2955 int thisIndent = newPara->GetAttributes().GetLeftIndent();
2956 int thisLevel = defToUse->FindLevelForIndent(thisIndent);
2957
2958 // If we've specified a level to apply to all, change the level.
2959 if (specifiedLevel != -1)
2960 thisLevel = specifiedLevel;
2961
2962 // Do promotion if specified
2963 if ((promoteBy != 0) && !para->GetRange().IsOutside(promotionRange))
2964 {
2965 thisLevel = thisLevel - promoteBy;
2966 if (thisLevel < 0)
2967 thisLevel = 0;
2968 if (thisLevel > 9)
2969 thisLevel = 9;
2970 }
2971
2972 // Apply the overall list style, and item style for this level
2973 wxTextAttr listStyle(defToUse->GetCombinedStyleForLevel(thisLevel, styleSheet));
2974 wxRichTextApplyStyle(newPara->GetAttributes(), listStyle);
2975
2976 // OK, we've (re)applied the style, now let's get the numbering right.
2977
2978 if (currentLevel == -1)
2979 currentLevel = thisLevel;
2980
2981 // Same level as before, do nothing except increment level's number afterwards
2982 if (currentLevel == thisLevel)
2983 {
2984 }
2985 // A deeper level: start renumbering all levels after current level
2986 else if (thisLevel > currentLevel)
2987 {
2988 for (i = currentLevel+1; i <= thisLevel; i++)
2989 {
2990 levels[i] = 0;
2991 }
2992 currentLevel = thisLevel;
2993 }
2994 else if (thisLevel < currentLevel)
2995 {
2996 currentLevel = thisLevel;
2997 }
2998
2999 // Use the current numbering if -1 and we have a bullet number already
3000 if (levels[currentLevel] == -1)
3001 {
3002 if (newPara->GetAttributes().HasBulletNumber())
3003 levels[currentLevel] = newPara->GetAttributes().GetBulletNumber();
3004 else
3005 levels[currentLevel] = 1;
3006 }
3007 else
3008 {
3009 levels[currentLevel] ++;
3010 }
3011
3012 newPara->GetAttributes().SetBulletNumber(levels[currentLevel]);
3013
3014 // Create the bullet text if an outline list
3015 if (listStyle.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE)
3016 {
3017 wxString text;
3018 for (i = 0; i <= currentLevel; i++)
3019 {
3020 if (!text.IsEmpty())
3021 text += wxT(".");
3022 text += wxString::Format(wxT("%d"), levels[i]);
3023 }
3024 newPara->GetAttributes().SetBulletText(text);
3025 }
3026 }
3027 }
3028 }
3029
3030 node = node->GetNext();
3031 }
3032
3033 // Do action, or delay it until end of batch.
3034 if (haveControl && withUndo)
3035 GetRichTextCtrl()->GetBuffer().SubmitAction(action);
3036
3037 return true;
3038 }
3039
3040 bool wxRichTextParagraphLayoutBox::NumberList(const wxRichTextRange& range, const wxString& defName, int flags, int startFrom, int specifiedLevel)
3041 {
3042 if (GetStyleSheet())
3043 {
3044 wxRichTextListStyleDefinition* def = NULL;
3045 if (!defName.IsEmpty())
3046 def = GetStyleSheet()->FindListStyle(defName);
3047 return NumberList(range, def, flags, startFrom, specifiedLevel);
3048 }
3049 return false;
3050 }
3051
3052 /// Promote the list items within the given range. promoteBy can be a positive or negative number, e.g. 1 or -1
3053 bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy, const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags, int specifiedLevel)
3054 {
3055 // TODO
3056 // One strategy is to first work out the range within which renumbering must occur. Then could pass these two ranges
3057 // to NumberList with a flag indicating promotion is required within one of the ranges.
3058 // Find first and last paragraphs in range. Then for first, calculate new indentation and look back until we find
3059 // a paragraph that either has no list style, or has one that is different or whose indentation is less.
3060 // We start renumbering from the para after that different para we found. We specify that the numbering of that
3061 // list position will start from 1.
3062 // Similarly, we look after the last para in the promote range for an indentation that is less (or no list style).
3063 // We can end the renumbering at this point.
3064
3065 // For now, only renumber within the promotion range.
3066
3067 return DoNumberList(range, range, promoteBy, def, flags, 1, specifiedLevel);
3068 }
3069
3070 bool wxRichTextParagraphLayoutBox::PromoteList(int promoteBy, const wxRichTextRange& range, const wxString& defName, int flags, int specifiedLevel)
3071 {
3072 if (GetStyleSheet())
3073 {
3074 wxRichTextListStyleDefinition* def = NULL;
3075 if (!defName.IsEmpty())
3076 def = GetStyleSheet()->FindListStyle(defName);
3077 return PromoteList(promoteBy, range, def, flags, specifiedLevel);
3078 }
3079 return false;
3080 }
3081
3082 /// Fills in the attributes for numbering a paragraph after previousParagraph. It also finds the
3083 /// position of the paragraph that it had to start looking from.
3084 bool wxRichTextParagraphLayoutBox::FindNextParagraphNumber(wxRichTextParagraph* previousParagraph, wxTextAttr& attr) const
3085 {
3086 if (!previousParagraph->GetAttributes().HasFlag(wxTEXT_ATTR_BULLET_STYLE) || previousParagraph->GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE)
3087 return false;
3088
3089 wxRichTextStyleSheet* styleSheet = GetStyleSheet();
3090 if (styleSheet && !previousParagraph->GetAttributes().GetListStyleName().IsEmpty())
3091 {
3092 wxRichTextListStyleDefinition* def = styleSheet->FindListStyle(previousParagraph->GetAttributes().GetListStyleName());
3093 if (def)
3094 {
3095 // int thisIndent = previousParagraph->GetAttributes().GetLeftIndent();
3096 // int thisLevel = def->FindLevelForIndent(thisIndent);
3097
3098 bool isOutline = (previousParagraph->GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE) != 0;
3099
3100 attr.SetFlags(previousParagraph->GetAttributes().GetFlags() & (wxTEXT_ATTR_BULLET_STYLE|wxTEXT_ATTR_BULLET_NUMBER|wxTEXT_ATTR_BULLET_TEXT|wxTEXT_ATTR_BULLET_NAME));
3101 if (previousParagraph->GetAttributes().HasBulletName())
3102 attr.SetBulletName(previousParagraph->GetAttributes().GetBulletName());
3103 attr.SetBulletStyle(previousParagraph->GetAttributes().GetBulletStyle());
3104 attr.SetListStyleName(previousParagraph->GetAttributes().GetListStyleName());
3105
3106 int nextNumber = previousParagraph->GetAttributes().GetBulletNumber() + 1;
3107 attr.SetBulletNumber(nextNumber);
3108
3109 if (isOutline)
3110 {
3111 wxString text = previousParagraph->GetAttributes().GetBulletText();
3112 if (!text.IsEmpty())
3113 {
3114 int pos = text.Find(wxT('.'), true);
3115 if (pos != wxNOT_FOUND)
3116 {
3117 text = text.Mid(0, text.Length() - pos - 1);
3118 }
3119 else
3120 text = wxEmptyString;
3121 if (!text.IsEmpty())
3122 text += wxT(".");
3123 text += wxString::Format(wxT("%d"), nextNumber);
3124 attr.SetBulletText(text);
3125 }
3126 }
3127
3128 return true;
3129 }
3130 else
3131 return false;
3132 }
3133 else
3134 return false;
3135 }
3136
3137 /*!
3138 * wxRichTextParagraph
3139 * This object represents a single paragraph (or in a straight text editor, a line).
3140 */
3141
3142 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraph, wxRichTextBox)
3143
3144 wxArrayInt wxRichTextParagraph::sm_defaultTabs;
3145
3146 wxRichTextParagraph::wxRichTextParagraph(wxRichTextObject* parent, wxTextAttr* style):
3147 wxRichTextBox(parent)
3148 {
3149 if (style)
3150 SetAttributes(*style);
3151 }
3152
3153 wxRichTextParagraph::wxRichTextParagraph(const wxString& text, wxRichTextObject* parent, wxTextAttr* paraStyle, wxTextAttr* charStyle):
3154 wxRichTextBox(parent)
3155 {
3156 if (paraStyle)
3157 SetAttributes(*paraStyle);
3158
3159 AppendChild(new wxRichTextPlainText(text, this, charStyle));
3160 }
3161
3162 wxRichTextParagraph::~wxRichTextParagraph()
3163 {
3164 ClearLines();
3165 }
3166
3167 /// Draw the item
3168 bool wxRichTextParagraph::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextRange& selectionRange, const wxRect& rect, int WXUNUSED(descent), int style)
3169 {
3170 wxTextAttr attr = GetCombinedAttributes();
3171
3172 // Draw the bullet, if any
3173 if (attr.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE)
3174 {
3175 if (attr.GetLeftSubIndent() != 0)
3176 {
3177 int spaceBeforePara = ConvertTenthsMMToPixels(dc, attr.GetParagraphSpacingBefore());
3178 int leftIndent = ConvertTenthsMMToPixels(dc, attr.GetLeftIndent());
3179
3180 wxTextAttr bulletAttr(GetCombinedAttributes());
3181
3182 // Combine with the font of the first piece of content, if one is specified
3183 if (GetChildren().GetCount() > 0)
3184 {
3185 wxRichTextObject* firstObj = (wxRichTextObject*) GetChildren().GetFirst()->GetData();
3186 if (firstObj->GetAttributes().HasFont())
3187 {
3188 wxRichTextApplyStyle(bulletAttr, firstObj->GetAttributes());
3189 }
3190 }
3191
3192 // Get line height from first line, if any
3193 wxRichTextLine* line = m_cachedLines.GetFirst() ? (wxRichTextLine* ) m_cachedLines.GetFirst()->GetData() : NULL;
3194
3195 wxPoint linePos;
3196 int lineHeight wxDUMMY_INITIALIZE(0);
3197 if (line)
3198 {
3199 lineHeight = line->GetSize().y;
3200 linePos = line->GetPosition() + GetPosition();
3201 }
3202 else
3203 {
3204 wxFont font;
3205 if (bulletAttr.HasFont() && GetBuffer())
3206 font = GetBuffer()->GetFontTable().FindFont(bulletAttr);
3207 else
3208 font = (*wxNORMAL_FONT);
3209
3210 wxCheckSetFont(dc, font);
3211
3212 lineHeight = dc.GetCharHeight();
3213 linePos = GetPosition();
3214 linePos.y += spaceBeforePara;
3215 }
3216
3217 wxRect bulletRect(GetPosition().x + leftIndent, linePos.y, linePos.x - (GetPosition().x + leftIndent), lineHeight);
3218
3219 if (attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP)
3220 {
3221 if (wxRichTextBuffer::GetRenderer())
3222 wxRichTextBuffer::GetRenderer()->DrawBitmapBullet(this, dc, bulletAttr, bulletRect);
3223 }
3224 else if (attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_STANDARD)
3225 {
3226 if (wxRichTextBuffer::GetRenderer())
3227 wxRichTextBuffer::GetRenderer()->DrawStandardBullet(this, dc, bulletAttr, bulletRect);
3228 }
3229 else
3230 {
3231 wxString bulletText = GetBulletText();
3232
3233 if (!bulletText.empty() && wxRichTextBuffer::GetRenderer())
3234 wxRichTextBuffer::GetRenderer()->DrawTextBullet(this, dc, bulletAttr, bulletRect, bulletText);
3235 }
3236 }
3237 }
3238
3239 // Draw the range for each line, one object at a time.
3240
3241 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetFirst();
3242 while (node)
3243 {
3244 wxRichTextLine* line = node->GetData();
3245 wxRichTextRange lineRange = line->GetAbsoluteRange();
3246
3247 // Lines are specified relative to the paragraph
3248
3249 wxPoint linePosition = line->GetPosition() + GetPosition();
3250
3251 // Don't draw if off the screen
3252 if (((style & wxRICHTEXT_DRAW_IGNORE_CACHE) != 0) || ((linePosition.y + line->GetSize().y) >= rect.y && linePosition.y <= rect.y + rect.height))
3253 {
3254 wxPoint objectPosition = linePosition;
3255 int maxDescent = line->GetDescent();
3256
3257 // Loop through objects until we get to the one within range
3258 wxRichTextObjectList::compatibility_iterator node2 = m_children.GetFirst();
3259
3260 int i = 0;
3261 while (node2)
3262 {
3263 wxRichTextObject* child = node2->GetData();
3264
3265 if (child->GetRange().GetLength() > 0 && !child->GetRange().IsOutside(lineRange) && !lineRange.IsOutside(range))
3266 {
3267 // Draw this part of the line at the correct position
3268 wxRichTextRange objectRange(child->GetRange());
3269 objectRange.LimitTo(lineRange);
3270
3271 wxSize objectSize;
3272 #if wxRICHTEXT_USE_OPTIMIZED_LINE_DRAWING && wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
3273 if (i < (int) line->GetObjectSizes().GetCount())
3274 {
3275 objectSize.x = line->GetObjectSizes()[(size_t) i];
3276 }
3277 else
3278 #endif
3279 {
3280 int descent = 0;
3281 child->GetRangeSize(objectRange, objectSize, descent, dc, wxRICHTEXT_UNFORMATTED, objectPosition);
3282 }
3283
3284 // Use the child object's width, but the whole line's height
3285 wxRect childRect(objectPosition, wxSize(objectSize.x, line->GetSize().y));
3286 child->Draw(dc, objectRange, selectionRange, childRect, maxDescent, style);
3287
3288 objectPosition.x += objectSize.x;
3289 i ++;
3290 }
3291 else if (child->GetRange().GetStart() > lineRange.GetEnd())
3292 // Can break out of inner loop now since we've passed this line's range
3293 break;
3294
3295 node2 = node2->GetNext();
3296 }
3297 }
3298
3299 node = node->GetNext();
3300 }
3301
3302 return true;
3303 }
3304
3305 // Get the range width using partial extents calculated for the whole paragraph.
3306 static int wxRichTextGetRangeWidth(const wxRichTextParagraph& para, const wxRichTextRange& range, const wxArrayInt& partialExtents)
3307 {
3308 wxASSERT(partialExtents.GetCount() >= (size_t) range.GetLength());
3309
3310 if (partialExtents.GetCount() < (size_t) range.GetLength())
3311 return 0;
3312
3313 int leftMostPos = 0;
3314 if (range.GetStart() - para.GetRange().GetStart() > 0)
3315 leftMostPos = partialExtents[range.GetStart() - para.GetRange().GetStart() - 1];
3316
3317 int rightMostPos = partialExtents[range.GetEnd() - para.GetRange().GetStart()];
3318
3319 int w = rightMostPos - leftMostPos;
3320
3321 return w;
3322 }
3323
3324 /// Lay the item out
3325 bool wxRichTextParagraph::Layout(wxDC& dc, const wxRect& rect, int style)
3326 {
3327 wxTextAttr attr = GetCombinedAttributes();
3328
3329 // ClearLines();
3330
3331 // Increase the size of the paragraph due to spacing
3332 int spaceBeforePara = ConvertTenthsMMToPixels(dc, attr.GetParagraphSpacingBefore());
3333 int spaceAfterPara = ConvertTenthsMMToPixels(dc, attr.GetParagraphSpacingAfter());
3334 int leftIndent = ConvertTenthsMMToPixels(dc, attr.GetLeftIndent());
3335 int leftSubIndent = ConvertTenthsMMToPixels(dc, attr.GetLeftSubIndent());
3336 int rightIndent = ConvertTenthsMMToPixels(dc, attr.GetRightIndent());
3337
3338 int lineSpacing = 0;
3339
3340 // Let's assume line spacing of 10 is normal, 15 is 1.5, 20 is 2, etc.
3341 if (attr.GetLineSpacing() != 10 && GetBuffer())
3342 {
3343 wxFont font(GetBuffer()->GetFontTable().FindFont(attr));
3344 wxCheckSetFont(dc, font);
3345 lineSpacing = (ConvertTenthsMMToPixels(dc, dc.GetCharHeight()) * attr.GetLineSpacing())/10;
3346 }
3347
3348 // Available space for text on each line differs.
3349 int availableTextSpaceFirstLine = rect.GetWidth() - leftIndent - rightIndent;
3350
3351 // Bullets start the text at the same position as subsequent lines
3352 if (attr.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE)
3353 availableTextSpaceFirstLine -= leftSubIndent;
3354
3355 int availableTextSpaceSubsequentLines = rect.GetWidth() - leftIndent - rightIndent - leftSubIndent;
3356
3357 // Start position for each line relative to the paragraph
3358 int startPositionFirstLine = leftIndent;
3359 int startPositionSubsequentLines = leftIndent + leftSubIndent;
3360
3361 // If we have a bullet in this paragraph, the start position for the first line's text
3362 // is actually leftIndent + leftSubIndent.
3363 if (attr.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE)
3364 startPositionFirstLine = startPositionSubsequentLines;
3365
3366 long lastEndPos = GetRange().GetStart()-1;
3367 long lastCompletedEndPos = lastEndPos;
3368
3369 int currentWidth = 0;
3370 SetPosition(rect.GetPosition());
3371
3372 wxPoint currentPosition(0, spaceBeforePara); // We will calculate lines relative to paragraph
3373 int lineHeight = 0;
3374 int maxWidth = 0;
3375 int maxAscent = 0;
3376 int maxDescent = 0;
3377 int lineCount = 0;
3378
3379 wxRichTextObjectList::compatibility_iterator node;
3380
3381 #if wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
3382 wxUnusedVar(style);
3383 wxArrayInt partialExtents;
3384
3385 wxSize paraSize;
3386 int paraDescent;
3387
3388 // This calculates the partial text extents
3389 GetRangeSize(GetRange(), paraSize, paraDescent, dc, wxRICHTEXT_UNFORMATTED|wxRICHTEXT_CACHE_SIZE, wxPoint(0,0), & partialExtents);
3390 #else
3391 node = m_children.GetFirst();
3392 while (node)
3393 {
3394 wxRichTextObject* child = node->GetData();
3395
3396 child->SetCachedSize(wxDefaultSize);
3397 child->Layout(dc, rect, style);
3398
3399 node = node->GetNext();
3400 }
3401
3402 #endif
3403
3404 // Split up lines
3405
3406 // We may need to go back to a previous child, in which case create the new line,
3407 // find the child corresponding to the start position of the string, and
3408 // continue.
3409
3410 node = m_children.GetFirst();
3411 while (node)
3412 {
3413 wxRichTextObject* child = node->GetData();
3414
3415 if (child->GetRange().GetLength() == 0)
3416 {
3417 node = node->GetNext();
3418 continue;
3419 }
3420
3421 // If this is e.g. a composite text box, it will need to be laid out itself.
3422 // But if just a text fragment or image, for example, this will
3423 // do nothing. NB: won't we need to set the position after layout?
3424 // since for example if position is dependent on vertical line size, we
3425 // can't tell the position until the size is determined. So possibly introduce
3426 // another layout phase.
3427
3428 // Available width depends on whether we're on the first or subsequent lines
3429 int availableSpaceForText = (lineCount == 0 ? availableTextSpaceFirstLine : availableTextSpaceSubsequentLines);
3430
3431 currentPosition.x = (lineCount == 0 ? startPositionFirstLine : startPositionSubsequentLines);
3432
3433 // We may only be looking at part of a child, if we searched back for wrapping
3434 // and found a suitable point some way into the child. So get the size for the fragment
3435 // if necessary.
3436
3437 long nextBreakPos = GetFirstLineBreakPosition(lastEndPos+1);
3438 long lastPosToUse = child->GetRange().GetEnd();
3439 bool lineBreakInThisObject = (nextBreakPos > -1 && nextBreakPos <= child->GetRange().GetEnd());
3440
3441 if (lineBreakInThisObject)
3442 lastPosToUse = nextBreakPos;
3443
3444 wxSize childSize;
3445 int childDescent = 0;
3446
3447 if ((nextBreakPos == -1) && (lastEndPos == child->GetRange().GetStart() - 1)) // i.e. we want to get the whole thing
3448 {
3449 childSize = child->GetCachedSize();
3450 childDescent = child->GetDescent();
3451 }
3452 else
3453 {
3454 #if wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
3455 // Get height only, then the width using the partial extents
3456 GetRangeSize(wxRichTextRange(lastEndPos+1, lastPosToUse), childSize, childDescent, dc, wxRICHTEXT_UNFORMATTED|wxRICHTEXT_HEIGHT_ONLY);
3457 childSize.x = wxRichTextGetRangeWidth(*this, wxRichTextRange(lastEndPos+1, lastPosToUse), partialExtents);
3458 #else
3459 GetRangeSize(wxRichTextRange(lastEndPos+1, lastPosToUse), childSize, childDescent, dc, wxRICHTEXT_UNFORMATTED, rect.GetPosition());
3460 #endif
3461 }
3462
3463 // Cases:
3464 // 1) There was a line break BEFORE the natural break
3465 // 2) There was a line break AFTER the natural break
3466 // 3) The child still fits (carry on)
3467
3468 if ((lineBreakInThisObject && (childSize.x + currentWidth <= availableSpaceForText)) ||
3469 (childSize.x + currentWidth > availableSpaceForText))
3470 {
3471 long wrapPosition = 0;
3472
3473 // Find a place to wrap. This may walk back to previous children,
3474 // for example if a word spans several objects.
3475 if (!FindWrapPosition(wxRichTextRange(lastCompletedEndPos+1, child->GetRange().GetEnd()), dc, availableSpaceForText, wrapPosition, & partialExtents))
3476 {
3477 // If the function failed, just cut it off at the end of this child.
3478 wrapPosition = child->GetRange().GetEnd();
3479 }
3480
3481 // FindWrapPosition can still return a value that will put us in an endless wrapping loop
3482 if (wrapPosition <= lastCompletedEndPos)
3483 wrapPosition = wxMax(lastCompletedEndPos+1,child->GetRange().GetEnd());
3484
3485 // wxLogDebug(wxT("Split at %ld"), wrapPosition);
3486
3487 // Let's find the actual size of the current line now
3488 wxSize actualSize;
3489 wxRichTextRange actualRange(lastCompletedEndPos+1, wrapPosition);
3490
3491 /// Use previous descent, not the wrapping descent we just found, since this may be too big
3492 /// for the fragment we're about to add.
3493 childDescent = maxDescent;
3494
3495 #if wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
3496 // Get height only, then the width using the partial extents
3497 GetRangeSize(actualRange, actualSize, childDescent, dc, wxRICHTEXT_UNFORMATTED|wxRICHTEXT_HEIGHT_ONLY);
3498 actualSize.x = wxRichTextGetRangeWidth(*this, actualRange, partialExtents);
3499 #else
3500 GetRangeSize(actualRange, actualSize, childDescent, dc, wxRICHTEXT_UNFORMATTED);
3501 #endif
3502
3503 currentWidth = actualSize.x;
3504 maxDescent = wxMax(childDescent, maxDescent);
3505 maxAscent = wxMax(actualSize.y-childDescent, maxAscent);
3506 lineHeight = maxDescent + maxAscent;
3507
3508 // Add a new line
3509 wxRichTextLine* line = AllocateLine(lineCount);
3510
3511 // Set relative range so we won't have to change line ranges when paragraphs are moved
3512 line->SetRange(wxRichTextRange(actualRange.GetStart() - GetRange().GetStart(), actualRange.GetEnd() - GetRange().GetStart()));
3513 line->SetPosition(currentPosition);
3514 line->SetSize(wxSize(currentWidth, lineHeight));
3515 line->SetDescent(maxDescent);
3516
3517 // Now move down a line. TODO: add margins, spacing
3518 currentPosition.y += lineHeight;
3519 currentPosition.y += lineSpacing;
3520 currentWidth = 0;
3521 maxDescent = 0;
3522 maxAscent = 0;
3523 maxWidth = wxMax(maxWidth, currentWidth);
3524
3525 lineCount ++;
3526
3527 // TODO: account for zero-length objects, such as fields
3528 wxASSERT(wrapPosition > lastCompletedEndPos);
3529
3530 lastEndPos = wrapPosition;
3531 lastCompletedEndPos = lastEndPos;
3532
3533 lineHeight = 0;
3534
3535 // May need to set the node back to a previous one, due to searching back in wrapping
3536 wxRichTextObject* childAfterWrapPosition = FindObjectAtPosition(wrapPosition+1);
3537 if (childAfterWrapPosition)
3538 node = m_children.Find(childAfterWrapPosition);
3539 else
3540 node = node->GetNext();
3541 }
3542 else
3543 {
3544 // We still fit, so don't add a line, and keep going
3545 currentWidth += childSize.x;
3546 maxDescent = wxMax(childDescent, maxDescent);
3547 maxAscent = wxMax(childSize.y-childDescent, maxAscent);
3548 lineHeight = maxDescent + maxAscent;
3549
3550 maxWidth = wxMax(maxWidth, currentWidth);
3551 lastEndPos = child->GetRange().GetEnd();
3552
3553 node = node->GetNext();
3554 }
3555 }
3556
3557 // Add the last line - it's the current pos -> last para pos
3558 // Substract -1 because the last position is always the end-paragraph position.
3559 if (lastCompletedEndPos <= GetRange().GetEnd()-1)
3560 {
3561 currentPosition.x = (lineCount == 0 ? startPositionFirstLine : startPositionSubsequentLines);
3562
3563 wxRichTextLine* line = AllocateLine(lineCount);
3564
3565 wxRichTextRange actualRange(lastCompletedEndPos+1, GetRange().GetEnd()-1);
3566
3567 // Set relative range so we won't have to change line ranges when paragraphs are moved
3568 line->SetRange(wxRichTextRange(actualRange.GetStart() - GetRange().GetStart(), actualRange.GetEnd() - GetRange().GetStart()));
3569
3570 line->SetPosition(currentPosition);
3571
3572 if (lineHeight == 0 && GetBuffer())
3573 {
3574 wxFont font(GetBuffer()->GetFontTable().FindFont(attr));
3575 wxCheckSetFont(dc, font);
3576 lineHeight = dc.GetCharHeight();
3577 }
3578 if (maxDescent == 0)
3579 {
3580 int w, h;
3581 dc.GetTextExtent(wxT("X"), & w, &h, & maxDescent);
3582 }
3583
3584 line->SetSize(wxSize(currentWidth, lineHeight));
3585 line->SetDescent(maxDescent);
3586 currentPosition.y += lineHeight;
3587 currentPosition.y += lineSpacing;
3588 lineCount ++;
3589 }
3590
3591 // Remove remaining unused line objects, if any
3592 ClearUnusedLines(lineCount);
3593
3594 // Apply styles to wrapped lines
3595 ApplyParagraphStyle(attr, rect, dc);
3596
3597 SetCachedSize(wxSize(maxWidth, currentPosition.y + spaceBeforePara + spaceAfterPara));
3598
3599 m_dirty = false;
3600
3601 #if wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
3602 #if wxRICHTEXT_USE_OPTIMIZED_LINE_DRAWING
3603 // Use the text extents to calculate the size of each fragment in each line
3604 wxRichTextLineList::compatibility_iterator lineNode = m_cachedLines.GetFirst();
3605 while (lineNode)
3606 {
3607 wxRichTextLine* line = lineNode->GetData();
3608 wxRichTextRange lineRange = line->GetAbsoluteRange();
3609
3610 // Loop through objects until we get to the one within range
3611 wxRichTextObjectList::compatibility_iterator node2 = m_children.GetFirst();
3612
3613 while (node2)
3614 {
3615 wxRichTextObject* child = node2->GetData();
3616
3617 if (child->GetRange().GetLength() > 0 && !child->GetRange().IsOutside(lineRange))
3618 {
3619 wxRichTextRange rangeToUse = lineRange;
3620 rangeToUse.LimitTo(child->GetRange());
3621
3622 // Find the size of the child from the text extents, and store in an array
3623 // for drawing later
3624 int left = 0;
3625 if (rangeToUse.GetStart() > GetRange().GetStart())
3626 left = partialExtents[(rangeToUse.GetStart()-1) - GetRange().GetStart()];
3627 int right = partialExtents[rangeToUse.GetEnd() - GetRange().GetStart()];
3628 int sz = right - left;
3629 line->GetObjectSizes().Add(sz);
3630 }
3631 else if (child->GetRange().GetStart() > lineRange.GetEnd())
3632 // Can break out of inner loop now since we've passed this line's range
3633 break;
3634
3635 node2 = node2->GetNext();
3636 }
3637
3638 lineNode = lineNode->GetNext();
3639 }
3640 #endif
3641 #endif
3642
3643 return true;
3644 }
3645
3646 /// Apply paragraph styles, such as centering, to wrapped lines
3647 void wxRichTextParagraph::ApplyParagraphStyle(const wxTextAttr& attr, const wxRect& rect, wxDC& dc)
3648 {
3649 if (!attr.HasAlignment())
3650 return;
3651
3652 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetFirst();
3653 while (node)
3654 {
3655 wxRichTextLine* line = node->GetData();
3656
3657 wxPoint pos = line->GetPosition();
3658 wxSize size = line->GetSize();
3659
3660 // centering, right-justification
3661 if (attr.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_CENTRE)
3662 {
3663 int rightIndent = ConvertTenthsMMToPixels(dc, attr.GetRightIndent());
3664 pos.x = (rect.GetWidth() - pos.x - rightIndent - size.x)/2 + pos.x;
3665 line->SetPosition(pos);
3666 }
3667 else if (attr.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_RIGHT)
3668 {
3669 int rightIndent = ConvertTenthsMMToPixels(dc, attr.GetRightIndent());
3670 pos.x = rect.GetWidth() - size.x - rightIndent;
3671 line->SetPosition(pos);
3672 }
3673
3674 node = node->GetNext();
3675 }
3676 }
3677
3678 /// Insert text at the given position
3679 bool wxRichTextParagraph::InsertText(long pos, const wxString& text)
3680 {
3681 wxRichTextObject* childToUse = NULL;
3682 wxRichTextObjectList::compatibility_iterator nodeToUse = wxRichTextObjectList::compatibility_iterator();
3683
3684 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
3685 while (node)
3686 {
3687 wxRichTextObject* child = node->GetData();
3688 if (child->GetRange().Contains(pos) && child->GetRange().GetLength() > 0)
3689 {
3690 childToUse = child;
3691 nodeToUse = node;
3692 break;
3693 }
3694
3695 node = node->GetNext();
3696 }
3697
3698 if (childToUse)
3699 {
3700 wxRichTextPlainText* textObject = wxDynamicCast(childToUse, wxRichTextPlainText);
3701 if (textObject)
3702 {
3703 int posInString = pos - textObject->GetRange().GetStart();
3704
3705 wxString newText = textObject->GetText().Mid(0, posInString) +
3706 text + textObject->GetText().Mid(posInString);
3707 textObject->SetText(newText);
3708
3709 int textLength = text.length();
3710
3711 textObject->SetRange(wxRichTextRange(textObject->GetRange().GetStart(),
3712 textObject->GetRange().GetEnd() + textLength));
3713
3714 // Increment the end range of subsequent fragments in this paragraph.
3715 // We'll set the paragraph range itself at a higher level.
3716
3717 wxRichTextObjectList::compatibility_iterator node = nodeToUse->GetNext();
3718 while (node)
3719 {
3720 wxRichTextObject* child = node->GetData();
3721 child->SetRange(wxRichTextRange(textObject->GetRange().GetStart() + textLength,
3722 textObject->GetRange().GetEnd() + textLength));
3723
3724 node = node->GetNext();
3725 }
3726
3727 return true;
3728 }
3729 else
3730 {
3731 // TODO: if not a text object, insert at closest position, e.g. in front of it
3732 }
3733 }
3734 else
3735 {
3736 // Add at end.
3737 // Don't pass parent initially to suppress auto-setting of parent range.
3738 // We'll do that at a higher level.
3739 wxRichTextPlainText* textObject = new wxRichTextPlainText(text, this);
3740
3741 AppendChild(textObject);
3742 return true;
3743 }
3744
3745 return false;
3746 }
3747
3748 void wxRichTextParagraph::Copy(const wxRichTextParagraph& obj)
3749 {
3750 wxRichTextBox::Copy(obj);
3751 }
3752
3753 /// Clear the cached lines
3754 void wxRichTextParagraph::ClearLines()
3755 {
3756 WX_CLEAR_LIST(wxRichTextLineList, m_cachedLines);
3757 }
3758
3759 /// Get/set the object size for the given range. Returns false if the range
3760 /// is invalid for this object.
3761 bool wxRichTextParagraph::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, int flags, wxPoint position, wxArrayInt* partialExtents) const
3762 {
3763 if (!range.IsWithin(GetRange()))
3764 return false;
3765
3766 if (flags & wxRICHTEXT_UNFORMATTED)
3767 {
3768 // Just use unformatted data, assume no line breaks
3769 // TODO: take into account line breaks
3770
3771 wxSize sz;
3772
3773 wxArrayInt childExtents;
3774 wxArrayInt* p;
3775 if (partialExtents)
3776 p = & childExtents;
3777 else
3778 p = NULL;
3779
3780 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
3781 while (node)
3782 {
3783
3784 wxRichTextObject* child = node->GetData();
3785 if (!child->GetRange().IsOutside(range))
3786 {
3787 wxSize childSize;
3788
3789 wxRichTextRange rangeToUse = range;
3790 rangeToUse.LimitTo(child->GetRange());
3791 int childDescent = 0;
3792
3793 // At present wxRICHTEXT_HEIGHT_ONLY is only fast if we're already cached the size,
3794 // but it's only going to be used after caching has taken place.
3795 if ((flags & wxRICHTEXT_HEIGHT_ONLY) && child->GetCachedSize().y != 0)
3796 {
3797 childDescent = child->GetDescent();
3798 childSize = child->GetCachedSize();
3799
3800 sz.y = wxMax(sz.y, childSize.y);
3801 sz.x += childSize.x;
3802 descent = wxMax(descent, childDescent);
3803 }
3804 else if (child->GetRangeSize(rangeToUse, childSize, childDescent, dc, flags, wxPoint(position.x + sz.x, position.y), p))
3805 {
3806 sz.y = wxMax(sz.y, childSize.y);
3807 sz.x += childSize.x;
3808 descent = wxMax(descent, childDescent);
3809
3810 if ((flags & wxRICHTEXT_CACHE_SIZE) && (rangeToUse == child->GetRange()))
3811 {
3812 child->SetCachedSize(childSize);
3813 child->SetDescent(childDescent);
3814 }
3815
3816 if (partialExtents)
3817 {
3818 int lastSize;
3819 if (partialExtents->GetCount() > 0)
3820 lastSize = (*partialExtents)[partialExtents->GetCount()-1];
3821 else
3822 lastSize = 0;
3823
3824 size_t i;
3825 for (i = 0; i < childExtents.GetCount(); i++)
3826 {
3827 partialExtents->Add(childExtents[i] + lastSize);
3828 }
3829 }
3830 }
3831
3832 if (p)
3833 p->Clear();
3834 }
3835
3836 node = node->GetNext();
3837 }
3838 size = sz;
3839 }
3840 else
3841 {
3842 // Use formatted data, with line breaks
3843 wxSize sz;
3844
3845 // We're going to loop through each line, and then for each line,
3846 // call GetRangeSize for the fragment that comprises that line.
3847 // Only we have to do that multiple times within the line, because
3848 // the line may be broken into pieces. For now ignore line break commands
3849 // (so we can assume that getting the unformatted size for a fragment
3850 // within a line is the actual size)
3851
3852 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetFirst();
3853 while (node)
3854 {
3855 wxRichTextLine* line = node->GetData();
3856 wxRichTextRange lineRange = line->GetAbsoluteRange();
3857 if (!lineRange.IsOutside(range))
3858 {
3859 wxSize lineSize;
3860
3861 wxRichTextObjectList::compatibility_iterator node2 = m_children.GetFirst();
3862 while (node2)
3863 {
3864 wxRichTextObject* child = node2->GetData();
3865
3866 if (!child->GetRange().IsOutside(lineRange))
3867 {
3868 wxRichTextRange rangeToUse = lineRange;
3869 rangeToUse.LimitTo(child->GetRange());
3870
3871 wxSize childSize;
3872 int childDescent = 0;
3873 if (child->GetRangeSize(rangeToUse, childSize, childDescent, dc, flags, wxPoint(position.x + sz.x, position.y)))
3874 {
3875 lineSize.y = wxMax(lineSize.y, childSize.y);
3876 lineSize.x += childSize.x;
3877 }
3878 descent = wxMax(descent, childDescent);
3879 }
3880
3881 node2 = node2->GetNext();
3882 }
3883
3884 // Increase size by a line (TODO: paragraph spacing)
3885 sz.y += lineSize.y;
3886 sz.x = wxMax(sz.x, lineSize.x);
3887 }
3888 node = node->GetNext();
3889 }
3890 size = sz;
3891 }
3892 return true;
3893 }
3894
3895 /// Finds the absolute position and row height for the given character position
3896 bool wxRichTextParagraph::FindPosition(wxDC& dc, long index, wxPoint& pt, int* height, bool forceLineStart)
3897 {
3898 if (index == -1)
3899 {
3900 wxRichTextLine* line = ((wxRichTextParagraphLayoutBox*)GetParent())->GetLineAtPosition(0);
3901 if (line)
3902 *height = line->GetSize().y;
3903 else
3904 *height = dc.GetCharHeight();
3905
3906 // -1 means 'the start of the buffer'.
3907 pt = GetPosition();
3908 if (line)
3909 pt = pt + line->GetPosition();
3910
3911 return true;
3912 }
3913
3914 // The final position in a paragraph is taken to mean the position
3915 // at the start of the next paragraph.
3916 if (index == GetRange().GetEnd())
3917 {
3918 wxRichTextParagraphLayoutBox* parent = wxDynamicCast(GetParent(), wxRichTextParagraphLayoutBox);
3919 wxASSERT( parent != NULL );
3920
3921 // Find the height at the next paragraph, if any
3922 wxRichTextLine* line = parent->GetLineAtPosition(index + 1);
3923 if (line)
3924 {
3925 *height = line->GetSize().y;
3926 pt = line->GetAbsolutePosition();
3927 }
3928 else
3929 {
3930 *height = dc.GetCharHeight();
3931 int indent = ConvertTenthsMMToPixels(dc, m_attributes.GetLeftIndent());
3932 pt = wxPoint(indent, GetCachedSize().y);
3933 }
3934
3935 return true;
3936 }
3937
3938 if (index < GetRange().GetStart() || index > GetRange().GetEnd())
3939 return false;
3940
3941 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetFirst();
3942 while (node)
3943 {
3944 wxRichTextLine* line = node->GetData();
3945 wxRichTextRange lineRange = line->GetAbsoluteRange();
3946 if (index >= lineRange.GetStart() && index <= lineRange.GetEnd())
3947 {
3948 // If this is the last point in the line, and we're forcing the
3949 // returned value to be the start of the next line, do the required
3950 // thing.
3951 if (index == lineRange.GetEnd() && forceLineStart)
3952 {
3953 if (node->GetNext())
3954 {
3955 wxRichTextLine* nextLine = node->GetNext()->GetData();
3956 *height = nextLine->GetSize().y;
3957 pt = nextLine->GetAbsolutePosition();
3958 return true;
3959 }
3960 }
3961
3962 pt.y = line->GetPosition().y + GetPosition().y;
3963
3964 wxRichTextRange r(lineRange.GetStart(), index);
3965 wxSize rangeSize;
3966 int descent = 0;
3967
3968 // We find the size of the line up to this point,
3969 // then we can add this size to the line start position and
3970 // paragraph start position to find the actual position.
3971
3972 if (GetRangeSize(r, rangeSize, descent, dc, wxRICHTEXT_UNFORMATTED, line->GetPosition()+ GetPosition()))
3973 {
3974 pt.x = line->GetPosition().x + GetPosition().x + rangeSize.x;
3975 *height = line->GetSize().y;
3976
3977 return true;
3978 }
3979
3980 }
3981
3982 node = node->GetNext();
3983 }
3984
3985 return false;
3986 }
3987
3988 /// Hit-testing: returns a flag indicating hit test details, plus
3989 /// information about position
3990 int wxRichTextParagraph::HitTest(wxDC& dc, const wxPoint& pt, long& textPosition)
3991 {
3992 wxPoint paraPos = GetPosition();
3993
3994 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetFirst();
3995 while (node)
3996 {
3997 wxRichTextLine* line = node->GetData();
3998 wxPoint linePos = paraPos + line->GetPosition();
3999 wxSize lineSize = line->GetSize();
4000 wxRichTextRange lineRange = line->GetAbsoluteRange();
4001
4002 if (pt.y <= linePos.y + lineSize.y)
4003 {
4004 if (pt.x < linePos.x)
4005 {
4006 textPosition = lineRange.GetStart();
4007 return wxRICHTEXT_HITTEST_BEFORE|wxRICHTEXT_HITTEST_OUTSIDE;
4008 }
4009 else if (pt.x >= (linePos.x + lineSize.x))
4010 {
4011 textPosition = lineRange.GetEnd();
4012 return wxRICHTEXT_HITTEST_AFTER|wxRICHTEXT_HITTEST_OUTSIDE;
4013 }
4014 else
4015 {
4016 #if wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
4017 wxArrayInt partialExtents;
4018
4019 wxSize paraSize;
4020 int paraDescent;
4021
4022 // This calculates the partial text extents
4023 GetRangeSize(lineRange, paraSize, paraDescent, dc, wxRICHTEXT_UNFORMATTED, wxPoint(0,0), & partialExtents);
4024
4025 int lastX = linePos.x;
4026 size_t i;
4027 for (i = 0; i < partialExtents.GetCount(); i++)
4028 {
4029 int nextX = partialExtents[i] + linePos.x;
4030
4031 if (pt.x >= lastX && pt.x <= nextX)
4032 {
4033 textPosition = i + lineRange.GetStart(); // minus 1?
4034
4035 // So now we know it's between i-1 and i.
4036 // Let's see if we can be more precise about
4037 // which side of the position it's on.
4038
4039 int midPoint = (nextX - lastX)/2 + lastX;
4040 if (pt.x >= midPoint)
4041 return wxRICHTEXT_HITTEST_AFTER;
4042 else
4043 return wxRICHTEXT_HITTEST_BEFORE;
4044 }
4045
4046 lastX = nextX;
4047 }
4048 #else
4049 long i;
4050 int lastX = linePos.x;
4051 for (i = lineRange.GetStart(); i <= lineRange.GetEnd(); i++)
4052 {
4053 wxSize childSize;
4054 int descent = 0;
4055
4056 wxRichTextRange rangeToUse(lineRange.GetStart(), i);
4057
4058 GetRangeSize(rangeToUse, childSize, descent, dc, wxRICHTEXT_UNFORMATTED, linePos);
4059
4060 int nextX = childSize.x + linePos.x;
4061
4062 if (pt.x >= lastX && pt.x <= nextX)
4063 {
4064 textPosition = i;
4065
4066 // So now we know it's between i-1 and i.
4067 // Let's see if we can be more precise about
4068 // which side of the position it's on.
4069
4070 int midPoint = (nextX - lastX)/2 + lastX;
4071 if (pt.x >= midPoint)
4072 return wxRICHTEXT_HITTEST_AFTER;
4073 else
4074 return wxRICHTEXT_HITTEST_BEFORE;
4075 }
4076 else
4077 {
4078 lastX = nextX;
4079 }
4080 }
4081 #endif
4082 }
4083 }
4084
4085 node = node->GetNext();
4086 }
4087
4088 return wxRICHTEXT_HITTEST_NONE;
4089 }
4090
4091 /// Split an object at this position if necessary, and return
4092 /// the previous object, or NULL if inserting at beginning.
4093 wxRichTextObject* wxRichTextParagraph::SplitAt(long pos, wxRichTextObject** previousObject)
4094 {
4095 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
4096 while (node)
4097 {
4098 wxRichTextObject* child = node->GetData();
4099
4100 if (pos == child->GetRange().GetStart())
4101 {
4102 if (previousObject)
4103 {
4104 if (node->GetPrevious())
4105 *previousObject = node->GetPrevious()->GetData();
4106 else
4107 *previousObject = NULL;
4108 }
4109
4110 return child;
4111 }
4112
4113 if (child->GetRange().Contains(pos))
4114 {
4115 // This should create a new object, transferring part of
4116 // the content to the old object and the rest to the new object.
4117 wxRichTextObject* newObject = child->DoSplit(pos);
4118
4119 // If we couldn't split this object, just insert in front of it.
4120 if (!newObject)
4121 {
4122 // Maybe this is an empty string, try the next one
4123 // return child;
4124 }
4125 else
4126 {
4127 // Insert the new object after 'child'
4128 if (node->GetNext())
4129 m_children.Insert(node->GetNext(), newObject);
4130 else
4131 m_children.Append(newObject);
4132 newObject->SetParent(this);
4133
4134 if (previousObject)
4135 *previousObject = child;
4136
4137 return newObject;
4138 }
4139 }
4140
4141 node = node->GetNext();
4142 }
4143 if (previousObject)
4144 *previousObject = NULL;
4145 return NULL;
4146 }
4147
4148 /// Move content to a list from obj on
4149 void wxRichTextParagraph::MoveToList(wxRichTextObject* obj, wxList& list)
4150 {
4151 wxRichTextObjectList::compatibility_iterator node = m_children.Find(obj);
4152 while (node)
4153 {
4154 wxRichTextObject* child = node->GetData();
4155 list.Append(child);
4156
4157 wxRichTextObjectList::compatibility_iterator oldNode = node;
4158
4159 node = node->GetNext();
4160
4161 m_children.DeleteNode(oldNode);
4162 }
4163 }
4164
4165 /// Add content back from list
4166 void wxRichTextParagraph::MoveFromList(wxList& list)
4167 {
4168 for (wxList::compatibility_iterator node = list.GetFirst(); node; node = node->GetNext())
4169 {
4170 AppendChild((wxRichTextObject*) node->GetData());
4171 }
4172 }
4173
4174 /// Calculate range
4175 void wxRichTextParagraph::CalculateRange(long start, long& end)
4176 {
4177 wxRichTextCompositeObject::CalculateRange(start, end);
4178
4179 // Add one for end of paragraph
4180 end ++;
4181
4182 m_range.SetRange(start, end);
4183 }
4184
4185 /// Find the object at the given position
4186 wxRichTextObject* wxRichTextParagraph::FindObjectAtPosition(long position)
4187 {
4188 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
4189 while (node)
4190 {
4191 wxRichTextObject* obj = node->GetData();
4192 if (obj->GetRange().Contains(position))
4193 return obj;
4194
4195 node = node->GetNext();
4196 }
4197 return NULL;
4198 }
4199
4200 /// Get the plain text searching from the start or end of the range.
4201 /// The resulting string may be shorter than the range given.
4202 bool wxRichTextParagraph::GetContiguousPlainText(wxString& text, const wxRichTextRange& range, bool fromStart)
4203 {
4204 text = wxEmptyString;
4205
4206 if (fromStart)
4207 {
4208 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
4209 while (node)
4210 {
4211 wxRichTextObject* obj = node->GetData();
4212 if (!obj->GetRange().IsOutside(range))
4213 {
4214 wxRichTextPlainText* textObj = wxDynamicCast(obj, wxRichTextPlainText);
4215 if (textObj)
4216 {
4217 text += textObj->GetTextForRange(range);
4218 }
4219 else
4220 {
4221 text += wxT(" ");
4222 }
4223 }
4224
4225 node = node->GetNext();
4226 }
4227 }
4228 else
4229 {
4230 wxRichTextObjectList::compatibility_iterator node = m_children.GetLast();
4231 while (node)
4232 {
4233 wxRichTextObject* obj = node->GetData();
4234 if (!obj->GetRange().IsOutside(range))
4235 {
4236 wxRichTextPlainText* textObj = wxDynamicCast(obj, wxRichTextPlainText);
4237 if (textObj)
4238 {
4239 text = textObj->GetTextForRange(range) + text;
4240 }
4241 else
4242 {
4243 text = wxT(" ") + text;
4244 }
4245 }
4246
4247 node = node->GetPrevious();
4248 }
4249 }
4250
4251 return true;
4252 }
4253
4254 /// Find a suitable wrap position.
4255 bool wxRichTextParagraph::FindWrapPosition(const wxRichTextRange& range, wxDC& dc, int availableSpace, long& wrapPosition, wxArrayInt* partialExtents)
4256 {
4257 if (range.GetLength() <= 0)
4258 return false;
4259
4260 // Find the first position where the line exceeds the available space.
4261 wxSize sz;
4262 long breakPosition = range.GetEnd();
4263
4264 #if wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
4265 if (partialExtents && partialExtents->GetCount() >= (size_t) (GetRange().GetLength()-1)) // the final position in a paragraph is the newline
4266 {
4267 int widthBefore;
4268
4269 if (range.GetStart() > GetRange().GetStart())
4270 widthBefore = (*partialExtents)[range.GetStart() - GetRange().GetStart() - 1];
4271 else
4272 widthBefore = 0;
4273
4274 size_t i;
4275 for (i = (size_t) range.GetStart(); i <= (size_t) range.GetEnd(); i++)
4276 {
4277 int widthFromStartOfThisRange = (*partialExtents)[i - GetRange().GetStart()] - widthBefore;
4278
4279 if (widthFromStartOfThisRange > availableSpace)
4280 {
4281 breakPosition = i-1;
4282 break;
4283 }
4284 }
4285 }
4286 else
4287 #endif
4288 {
4289 // Binary chop for speed
4290 long minPos = range.GetStart();
4291 long maxPos = range.GetEnd();
4292 while (true)
4293 {
4294 if (minPos == maxPos)
4295 {
4296 int descent = 0;
4297 GetRangeSize(wxRichTextRange(range.GetStart(), minPos), sz, descent, dc, wxRICHTEXT_UNFORMATTED);
4298
4299 if (sz.x > availableSpace)
4300 breakPosition = minPos - 1;
4301 break;
4302 }
4303 else if ((maxPos - minPos) == 1)
4304 {
4305 int descent = 0;
4306 GetRangeSize(wxRichTextRange(range.GetStart(), minPos), sz, descent, dc, wxRICHTEXT_UNFORMATTED);
4307
4308 if (sz.x > availableSpace)
4309 breakPosition = minPos - 1;
4310 else
4311 {
4312 GetRangeSize(wxRichTextRange(range.GetStart(), maxPos), sz, descent, dc, wxRICHTEXT_UNFORMATTED);
4313 if (sz.x > availableSpace)
4314 breakPosition = maxPos-1;
4315 }
4316 break;
4317 }
4318 else
4319 {
4320 long nextPos = minPos + ((maxPos - minPos) / 2);
4321
4322 int descent = 0;
4323 GetRangeSize(wxRichTextRange(range.GetStart(), nextPos), sz, descent, dc, wxRICHTEXT_UNFORMATTED);
4324
4325 if (sz.x > availableSpace)
4326 {
4327 maxPos = nextPos;
4328 }
4329 else
4330 {
4331 minPos = nextPos;
4332 }
4333 }
4334 }
4335 }
4336
4337 // Now we know the last position on the line.
4338 // Let's try to find a word break.
4339
4340 wxString plainText;
4341 if (GetContiguousPlainText(plainText, wxRichTextRange(range.GetStart(), breakPosition), false))
4342 {
4343 int newLinePos = plainText.Find(wxRichTextLineBreakChar);
4344 if (newLinePos != wxNOT_FOUND)
4345 {
4346 breakPosition = wxMax(0, range.GetStart() + newLinePos);
4347 }
4348 else
4349 {
4350 int spacePos = plainText.Find(wxT(' '), true);
4351 int tabPos = plainText.Find(wxT('\t'), true);
4352 int pos = wxMax(spacePos, tabPos);
4353 if (pos != wxNOT_FOUND)
4354 {
4355 int positionsFromEndOfString = plainText.length() - pos - 1;
4356 breakPosition = breakPosition - positionsFromEndOfString;
4357 }
4358 }
4359 }
4360
4361 wrapPosition = breakPosition;
4362
4363 return true;
4364 }
4365
4366 /// Get the bullet text for this paragraph.
4367 wxString wxRichTextParagraph::GetBulletText()
4368 {
4369 if (GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE ||
4370 (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP))
4371 return wxEmptyString;
4372
4373 int number = GetAttributes().GetBulletNumber();
4374
4375 wxString text;
4376 if ((GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ARABIC) || (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE))
4377 {
4378 text.Printf(wxT("%d"), number);
4379 }
4380 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER)
4381 {
4382 // TODO: Unicode, and also check if number > 26
4383 text.Printf(wxT("%c"), (wxChar) (number+64));
4384 }
4385 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER)
4386 {
4387 // TODO: Unicode, and also check if number > 26
4388 text.Printf(wxT("%c"), (wxChar) (number+96));
4389 }
4390 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER)
4391 {
4392 text = wxRichTextDecimalToRoman(number);
4393 }
4394 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER)
4395 {
4396 text = wxRichTextDecimalToRoman(number);
4397 text.MakeLower();
4398 }
4399 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL)
4400 {
4401 text = GetAttributes().GetBulletText();
4402 }
4403
4404 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE)
4405 {
4406 // The outline style relies on the text being computed statically,
4407 // since it depends on other levels points (e.g. 1.2.1.1). So normally the bullet text
4408 // should be stored in the attributes; if not, just use the number for this
4409 // level, as previously computed.
4410 if (!GetAttributes().GetBulletText().IsEmpty())
4411 text = GetAttributes().GetBulletText();
4412 }
4413
4414 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PARENTHESES)
4415 {
4416 text = wxT("(") + text + wxT(")");
4417 }
4418 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS)
4419 {
4420 text = text + wxT(")");
4421 }
4422
4423 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PERIOD)
4424 {
4425 text += wxT(".");
4426 }
4427
4428 return text;
4429 }
4430
4431 /// Allocate or reuse a line object
4432 wxRichTextLine* wxRichTextParagraph::AllocateLine(int pos)
4433 {
4434 if (pos < (int) m_cachedLines.GetCount())
4435 {
4436 wxRichTextLine* line = m_cachedLines.Item(pos)->GetData();
4437 line->Init(this);
4438 return line;
4439 }
4440 else
4441 {
4442 wxRichTextLine* line = new wxRichTextLine(this);
4443 m_cachedLines.Append(line);
4444 return line;
4445 }
4446 }
4447
4448 /// Clear remaining unused line objects, if any
4449 bool wxRichTextParagraph::ClearUnusedLines(int lineCount)
4450 {
4451 int cachedLineCount = m_cachedLines.GetCount();
4452 if ((int) cachedLineCount > lineCount)
4453 {
4454 for (int i = 0; i < (int) (cachedLineCount - lineCount); i ++)
4455 {
4456 wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetLast();
4457 wxRichTextLine* line = node->GetData();
4458 m_cachedLines.Erase(node);
4459 delete line;
4460 }
4461 }
4462 return true;
4463 }
4464
4465 /// Get combined attributes of the base style, paragraph style and character style. We use this to dynamically
4466 /// retrieve the actual style.
4467 wxTextAttr wxRichTextParagraph::GetCombinedAttributes(const wxTextAttr& contentStyle) const
4468 {
4469 wxTextAttr attr;
4470 wxRichTextBuffer* buf = wxDynamicCast(GetParent(), wxRichTextBuffer);
4471 if (buf)
4472 {
4473 attr = buf->GetBasicStyle();
4474 wxRichTextApplyStyle(attr, GetAttributes());
4475 }
4476 else
4477 attr = GetAttributes();
4478
4479 wxRichTextApplyStyle(attr, contentStyle);
4480 return attr;
4481 }
4482
4483 /// Get combined attributes of the base style and paragraph style.
4484 wxTextAttr wxRichTextParagraph::GetCombinedAttributes() const
4485 {
4486 wxTextAttr attr;
4487 wxRichTextBuffer* buf = wxDynamicCast(GetParent(), wxRichTextBuffer);
4488 if (buf)
4489 {
4490 attr = buf->GetBasicStyle();
4491 wxRichTextApplyStyle(attr, GetAttributes());
4492 }
4493 else
4494 attr = GetAttributes();
4495
4496 return attr;
4497 }
4498
4499 /// Create default tabstop array
4500 void wxRichTextParagraph::InitDefaultTabs()
4501 {
4502 // create a default tab list at 10 mm each.
4503 for (int i = 0; i < 20; ++i)
4504 {
4505 sm_defaultTabs.Add(i*100);
4506 }
4507 }
4508
4509 /// Clear default tabstop array
4510 void wxRichTextParagraph::ClearDefaultTabs()
4511 {
4512 sm_defaultTabs.Clear();
4513 }
4514
4515 /// Get the first position from pos that has a line break character.
4516 long wxRichTextParagraph::GetFirstLineBreakPosition(long pos)
4517 {
4518 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
4519 while (node)
4520 {
4521 wxRichTextObject* obj = node->GetData();
4522 if (pos >= obj->GetRange().GetStart() && pos <= obj->GetRange().GetEnd())
4523 {
4524 wxRichTextPlainText* textObj = wxDynamicCast(obj, wxRichTextPlainText);
4525 if (textObj)
4526 {
4527 long breakPos = textObj->GetFirstLineBreakPosition(pos);
4528 if (breakPos > -1)
4529 return breakPos;
4530 }
4531 }
4532 node = node->GetNext();
4533 }
4534 return -1;
4535 }
4536
4537 /*!
4538 * wxRichTextLine
4539 * This object represents a line in a paragraph, and stores
4540 * offsets from the start of the paragraph representing the
4541 * start and end positions of the line.
4542 */
4543
4544 wxRichTextLine::wxRichTextLine(wxRichTextParagraph* parent)
4545 {
4546 Init(parent);
4547 }
4548
4549 /// Initialisation
4550 void wxRichTextLine::Init(wxRichTextParagraph* parent)
4551 {
4552 m_parent = parent;
4553 m_range.SetRange(-1, -1);
4554 m_pos = wxPoint(0, 0);
4555 m_size = wxSize(0, 0);
4556 m_descent = 0;
4557 #if wxRICHTEXT_USE_OPTIMIZED_LINE_DRAWING
4558 m_objectSizes.Clear();
4559 #endif
4560 }
4561
4562 /// Copy
4563 void wxRichTextLine::Copy(const wxRichTextLine& obj)
4564 {
4565 m_range = obj.m_range;
4566 #if wxRICHTEXT_USE_OPTIMIZED_LINE_DRAWING
4567 m_objectSizes = obj.m_objectSizes;
4568 #endif
4569 }
4570
4571 /// Get the absolute object position
4572 wxPoint wxRichTextLine::GetAbsolutePosition() const
4573 {
4574 return m_parent->GetPosition() + m_pos;
4575 }
4576
4577 /// Get the absolute range
4578 wxRichTextRange wxRichTextLine::GetAbsoluteRange() const
4579 {
4580 wxRichTextRange range(m_range.GetStart() + m_parent->GetRange().GetStart(), 0);
4581 range.SetEnd(range.GetStart() + m_range.GetLength()-1);
4582 return range;
4583 }
4584
4585 /*!
4586 * wxRichTextPlainText
4587 * This object represents a single piece of text.
4588 */
4589
4590 IMPLEMENT_DYNAMIC_CLASS(wxRichTextPlainText, wxRichTextObject)
4591
4592 wxRichTextPlainText::wxRichTextPlainText(const wxString& text, wxRichTextObject* parent, wxTextAttr* style):
4593 wxRichTextObject(parent)
4594 {
4595 if (style)
4596 SetAttributes(*style);
4597
4598 m_text = text;
4599 }
4600
4601 #define USE_KERNING_FIX 1
4602
4603 // If insufficient tabs are defined, this is the tab width used
4604 #define WIDTH_FOR_DEFAULT_TABS 50
4605
4606 /// Draw the item
4607 bool wxRichTextPlainText::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextRange& selectionRange, const wxRect& rect, int descent, int WXUNUSED(style))
4608 {
4609 wxRichTextParagraph* para = wxDynamicCast(GetParent(), wxRichTextParagraph);
4610 wxASSERT (para != NULL);
4611
4612 wxTextAttr textAttr(para ? para->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4613
4614 int offset = GetRange().GetStart();
4615
4616 // Replace line break characters with spaces
4617 wxString str = m_text;
4618 wxString toRemove = wxRichTextLineBreakChar;
4619 str.Replace(toRemove, wxT(" "));
4620 if (textAttr.HasTextEffects() && (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS))
4621 str.MakeUpper();
4622
4623 long len = range.GetLength();
4624 wxString stringChunk = str.Mid(range.GetStart() - offset, (size_t) len);
4625
4626 // Test for the optimized situations where all is selected, or none
4627 // is selected.
4628
4629 wxFont textFont(GetBuffer()->GetFontTable().FindFont(textAttr));
4630 wxCheckSetFont(dc, textFont);
4631 int charHeight = dc.GetCharHeight();
4632
4633 int x, y;
4634 if ( textFont.Ok() )
4635 {
4636 if ( textAttr.HasTextEffects() && (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUPERSCRIPT) )
4637 {
4638 double size = static_cast<double>(textFont.GetPointSize()) / wxSCRIPT_MUL_FACTOR;
4639 textFont.SetPointSize( static_cast<int>(size) );
4640 x = rect.x;
4641 y = rect.y;
4642 wxCheckSetFont(dc, textFont);
4643 }
4644 else if ( textAttr.HasTextEffects() && (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUBSCRIPT) )
4645 {
4646 double size = static_cast<double>(textFont.GetPointSize()) / wxSCRIPT_MUL_FACTOR;
4647 textFont.SetPointSize( static_cast<int>(size) );
4648 x = rect.x;
4649 int sub_height = static_cast<int>( static_cast<double>(charHeight) / wxSCRIPT_MUL_FACTOR);
4650 y = rect.y + (rect.height - sub_height + (descent - m_descent));
4651 wxCheckSetFont(dc, textFont);
4652 }
4653 else
4654 {
4655 x = rect.x;
4656 y = rect.y + (rect.height - charHeight - (descent - m_descent));
4657 }
4658 }
4659 else
4660 {
4661 x = rect.x;
4662 y = rect.y + (rect.height - charHeight - (descent - m_descent));
4663 }
4664
4665 // (a) All selected.
4666 if (selectionRange.GetStart() <= range.GetStart() && selectionRange.GetEnd() >= range.GetEnd())
4667 {
4668 DrawTabbedString(dc, textAttr, rect, stringChunk, x, y, true);
4669 }
4670 // (b) None selected.
4671 else if (selectionRange.GetEnd() < range.GetStart() || selectionRange.GetStart() > range.GetEnd())
4672 {
4673 // Draw all unselected
4674 DrawTabbedString(dc, textAttr, rect, stringChunk, x, y, false);
4675 }
4676 else
4677 {
4678 // (c) Part selected, part not
4679 // Let's draw unselected chunk, selected chunk, then unselected chunk.
4680
4681 dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT);
4682
4683 // 1. Initial unselected chunk, if any, up until start of selection.
4684 if (selectionRange.GetStart() > range.GetStart() && selectionRange.GetStart() <= range.GetEnd())
4685 {
4686 int r1 = range.GetStart();
4687 int s1 = selectionRange.GetStart()-1;
4688 int fragmentLen = s1 - r1 + 1;
4689 if (fragmentLen < 0)
4690 {
4691 wxLogDebug(wxT("Mid(%d, %d"), (int)(r1 - offset), (int)fragmentLen);
4692 }
4693 wxString stringFragment = str.Mid(r1 - offset, fragmentLen);
4694
4695 DrawTabbedString(dc, textAttr, rect, stringFragment, x, y, false);
4696
4697 #if USE_KERNING_FIX
4698 if (stringChunk.Find(wxT("\t")) == wxNOT_FOUND)
4699 {
4700 // Compensate for kerning difference
4701 wxString stringFragment2(str.Mid(r1 - offset, fragmentLen+1));
4702 wxString stringFragment3(str.Mid(r1 - offset + fragmentLen, 1));
4703
4704 wxCoord w1, h1, w2, h2, w3, h3;
4705 dc.GetTextExtent(stringFragment, & w1, & h1);
4706 dc.GetTextExtent(stringFragment2, & w2, & h2);
4707 dc.GetTextExtent(stringFragment3, & w3, & h3);
4708
4709 int kerningDiff = (w1 + w3) - w2;
4710 x = x - kerningDiff;
4711 }
4712 #endif
4713 }
4714
4715 // 2. Selected chunk, if any.
4716 if (selectionRange.GetEnd() >= range.GetStart())
4717 {
4718 int s1 = wxMax(selectionRange.GetStart(), range.GetStart());
4719 int s2 = wxMin(selectionRange.GetEnd(), range.GetEnd());
4720
4721 int fragmentLen = s2 - s1 + 1;
4722 if (fragmentLen < 0)
4723 {
4724 wxLogDebug(wxT("Mid(%d, %d"), (int)(s1 - offset), (int)fragmentLen);
4725 }
4726 wxString stringFragment = str.Mid(s1 - offset, fragmentLen);
4727
4728 DrawTabbedString(dc, textAttr, rect, stringFragment, x, y, true);
4729
4730 #if USE_KERNING_FIX
4731 if (stringChunk.Find(wxT("\t")) == wxNOT_FOUND)
4732 {
4733 // Compensate for kerning difference
4734 wxString stringFragment2(str.Mid(s1 - offset, fragmentLen+1));
4735 wxString stringFragment3(str.Mid(s1 - offset + fragmentLen, 1));
4736
4737 wxCoord w1, h1, w2, h2, w3, h3;
4738 dc.GetTextExtent(stringFragment, & w1, & h1);
4739 dc.GetTextExtent(stringFragment2, & w2, & h2);
4740 dc.GetTextExtent(stringFragment3, & w3, & h3);
4741
4742 int kerningDiff = (w1 + w3) - w2;
4743 x = x - kerningDiff;
4744 }
4745 #endif
4746 }
4747
4748 // 3. Remaining unselected chunk, if any
4749 if (selectionRange.GetEnd() < range.GetEnd())
4750 {
4751 int s2 = wxMin(selectionRange.GetEnd()+1, range.GetEnd());
4752 int r2 = range.GetEnd();
4753
4754 int fragmentLen = r2 - s2 + 1;
4755 if (fragmentLen < 0)
4756 {
4757 wxLogDebug(wxT("Mid(%d, %d"), (int)(s2 - offset), (int)fragmentLen);
4758 }
4759 wxString stringFragment = str.Mid(s2 - offset, fragmentLen);
4760
4761 DrawTabbedString(dc, textAttr, rect, stringFragment, x, y, false);
4762 }
4763 }
4764
4765 return true;
4766 }
4767
4768 bool wxRichTextPlainText::DrawTabbedString(wxDC& dc, const wxTextAttr& attr, const wxRect& rect,wxString& str, wxCoord& x, wxCoord& y, bool selected)
4769 {
4770 bool hasTabs = (str.Find(wxT('\t')) != wxNOT_FOUND);
4771
4772 wxArrayInt tabArray;
4773 int tabCount;
4774 if (hasTabs)
4775 {
4776 if (attr.GetTabs().IsEmpty())
4777 tabArray = wxRichTextParagraph::GetDefaultTabs();
4778 else
4779 tabArray = attr.GetTabs();
4780 tabCount = tabArray.GetCount();
4781
4782 for (int i = 0; i < tabCount; ++i)
4783 {
4784 int pos = tabArray[i];
4785 pos = ConvertTenthsMMToPixels(dc, pos);
4786 tabArray[i] = pos;
4787 }
4788 }
4789 else
4790 tabCount = 0;
4791
4792 int nextTabPos = -1;
4793 int tabPos = -1;
4794 wxCoord w, h;
4795
4796 if (selected)
4797 {
4798 wxColour highlightColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT));
4799 wxColour highlightTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT));
4800
4801 wxCheckSetBrush(dc, wxBrush(highlightColour));
4802 wxCheckSetPen(dc, wxPen(highlightColour));
4803 dc.SetTextForeground(highlightTextColour);
4804 dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT);
4805 }
4806 else
4807 {
4808 dc.SetTextForeground(attr.GetTextColour());
4809
4810 if (attr.HasFlag(wxTEXT_ATTR_BACKGROUND_COLOUR) && attr.GetBackgroundColour().IsOk())
4811 {
4812 dc.SetBackgroundMode(wxBRUSHSTYLE_SOLID);
4813 dc.SetTextBackground(attr.GetBackgroundColour());
4814 }
4815 else
4816 dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT);
4817 }
4818
4819 wxCoord x_orig = x;
4820 while (hasTabs)
4821 {
4822 // the string has a tab
4823 // break up the string at the Tab
4824 wxString stringChunk = str.BeforeFirst(wxT('\t'));
4825 str = str.AfterFirst(wxT('\t'));
4826 dc.GetTextExtent(stringChunk, & w, & h);
4827 tabPos = x + w;
4828 bool not_found = true;
4829 for (int i = 0; i < tabCount && not_found; ++i)
4830 {
4831 nextTabPos = tabArray.Item(i) + x_orig;
4832
4833 // Find the next tab position.
4834 // Even if we're at the end of the tab array, we must still draw the chunk.
4835
4836 if (nextTabPos > tabPos || (i == (tabCount - 1)))
4837 {
4838 if (nextTabPos <= tabPos)
4839 {
4840 int defaultTabWidth = ConvertTenthsMMToPixels(dc, WIDTH_FOR_DEFAULT_TABS);
4841 nextTabPos = tabPos + defaultTabWidth;
4842 }
4843
4844 not_found = false;
4845 if (selected)
4846 {
4847 w = nextTabPos - x;
4848 wxRect selRect(x, rect.y, w, rect.GetHeight());
4849 dc.DrawRectangle(selRect);
4850 }
4851 dc.DrawText(stringChunk, x, y);
4852
4853 if (attr.HasTextEffects() && (attr.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH))
4854 {
4855 wxPen oldPen = dc.GetPen();
4856 wxCheckSetPen(dc, wxPen(attr.GetTextColour(), 1));
4857 dc.DrawLine(x, (int) (y+(h/2)+0.5), x+w, (int) (y+(h/2)+0.5));
4858 wxCheckSetPen(dc, oldPen);
4859 }
4860
4861 x = nextTabPos;
4862 }
4863 }
4864 hasTabs = (str.Find(wxT('\t')) != wxNOT_FOUND);
4865 }
4866
4867 if (!str.IsEmpty())
4868 {
4869 dc.GetTextExtent(str, & w, & h);
4870 if (selected)
4871 {
4872 wxRect selRect(x, rect.y, w, rect.GetHeight());
4873 dc.DrawRectangle(selRect);
4874 }
4875 dc.DrawText(str, x, y);
4876
4877 if (attr.HasTextEffects() && (attr.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH))
4878 {
4879 wxPen oldPen = dc.GetPen();
4880 wxCheckSetPen(dc, wxPen(attr.GetTextColour(), 1));
4881 dc.DrawLine(x, (int) (y+(h/2)+0.5), x+w, (int) (y+(h/2)+0.5));
4882 wxCheckSetPen(dc, oldPen);
4883 }
4884
4885 x += w;
4886 }
4887 return true;
4888
4889 }
4890
4891 /// Lay the item out
4892 bool wxRichTextPlainText::Layout(wxDC& dc, const wxRect& WXUNUSED(rect), int WXUNUSED(style))
4893 {
4894 // Only lay out if we haven't already cached the size
4895 if (m_size.x == -1)
4896 GetRangeSize(GetRange(), m_size, m_descent, dc, 0, wxPoint(0, 0));
4897
4898 return true;
4899 }
4900
4901 /// Copy
4902 void wxRichTextPlainText::Copy(const wxRichTextPlainText& obj)
4903 {
4904 wxRichTextObject::Copy(obj);
4905
4906 m_text = obj.m_text;
4907 }
4908
4909 /// Get/set the object size for the given range. Returns false if the range
4910 /// is invalid for this object.
4911 bool wxRichTextPlainText::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, int WXUNUSED(flags), wxPoint position, wxArrayInt* partialExtents) const
4912 {
4913 if (!range.IsWithin(GetRange()))
4914 return false;
4915
4916 wxRichTextParagraph* para = wxDynamicCast(GetParent(), wxRichTextParagraph);
4917 wxASSERT (para != NULL);
4918
4919 wxTextAttr textAttr(para ? para->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4920
4921 // Always assume unformatted text, since at this level we have no knowledge
4922 // of line breaks - and we don't need it, since we'll calculate size within
4923 // formatted text by doing it in chunks according to the line ranges
4924
4925 bool bScript(false);
4926 wxFont font(GetBuffer()->GetFontTable().FindFont(textAttr));
4927 if (font.Ok())
4928 {
4929 if ( textAttr.HasTextEffects() && ( (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUPERSCRIPT)
4930 || (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUBSCRIPT) ) )
4931 {
4932 wxFont textFont = font;
4933 double size = static_cast<double>(textFont.GetPointSize()) / wxSCRIPT_MUL_FACTOR;
4934 textFont.SetPointSize( static_cast<int>(size) );
4935 wxCheckSetFont(dc, textFont);
4936 bScript = true;
4937 }
4938 else
4939 {
4940 wxCheckSetFont(dc, font);
4941 }
4942 }
4943
4944 bool haveDescent = false;
4945 int startPos = range.GetStart() - GetRange().GetStart();
4946 long len = range.GetLength();
4947
4948 wxString str(m_text);
4949 wxString toReplace = wxRichTextLineBreakChar;
4950 str.Replace(toReplace, wxT(" "));
4951
4952 wxString stringChunk = str.Mid(startPos, (size_t) len);
4953
4954 if (textAttr.HasTextEffects() && (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS))
4955 stringChunk.MakeUpper();
4956
4957 wxCoord w, h;
4958 int width = 0;
4959 if (stringChunk.Find(wxT('\t')) != wxNOT_FOUND)
4960 {
4961 // the string has a tab
4962 wxArrayInt tabArray;
4963 if (textAttr.GetTabs().IsEmpty())
4964 tabArray = wxRichTextParagraph::GetDefaultTabs();
4965 else
4966 tabArray = textAttr.GetTabs();
4967
4968 int tabCount = tabArray.GetCount();
4969
4970 for (int i = 0; i < tabCount; ++i)
4971 {
4972 int pos = tabArray[i];
4973 pos = ((wxRichTextPlainText*) this)->ConvertTenthsMMToPixels(dc, pos);
4974 tabArray[i] = pos;
4975 }
4976
4977 int nextTabPos = -1;
4978
4979 while (stringChunk.Find(wxT('\t')) >= 0)
4980 {
4981 int absoluteWidth = 0;
4982
4983 // the string has a tab
4984 // break up the string at the Tab
4985 wxString stringFragment = stringChunk.BeforeFirst(wxT('\t'));
4986 stringChunk = stringChunk.AfterFirst(wxT('\t'));
4987
4988 if (partialExtents)
4989 {
4990 int oldWidth;
4991 if (partialExtents->GetCount() > 0)
4992 oldWidth = (*partialExtents)[partialExtents->GetCount()-1];
4993 else
4994 oldWidth = 0;
4995
4996 // Add these partial extents
4997 wxArrayInt p;
4998 dc.GetPartialTextExtents(stringFragment, p);
4999 size_t j;
5000 for (j = 0; j < p.GetCount(); j++)
5001 partialExtents->Add(oldWidth + p[j]);
5002
5003 if (partialExtents->GetCount() > 0)
5004 absoluteWidth = (*partialExtents)[(*partialExtents).GetCount()-1] + position.x;
5005 else
5006 absoluteWidth = position.x;
5007 }
5008 else
5009 {
5010 dc.GetTextExtent(stringFragment, & w, & h);
5011 width += w;
5012 absoluteWidth = width + position.x;
5013 haveDescent = true;
5014 }
5015
5016 bool notFound = true;
5017 for (int i = 0; i < tabCount && notFound; ++i)
5018 {
5019 nextTabPos = tabArray.Item(i);
5020
5021 // Find the next tab position.
5022 // Even if we're at the end of the tab array, we must still process the chunk.
5023
5024 if (nextTabPos > absoluteWidth || (i == (tabCount - 1)))
5025 {
5026 if (nextTabPos <= absoluteWidth)
5027 {
5028 int defaultTabWidth = ((wxRichTextPlainText*) this)->ConvertTenthsMMToPixels(dc, WIDTH_FOR_DEFAULT_TABS);
5029 nextTabPos = absoluteWidth + defaultTabWidth;
5030 }
5031
5032 notFound = false;
5033 width = nextTabPos - position.x;
5034
5035 if (partialExtents)
5036 partialExtents->Add(width);
5037 }
5038 }
5039 }
5040 }
5041
5042 if (!stringChunk.IsEmpty())
5043 {
5044 if (partialExtents)
5045 {
5046 int oldWidth;
5047 if (partialExtents->GetCount() > 0)
5048 oldWidth = (*partialExtents)[partialExtents->GetCount()-1];
5049 else
5050 oldWidth = 0;
5051
5052 // Add these partial extents
5053 wxArrayInt p;
5054 dc.GetPartialTextExtents(stringChunk, p);
5055 size_t j;
5056 for (j = 0; j < p.GetCount(); j++)
5057 partialExtents->Add(oldWidth + p[j]);
5058 }
5059 else
5060 {
5061 dc.GetTextExtent(stringChunk, & w, & h, & descent);
5062 width += w;
5063 haveDescent = true;
5064 }
5065 }
5066
5067 if (partialExtents)
5068 {
5069 int charHeight = dc.GetCharHeight();
5070 if ((*partialExtents).GetCount() > 0)
5071 w = (*partialExtents)[partialExtents->GetCount()-1];
5072 else
5073 w = 0;
5074 size = wxSize(w, charHeight);
5075 }
5076 else
5077 {
5078 size = wxSize(width, dc.GetCharHeight());
5079 }
5080
5081 if (!haveDescent)
5082 dc.GetTextExtent(wxT("X"), & w, & h, & descent);
5083
5084 if ( bScript )
5085 dc.SetFont(font);
5086
5087 return true;
5088 }
5089
5090 /// Do a split, returning an object containing the second part, and setting
5091 /// the first part in 'this'.
5092 wxRichTextObject* wxRichTextPlainText::DoSplit(long pos)
5093 {
5094 long index = pos - GetRange().GetStart();
5095
5096 if (index < 0 || index >= (int) m_text.length())
5097 return NULL;
5098
5099 wxString firstPart = m_text.Mid(0, index);
5100 wxString secondPart = m_text.Mid(index);
5101
5102 m_text = firstPart;
5103
5104 wxRichTextPlainText* newObject = new wxRichTextPlainText(secondPart);
5105 newObject->SetAttributes(GetAttributes());
5106
5107 newObject->SetRange(wxRichTextRange(pos, GetRange().GetEnd()));
5108 GetRange().SetEnd(pos-1);
5109
5110 return newObject;
5111 }
5112
5113 /// Calculate range
5114 void wxRichTextPlainText::CalculateRange(long start, long& end)
5115 {
5116 end = start + m_text.length() - 1;
5117 m_range.SetRange(start, end);
5118 }
5119
5120 /// Delete range
5121 bool wxRichTextPlainText::DeleteRange(const wxRichTextRange& range)
5122 {
5123 wxRichTextRange r = range;
5124
5125 r.LimitTo(GetRange());
5126
5127 if (r.GetStart() == GetRange().GetStart() && r.GetEnd() == GetRange().GetEnd())
5128 {
5129 m_text.Empty();
5130 return true;
5131 }
5132
5133 long startIndex = r.GetStart() - GetRange().GetStart();
5134 long len = r.GetLength();
5135
5136 m_text = m_text.Mid(0, startIndex) + m_text.Mid(startIndex+len);
5137 return true;
5138 }
5139
5140 /// Get text for the given range.
5141 wxString wxRichTextPlainText::GetTextForRange(const wxRichTextRange& range) const
5142 {
5143 wxRichTextRange r = range;
5144
5145 r.LimitTo(GetRange());
5146
5147 long startIndex = r.GetStart() - GetRange().GetStart();
5148 long len = r.GetLength();
5149
5150 return m_text.Mid(startIndex, len);
5151 }
5152
5153 /// Returns true if this object can merge itself with the given one.
5154 bool wxRichTextPlainText::CanMerge(wxRichTextObject* object) const
5155 {
5156 return object->GetClassInfo() == CLASSINFO(wxRichTextPlainText) &&
5157 (m_text.empty() || wxTextAttrEq(GetAttributes(), object->GetAttributes()));
5158 }
5159
5160 /// Returns true if this object merged itself with the given one.
5161 /// The calling code will then delete the given object.
5162 bool wxRichTextPlainText::Merge(wxRichTextObject* object)
5163 {
5164 wxRichTextPlainText* textObject = wxDynamicCast(object, wxRichTextPlainText);
5165 wxASSERT( textObject != NULL );
5166
5167 if (textObject)
5168 {
5169 m_text += textObject->GetText();
5170 wxRichTextApplyStyle(m_attributes, textObject->GetAttributes());
5171 return true;
5172 }
5173 else
5174 return false;
5175 }
5176
5177 /// Dump to output stream for debugging
5178 void wxRichTextPlainText::Dump(wxTextOutputStream& stream)
5179 {
5180 wxRichTextObject::Dump(stream);
5181 stream << m_text << wxT("\n");
5182 }
5183
5184 /// Get the first position from pos that has a line break character.
5185 long wxRichTextPlainText::GetFirstLineBreakPosition(long pos)
5186 {
5187 int i;
5188 int len = m_text.length();
5189 int startPos = pos - m_range.GetStart();
5190 for (i = startPos; i < len; i++)
5191 {
5192 wxChar ch = m_text[i];
5193 if (ch == wxRichTextLineBreakChar)
5194 {
5195 return i + m_range.GetStart();
5196 }
5197 }
5198 return -1;
5199 }
5200
5201 /*!
5202 * wxRichTextBuffer
5203 * This is a kind of box, used to represent the whole buffer
5204 */
5205
5206 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBuffer, wxRichTextParagraphLayoutBox)
5207
5208 wxList wxRichTextBuffer::sm_handlers;
5209 wxRichTextRenderer* wxRichTextBuffer::sm_renderer = NULL;
5210 int wxRichTextBuffer::sm_bulletRightMargin = 20;
5211 float wxRichTextBuffer::sm_bulletProportion = (float) 0.3;
5212
5213 /// Initialisation
5214 void wxRichTextBuffer::Init()
5215 {
5216 m_commandProcessor = new wxCommandProcessor;
5217 m_styleSheet = NULL;
5218 m_modified = false;
5219 m_batchedCommandDepth = 0;
5220 m_batchedCommand = NULL;
5221 m_suppressUndo = 0;
5222 m_handlerFlags = 0;
5223 m_scale = 1.0;
5224 }
5225
5226 /// Initialisation
5227 wxRichTextBuffer::~wxRichTextBuffer()
5228 {
5229 delete m_commandProcessor;
5230 delete m_batchedCommand;
5231
5232 ClearStyleStack();
5233 ClearEventHandlers();
5234 }
5235
5236 void wxRichTextBuffer::ResetAndClearCommands()
5237 {
5238 Reset();
5239
5240 GetCommandProcessor()->ClearCommands();
5241
5242 Modify(false);
5243 Invalidate(wxRICHTEXT_ALL);
5244 }
5245
5246 void wxRichTextBuffer::Copy(const wxRichTextBuffer& obj)
5247 {
5248 wxRichTextParagraphLayoutBox::Copy(obj);
5249
5250 m_styleSheet = obj.m_styleSheet;
5251 m_modified = obj.m_modified;
5252 m_batchedCommandDepth = obj.m_batchedCommandDepth;
5253 m_batchedCommand = obj.m_batchedCommand;
5254 m_suppressUndo = obj.m_suppressUndo;
5255 }
5256
5257 /// Push style sheet to top of stack
5258 bool wxRichTextBuffer::PushStyleSheet(wxRichTextStyleSheet* styleSheet)
5259 {
5260 if (m_styleSheet)
5261 styleSheet->InsertSheet(m_styleSheet);
5262
5263 SetStyleSheet(styleSheet);
5264
5265 return true;
5266 }
5267
5268 /// Pop style sheet from top of stack
5269 wxRichTextStyleSheet* wxRichTextBuffer::PopStyleSheet()
5270 {
5271 if (m_styleSheet)
5272 {
5273 wxRichTextStyleSheet* oldSheet = m_styleSheet;
5274 m_styleSheet = oldSheet->GetNextSheet();
5275 oldSheet->Unlink();
5276
5277 return oldSheet;
5278 }
5279 else
5280 return NULL;
5281 }
5282
5283 /// Submit command to insert paragraphs
5284 bool wxRichTextBuffer::InsertParagraphsWithUndo(long pos, const wxRichTextParagraphLayoutBox& paragraphs, wxRichTextCtrl* ctrl, int flags)
5285 {
5286 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Text"), wxRICHTEXT_INSERT, this, ctrl, false);
5287
5288 wxTextAttr attr(GetDefaultStyle());
5289
5290 wxTextAttr* p = NULL;
5291 wxTextAttr paraAttr;
5292 if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
5293 {
5294 paraAttr = GetStyleForNewParagraph(pos);
5295 if (!paraAttr.IsDefault())
5296 p = & paraAttr;
5297 }
5298 else
5299 p = & attr;
5300
5301 action->GetNewParagraphs() = paragraphs;
5302
5303 if (p && !p->IsDefault())
5304 {
5305 for (wxRichTextObjectList::compatibility_iterator node = action->GetNewParagraphs().GetChildren().GetFirst(); node; node = node->GetNext())
5306 {
5307 wxRichTextObject* child = node->GetData();
5308 child->SetAttributes(*p);
5309 }
5310 }
5311
5312 action->SetPosition(pos);
5313
5314 wxRichTextRange range = wxRichTextRange(pos, pos + paragraphs.GetRange().GetEnd() - 1);
5315 if (!paragraphs.GetPartialParagraph())
5316 range.SetEnd(range.GetEnd()+1);
5317
5318 // Set the range we'll need to delete in Undo
5319 action->SetRange(range);
5320
5321 SubmitAction(action);
5322
5323 return true;
5324 }
5325
5326 /// Submit command to insert the given text
5327 bool wxRichTextBuffer::InsertTextWithUndo(long pos, const wxString& text, wxRichTextCtrl* ctrl, int flags)
5328 {
5329 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Text"), wxRICHTEXT_INSERT, this, ctrl, false);
5330
5331 wxTextAttr* p = NULL;
5332 wxTextAttr paraAttr;
5333 if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
5334 {
5335 // Get appropriate paragraph style
5336 paraAttr = GetStyleForNewParagraph(pos, false, false);
5337 if (!paraAttr.IsDefault())
5338 p = & paraAttr;
5339 }
5340
5341 action->GetNewParagraphs().AddParagraphs(text, p);
5342
5343 int length = action->GetNewParagraphs().GetRange().GetLength();
5344
5345 if (text.length() > 0 && text.Last() != wxT('\n'))
5346 {
5347 // Don't count the newline when undoing
5348 length --;
5349 action->GetNewParagraphs().SetPartialParagraph(true);
5350 }
5351 else if (text.length() > 0 && text.Last() == wxT('\n'))
5352 length --;
5353
5354 action->SetPosition(pos);
5355
5356 // Set the range we'll need to delete in Undo
5357 action->SetRange(wxRichTextRange(pos, pos + length - 1));
5358
5359 SubmitAction(action);
5360
5361 return true;
5362 }
5363
5364 /// Submit command to insert the given text
5365 bool wxRichTextBuffer::InsertNewlineWithUndo(long pos, wxRichTextCtrl* ctrl, int flags)
5366 {
5367 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Text"), wxRICHTEXT_INSERT, this, ctrl, false);
5368
5369 wxTextAttr* p = NULL;
5370 wxTextAttr paraAttr;
5371 if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
5372 {
5373 paraAttr = GetStyleForNewParagraph(pos, false, true /* look for next paragraph style */);
5374 if (!paraAttr.IsDefault())
5375 p = & paraAttr;
5376 }
5377
5378 wxTextAttr attr(GetDefaultStyle());
5379
5380 wxRichTextParagraph* newPara = new wxRichTextParagraph(wxEmptyString, this, & attr);
5381 action->GetNewParagraphs().AppendChild(newPara);
5382 action->GetNewParagraphs().UpdateRanges();
5383 action->GetNewParagraphs().SetPartialParagraph(false);
5384 wxRichTextParagraph* para = GetParagraphAtPosition(pos, false);
5385 long pos1 = pos;
5386
5387 if (p)
5388 newPara->SetAttributes(*p);
5389
5390 if (flags & wxRICHTEXT_INSERT_INTERACTIVE)
5391 {
5392 if (para && para->GetRange().GetEnd() == pos)
5393 pos1 ++;
5394
5395 // Now see if we need to number the paragraph.
5396 if (newPara->GetAttributes().HasBulletNumber())
5397 {
5398 wxRichTextAttr numberingAttr;
5399 if (FindNextParagraphNumber(para, numberingAttr))
5400 wxRichTextApplyStyle(newPara->GetAttributes(), (const wxRichTextAttr&) numberingAttr);
5401 }
5402 }
5403
5404 action->SetPosition(pos);
5405
5406 // Use the default character style
5407 // Use the default character style
5408 if (!GetDefaultStyle().IsDefault() && newPara->GetChildren().GetFirst())
5409 {
5410 // Check whether the default style merely reflects the paragraph/basic style,
5411 // in which case don't apply it.
5412 wxTextAttrEx defaultStyle(GetDefaultStyle());
5413 wxTextAttrEx toApply;
5414 if (para)
5415 {
5416 wxRichTextAttr combinedAttr = para->GetCombinedAttributes();
5417 wxTextAttrEx newAttr;
5418 // This filters out attributes that are accounted for by the current
5419 // paragraph/basic style
5420 wxRichTextApplyStyle(toApply, defaultStyle, & combinedAttr);
5421 }
5422 else
5423 toApply = defaultStyle;
5424
5425 if (!toApply.IsDefault())
5426 newPara->GetChildren().GetFirst()->GetData()->SetAttributes(toApply);
5427 }
5428
5429 // Set the range we'll need to delete in Undo
5430 action->SetRange(wxRichTextRange(pos1, pos1));
5431
5432 SubmitAction(action);
5433
5434 return true;
5435 }
5436
5437 /// Submit command to insert the given image
5438 bool wxRichTextBuffer::InsertImageWithUndo(long pos, const wxRichTextImageBlock& imageBlock, wxRichTextCtrl* ctrl, int flags)
5439 {
5440 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Image"), wxRICHTEXT_INSERT, this, ctrl, false);
5441
5442 wxTextAttr* p = NULL;
5443 wxTextAttr paraAttr;
5444 if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
5445 {
5446 paraAttr = GetStyleForNewParagraph(pos);
5447 if (!paraAttr.IsDefault())
5448 p = & paraAttr;
5449 }
5450
5451 wxTextAttr attr(GetDefaultStyle());
5452
5453 wxRichTextParagraph* newPara = new wxRichTextParagraph(this, & attr);
5454 if (p)
5455 newPara->SetAttributes(*p);
5456
5457 wxRichTextImage* imageObject = new wxRichTextImage(imageBlock, newPara);
5458 newPara->AppendChild(imageObject);
5459 action->GetNewParagraphs().AppendChild(newPara);
5460 action->GetNewParagraphs().UpdateRanges();
5461
5462 action->GetNewParagraphs().SetPartialParagraph(true);
5463
5464 action->SetPosition(pos);
5465
5466 // Set the range we'll need to delete in Undo
5467 action->SetRange(wxRichTextRange(pos, pos));
5468
5469 SubmitAction(action);
5470
5471 return true;
5472 }
5473
5474 /// Get the style that is appropriate for a new paragraph at this position.
5475 /// If the previous paragraph has a paragraph style name, look up the next-paragraph
5476 /// style.
5477 wxTextAttr wxRichTextBuffer::GetStyleForNewParagraph(long pos, bool caretPosition, bool lookUpNewParaStyle) const
5478 {
5479 wxRichTextParagraph* para = GetParagraphAtPosition(pos, caretPosition);
5480 if (para)
5481 {
5482 wxTextAttr attr;
5483 bool foundAttributes = false;
5484
5485 // Look for a matching paragraph style
5486 if (lookUpNewParaStyle && !para->GetAttributes().GetParagraphStyleName().IsEmpty() && GetStyleSheet())
5487 {
5488 wxRichTextParagraphStyleDefinition* paraDef = GetStyleSheet()->FindParagraphStyle(para->GetAttributes().GetParagraphStyleName());
5489 if (paraDef)
5490 {
5491 // If we're not at the end of the paragraph, then we apply THIS style, and not the designated next style.
5492 if (para->GetRange().GetEnd() == pos && !paraDef->GetNextStyle().IsEmpty())
5493 {
5494 wxRichTextParagraphStyleDefinition* nextParaDef = GetStyleSheet()->FindParagraphStyle(paraDef->GetNextStyle());
5495 if (nextParaDef)
5496 {
5497 foundAttributes = true;
5498 attr = nextParaDef->GetStyleMergedWithBase(GetStyleSheet());
5499 }
5500 }
5501
5502 // If we didn't find the 'next style', use this style instead.
5503 if (!foundAttributes)
5504 {
5505 foundAttributes = true;
5506 attr = paraDef->GetStyleMergedWithBase(GetStyleSheet());
5507 }
5508 }
5509 }
5510
5511 // Also apply list style if present
5512 if (lookUpNewParaStyle && !para->GetAttributes().GetListStyleName().IsEmpty() && GetStyleSheet())
5513 {
5514 wxRichTextListStyleDefinition* listDef = GetStyleSheet()->FindListStyle(para->GetAttributes().GetListStyleName());
5515 if (listDef)
5516 {
5517 int thisIndent = para->GetAttributes().GetLeftIndent();
5518 int thisLevel = para->GetAttributes().HasOutlineLevel() ? para->GetAttributes().GetOutlineLevel() : listDef->FindLevelForIndent(thisIndent);
5519
5520 // Apply the overall list style, and item style for this level
5521 wxRichTextAttr listStyle(listDef->GetCombinedStyleForLevel(thisLevel, GetStyleSheet()));
5522 wxRichTextApplyStyle(attr, listStyle);
5523 attr.SetOutlineLevel(thisLevel);
5524 if (para->GetAttributes().HasBulletNumber())
5525 attr.SetBulletNumber(para->GetAttributes().GetBulletNumber());
5526 }
5527 }
5528
5529 if (!foundAttributes)
5530 {
5531 attr = para->GetAttributes();
5532 int flags = attr.GetFlags();
5533
5534 // Eliminate character styles
5535 flags &= ( (~ wxTEXT_ATTR_FONT) |
5536 (~ wxTEXT_ATTR_TEXT_COLOUR) |
5537 (~ wxTEXT_ATTR_BACKGROUND_COLOUR) );
5538 attr.SetFlags(flags);
5539 }
5540
5541 return attr;
5542 }
5543 else
5544 return wxTextAttr();
5545 }
5546
5547 /// Submit command to delete this range
5548 bool wxRichTextBuffer::DeleteRangeWithUndo(const wxRichTextRange& range, wxRichTextCtrl* ctrl)
5549 {
5550 wxRichTextAction* action = new wxRichTextAction(NULL, _("Delete"), wxRICHTEXT_DELETE, this, ctrl);
5551
5552 action->SetPosition(ctrl->GetCaretPosition());
5553
5554 // Set the range to delete
5555 action->SetRange(range);
5556
5557 // Copy the fragment that we'll need to restore in Undo
5558 CopyFragment(range, action->GetOldParagraphs());
5559
5560 // See if we're deleting a paragraph marker, in which case we need to
5561 // make a note not to copy the attributes from the 2nd paragraph to the 1st.
5562 if (range.GetStart() == range.GetEnd())
5563 {
5564 wxRichTextParagraph* para = GetParagraphAtPosition(range.GetStart());
5565 if (para && para->GetRange().GetEnd() == range.GetEnd())
5566 {
5567 wxRichTextParagraph* nextPara = GetParagraphAtPosition(range.GetStart()+1);
5568 if (nextPara && nextPara != para)
5569 {
5570 action->GetOldParagraphs().GetChildren().GetFirst()->GetData()->SetAttributes(nextPara->GetAttributes());
5571 action->GetOldParagraphs().GetAttributes().SetFlags(action->GetOldParagraphs().GetAttributes().GetFlags() | wxTEXT_ATTR_KEEP_FIRST_PARA_STYLE);
5572 }
5573 }
5574 }
5575
5576 SubmitAction(action);
5577
5578 return true;
5579 }
5580
5581 /// Collapse undo/redo commands
5582 bool wxRichTextBuffer::BeginBatchUndo(const wxString& cmdName)
5583 {
5584 if (m_batchedCommandDepth == 0)
5585 {
5586 wxASSERT(m_batchedCommand == NULL);
5587 if (m_batchedCommand)
5588 {
5589 GetCommandProcessor()->Store(m_batchedCommand);
5590 }
5591 m_batchedCommand = new wxRichTextCommand(cmdName);
5592 }
5593
5594 m_batchedCommandDepth ++;
5595
5596 return true;
5597 }
5598
5599 /// Collapse undo/redo commands
5600 bool wxRichTextBuffer::EndBatchUndo()
5601 {
5602 m_batchedCommandDepth --;
5603
5604 wxASSERT(m_batchedCommandDepth >= 0);
5605 wxASSERT(m_batchedCommand != NULL);
5606
5607 if (m_batchedCommandDepth == 0)
5608 {
5609 GetCommandProcessor()->Store(m_batchedCommand);
5610 m_batchedCommand = NULL;
5611 }
5612
5613 return true;
5614 }
5615
5616 /// Submit immediately, or delay according to whether collapsing is on
5617 bool wxRichTextBuffer::SubmitAction(wxRichTextAction* action)
5618 {
5619 if (BatchingUndo() && m_batchedCommand && !SuppressingUndo())
5620 {
5621 wxRichTextCommand* cmd = new wxRichTextCommand(action->GetName());
5622 cmd->AddAction(action);
5623 cmd->Do();
5624 cmd->GetActions().Clear();
5625 delete cmd;
5626
5627 m_batchedCommand->AddAction(action);
5628 }
5629 else
5630 {
5631 wxRichTextCommand* cmd = new wxRichTextCommand(action->GetName());
5632 cmd->AddAction(action);
5633
5634 // Only store it if we're not suppressing undo.
5635 return GetCommandProcessor()->Submit(cmd, !SuppressingUndo());
5636 }
5637
5638 return true;
5639 }
5640
5641 /// Begin suppressing undo/redo commands.
5642 bool wxRichTextBuffer::BeginSuppressUndo()
5643 {
5644 m_suppressUndo ++;
5645
5646 return true;
5647 }
5648
5649 /// End suppressing undo/redo commands.
5650 bool wxRichTextBuffer::EndSuppressUndo()
5651 {
5652 m_suppressUndo --;
5653
5654 return true;
5655 }
5656
5657 /// Begin using a style
5658 bool wxRichTextBuffer::BeginStyle(const wxTextAttr& style)
5659 {
5660 wxTextAttr newStyle(GetDefaultStyle());
5661
5662 // Save the old default style
5663 m_attributeStack.Append((wxObject*) new wxTextAttr(GetDefaultStyle()));
5664
5665 wxRichTextApplyStyle(newStyle, style);
5666 newStyle.SetFlags(style.GetFlags()|newStyle.GetFlags());
5667
5668 SetDefaultStyle(newStyle);
5669
5670 return true;
5671 }
5672
5673 /// End the style
5674 bool wxRichTextBuffer::EndStyle()
5675 {
5676 if (!m_attributeStack.GetFirst())
5677 {
5678 wxLogDebug(_("Too many EndStyle calls!"));
5679 return false;
5680 }
5681
5682 wxList::compatibility_iterator node = m_attributeStack.GetLast();
5683 wxTextAttr* attr = (wxTextAttr*)node->GetData();
5684 m_attributeStack.Erase(node);
5685
5686 SetDefaultStyle(*attr);
5687
5688 delete attr;
5689 return true;
5690 }
5691
5692 /// End all styles
5693 bool wxRichTextBuffer::EndAllStyles()
5694 {
5695 while (m_attributeStack.GetCount() != 0)
5696 EndStyle();
5697 return true;
5698 }
5699
5700 /// Clear the style stack
5701 void wxRichTextBuffer::ClearStyleStack()
5702 {
5703 for (wxList::compatibility_iterator node = m_attributeStack.GetFirst(); node; node = node->GetNext())
5704 delete (wxTextAttr*) node->GetData();
5705 m_attributeStack.Clear();
5706 }
5707
5708 /// Begin using bold
5709 bool wxRichTextBuffer::BeginBold()
5710 {
5711 wxTextAttr attr;
5712 attr.SetFontWeight(wxFONTWEIGHT_BOLD);
5713
5714 return BeginStyle(attr);
5715 }
5716
5717 /// Begin using italic
5718 bool wxRichTextBuffer::BeginItalic()
5719 {
5720 wxTextAttr attr;
5721 attr.SetFontStyle(wxFONTSTYLE_ITALIC);
5722
5723 return BeginStyle(attr);
5724 }
5725
5726 /// Begin using underline
5727 bool wxRichTextBuffer::BeginUnderline()
5728 {
5729 wxTextAttr attr;
5730 attr.SetFontUnderlined(true);
5731
5732 return BeginStyle(attr);
5733 }
5734
5735 /// Begin using point size
5736 bool wxRichTextBuffer::BeginFontSize(int pointSize)
5737 {
5738 wxTextAttr attr;
5739 attr.SetFontSize(pointSize);
5740
5741 return BeginStyle(attr);
5742 }
5743
5744 /// Begin using this font
5745 bool wxRichTextBuffer::BeginFont(const wxFont& font)
5746 {
5747 wxTextAttr attr;
5748 attr.SetFont(font);
5749
5750 return BeginStyle(attr);
5751 }
5752
5753 /// Begin using this colour
5754 bool wxRichTextBuffer::BeginTextColour(const wxColour& colour)
5755 {
5756 wxTextAttr attr;
5757 attr.SetFlags(wxTEXT_ATTR_TEXT_COLOUR);
5758 attr.SetTextColour(colour);
5759
5760 return BeginStyle(attr);
5761 }
5762
5763 /// Begin using alignment
5764 bool wxRichTextBuffer::BeginAlignment(wxTextAttrAlignment alignment)
5765 {
5766 wxTextAttr attr;
5767 attr.SetFlags(wxTEXT_ATTR_ALIGNMENT);
5768 attr.SetAlignment(alignment);
5769
5770 return BeginStyle(attr);
5771 }
5772
5773 /// Begin left indent
5774 bool wxRichTextBuffer::BeginLeftIndent(int leftIndent, int leftSubIndent)
5775 {
5776 wxTextAttr attr;
5777 attr.SetFlags(wxTEXT_ATTR_LEFT_INDENT);
5778 attr.SetLeftIndent(leftIndent, leftSubIndent);
5779
5780 return BeginStyle(attr);
5781 }
5782
5783 /// Begin right indent
5784 bool wxRichTextBuffer::BeginRightIndent(int rightIndent)
5785 {
5786 wxTextAttr attr;
5787 attr.SetFlags(wxTEXT_ATTR_RIGHT_INDENT);
5788 attr.SetRightIndent(rightIndent);
5789
5790 return BeginStyle(attr);
5791 }
5792
5793 /// Begin paragraph spacing
5794 bool wxRichTextBuffer::BeginParagraphSpacing(int before, int after)
5795 {
5796 long flags = 0;
5797 if (before != 0)
5798 flags |= wxTEXT_ATTR_PARA_SPACING_BEFORE;
5799 if (after != 0)
5800 flags |= wxTEXT_ATTR_PARA_SPACING_AFTER;
5801
5802 wxTextAttr attr;
5803 attr.SetFlags(flags);
5804 attr.SetParagraphSpacingBefore(before);
5805 attr.SetParagraphSpacingAfter(after);
5806
5807 return BeginStyle(attr);
5808 }
5809
5810 /// Begin line spacing
5811 bool wxRichTextBuffer::BeginLineSpacing(int lineSpacing)
5812 {
5813 wxTextAttr attr;
5814 attr.SetFlags(wxTEXT_ATTR_LINE_SPACING);
5815 attr.SetLineSpacing(lineSpacing);
5816
5817 return BeginStyle(attr);
5818 }
5819
5820 /// Begin numbered bullet
5821 bool wxRichTextBuffer::BeginNumberedBullet(int bulletNumber, 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.SetBulletNumber(bulletNumber);
5827 attr.SetLeftIndent(leftIndent, leftSubIndent);
5828
5829 return BeginStyle(attr);
5830 }
5831
5832 /// Begin symbol bullet
5833 bool wxRichTextBuffer::BeginSymbolBullet(const wxString& symbol, 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.SetBulletText(symbol);
5840
5841 return BeginStyle(attr);
5842 }
5843
5844 /// Begin standard bullet
5845 bool wxRichTextBuffer::BeginStandardBullet(const wxString& bulletName, int leftIndent, int leftSubIndent, int bulletStyle)
5846 {
5847 wxTextAttr attr;
5848 attr.SetFlags(wxTEXT_ATTR_BULLET_STYLE|wxTEXT_ATTR_LEFT_INDENT);
5849 attr.SetBulletStyle(bulletStyle);
5850 attr.SetLeftIndent(leftIndent, leftSubIndent);
5851 attr.SetBulletName(bulletName);
5852
5853 return BeginStyle(attr);
5854 }
5855
5856 /// Begin named character style
5857 bool wxRichTextBuffer::BeginCharacterStyle(const wxString& characterStyle)
5858 {
5859 if (GetStyleSheet())
5860 {
5861 wxRichTextCharacterStyleDefinition* def = GetStyleSheet()->FindCharacterStyle(characterStyle);
5862 if (def)
5863 {
5864 wxTextAttr attr = def->GetStyleMergedWithBase(GetStyleSheet());
5865 return BeginStyle(attr);
5866 }
5867 }
5868 return false;
5869 }
5870
5871 /// Begin named paragraph style
5872 bool wxRichTextBuffer::BeginParagraphStyle(const wxString& paragraphStyle)
5873 {
5874 if (GetStyleSheet())
5875 {
5876 wxRichTextParagraphStyleDefinition* def = GetStyleSheet()->FindParagraphStyle(paragraphStyle);
5877 if (def)
5878 {
5879 wxTextAttr attr = def->GetStyleMergedWithBase(GetStyleSheet());
5880 return BeginStyle(attr);
5881 }
5882 }
5883 return false;
5884 }
5885
5886 /// Begin named list style
5887 bool wxRichTextBuffer::BeginListStyle(const wxString& listStyle, int level, int number)
5888 {
5889 if (GetStyleSheet())
5890 {
5891 wxRichTextListStyleDefinition* def = GetStyleSheet()->FindListStyle(listStyle);
5892 if (def)
5893 {
5894 wxTextAttr attr(def->GetCombinedStyleForLevel(level));
5895
5896 attr.SetBulletNumber(number);
5897
5898 return BeginStyle(attr);
5899 }
5900 }
5901 return false;
5902 }
5903
5904 /// Begin URL
5905 bool wxRichTextBuffer::BeginURL(const wxString& url, const wxString& characterStyle)
5906 {
5907 wxTextAttr attr;
5908
5909 if (!characterStyle.IsEmpty() && GetStyleSheet())
5910 {
5911 wxRichTextCharacterStyleDefinition* def = GetStyleSheet()->FindCharacterStyle(characterStyle);
5912 if (def)
5913 {
5914 attr = def->GetStyleMergedWithBase(GetStyleSheet());
5915 }
5916 }
5917 attr.SetURL(url);
5918
5919 return BeginStyle(attr);
5920 }
5921
5922 /// Adds a handler to the end
5923 void wxRichTextBuffer::AddHandler(wxRichTextFileHandler *handler)
5924 {
5925 sm_handlers.Append(handler);
5926 }
5927
5928 /// Inserts a handler at the front
5929 void wxRichTextBuffer::InsertHandler(wxRichTextFileHandler *handler)
5930 {
5931 sm_handlers.Insert( handler );
5932 }
5933
5934 /// Removes a handler
5935 bool wxRichTextBuffer::RemoveHandler(const wxString& name)
5936 {
5937 wxRichTextFileHandler *handler = FindHandler(name);
5938 if (handler)
5939 {
5940 sm_handlers.DeleteObject(handler);
5941 delete handler;
5942 return true;
5943 }
5944 else
5945 return false;
5946 }
5947
5948 /// Finds a handler by filename or, if supplied, type
5949 wxRichTextFileHandler *wxRichTextBuffer::FindHandlerFilenameOrType(const wxString& filename,
5950 wxRichTextFileType imageType)
5951 {
5952 if (imageType != wxRICHTEXT_TYPE_ANY)
5953 return FindHandler(imageType);
5954 else if (!filename.IsEmpty())
5955 {
5956 wxString path, file, ext;
5957 wxFileName::SplitPath(filename, & path, & file, & ext);
5958 return FindHandler(ext, imageType);
5959 }
5960 else
5961 return NULL;
5962 }
5963
5964
5965 /// Finds a handler by name
5966 wxRichTextFileHandler* wxRichTextBuffer::FindHandler(const wxString& name)
5967 {
5968 wxList::compatibility_iterator node = sm_handlers.GetFirst();
5969 while (node)
5970 {
5971 wxRichTextFileHandler *handler = (wxRichTextFileHandler*)node->GetData();
5972 if (handler->GetName().Lower() == name.Lower()) return handler;
5973
5974 node = node->GetNext();
5975 }
5976 return NULL;
5977 }
5978
5979 /// Finds a handler by extension and type
5980 wxRichTextFileHandler* wxRichTextBuffer::FindHandler(const wxString& extension, wxRichTextFileType type)
5981 {
5982 wxList::compatibility_iterator node = sm_handlers.GetFirst();
5983 while (node)
5984 {
5985 wxRichTextFileHandler *handler = (wxRichTextFileHandler*)node->GetData();
5986 if ( handler->GetExtension().Lower() == extension.Lower() &&
5987 (type == wxRICHTEXT_TYPE_ANY || handler->GetType() == type) )
5988 return handler;
5989 node = node->GetNext();
5990 }
5991 return 0;
5992 }
5993
5994 /// Finds a handler by type
5995 wxRichTextFileHandler* wxRichTextBuffer::FindHandler(wxRichTextFileType type)
5996 {
5997 wxList::compatibility_iterator node = sm_handlers.GetFirst();
5998 while (node)
5999 {
6000 wxRichTextFileHandler *handler = (wxRichTextFileHandler *)node->GetData();
6001 if (handler->GetType() == type) return handler;
6002 node = node->GetNext();
6003 }
6004 return NULL;
6005 }
6006
6007 void wxRichTextBuffer::InitStandardHandlers()
6008 {
6009 if (!FindHandler(wxRICHTEXT_TYPE_TEXT))
6010 AddHandler(new wxRichTextPlainTextHandler);
6011 }
6012
6013 void wxRichTextBuffer::CleanUpHandlers()
6014 {
6015 wxList::compatibility_iterator node = sm_handlers.GetFirst();
6016 while (node)
6017 {
6018 wxRichTextFileHandler* handler = (wxRichTextFileHandler*)node->GetData();
6019 wxList::compatibility_iterator next = node->GetNext();
6020 delete handler;
6021 node = next;
6022 }
6023
6024 sm_handlers.Clear();
6025 }
6026
6027 wxString wxRichTextBuffer::GetExtWildcard(bool combine, bool save, wxArrayInt* types)
6028 {
6029 if (types)
6030 types->Clear();
6031
6032 wxString wildcard;
6033
6034 wxList::compatibility_iterator node = GetHandlers().GetFirst();
6035 int count = 0;
6036 while (node)
6037 {
6038 wxRichTextFileHandler* handler = (wxRichTextFileHandler*) node->GetData();
6039 if (handler->IsVisible() && ((save && handler->CanSave()) || (!save && handler->CanLoad())))
6040 {
6041 if (combine)
6042 {
6043 if (count > 0)
6044 wildcard += wxT(";");
6045 wildcard += wxT("*.") + handler->GetExtension();
6046 }
6047 else
6048 {
6049 if (count > 0)
6050 wildcard += wxT("|");
6051 wildcard += handler->GetName();
6052 wildcard += wxT(" ");
6053 wildcard += _("files");
6054 wildcard += wxT(" (*.");
6055 wildcard += handler->GetExtension();
6056 wildcard += wxT(")|*.");
6057 wildcard += handler->GetExtension();
6058 if (types)
6059 types->Add(handler->GetType());
6060 }
6061 count ++;
6062 }
6063
6064 node = node->GetNext();
6065 }
6066
6067 if (combine)
6068 wildcard = wxT("(") + wildcard + wxT(")|") + wildcard;
6069 return wildcard;
6070 }
6071
6072 /// Load a file
6073 bool wxRichTextBuffer::LoadFile(const wxString& filename, wxRichTextFileType type)
6074 {
6075 wxRichTextFileHandler* handler = FindHandlerFilenameOrType(filename, type);
6076 if (handler)
6077 {
6078 SetDefaultStyle(wxTextAttr());
6079 handler->SetFlags(GetHandlerFlags());
6080 bool success = handler->LoadFile(this, filename);
6081 Invalidate(wxRICHTEXT_ALL);
6082 return success;
6083 }
6084 else
6085 return false;
6086 }
6087
6088 /// Save a file
6089 bool wxRichTextBuffer::SaveFile(const wxString& filename, wxRichTextFileType type)
6090 {
6091 wxRichTextFileHandler* handler = FindHandlerFilenameOrType(filename, type);
6092 if (handler)
6093 {
6094 handler->SetFlags(GetHandlerFlags());
6095 return handler->SaveFile(this, filename);
6096 }
6097 else
6098 return false;
6099 }
6100
6101 /// Load from a stream
6102 bool wxRichTextBuffer::LoadFile(wxInputStream& stream, wxRichTextFileType type)
6103 {
6104 wxRichTextFileHandler* handler = FindHandler(type);
6105 if (handler)
6106 {
6107 SetDefaultStyle(wxTextAttr());
6108 handler->SetFlags(GetHandlerFlags());
6109 bool success = handler->LoadFile(this, stream);
6110 Invalidate(wxRICHTEXT_ALL);
6111 return success;
6112 }
6113 else
6114 return false;
6115 }
6116
6117 /// Save to a stream
6118 bool wxRichTextBuffer::SaveFile(wxOutputStream& stream, wxRichTextFileType type)
6119 {
6120 wxRichTextFileHandler* handler = FindHandler(type);
6121 if (handler)
6122 {
6123 handler->SetFlags(GetHandlerFlags());
6124 return handler->SaveFile(this, stream);
6125 }
6126 else
6127 return false;
6128 }
6129
6130 /// Copy the range to the clipboard
6131 bool wxRichTextBuffer::CopyToClipboard(const wxRichTextRange& range)
6132 {
6133 bool success = false;
6134 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
6135
6136 if (!wxTheClipboard->IsOpened() && wxTheClipboard->Open())
6137 {
6138 wxTheClipboard->Clear();
6139
6140 // Add composite object
6141
6142 wxDataObjectComposite* compositeObject = new wxDataObjectComposite();
6143
6144 {
6145 wxString text = GetTextForRange(range);
6146
6147 #ifdef __WXMSW__
6148 text = wxTextFile::Translate(text, wxTextFileType_Dos);
6149 #endif
6150
6151 compositeObject->Add(new wxTextDataObject(text), false /* not preferred */);
6152 }
6153
6154 // Add rich text buffer data object. This needs the XML handler to be present.
6155
6156 if (FindHandler(wxRICHTEXT_TYPE_XML))
6157 {
6158 wxRichTextBuffer* richTextBuf = new wxRichTextBuffer;
6159 CopyFragment(range, *richTextBuf);
6160
6161 compositeObject->Add(new wxRichTextBufferDataObject(richTextBuf), true /* preferred */);
6162 }
6163
6164 if (wxTheClipboard->SetData(compositeObject))
6165 success = true;
6166
6167 wxTheClipboard->Close();
6168 }
6169
6170 #else
6171 wxUnusedVar(range);
6172 #endif
6173 return success;
6174 }
6175
6176 /// Paste the clipboard content to the buffer
6177 bool wxRichTextBuffer::PasteFromClipboard(long position)
6178 {
6179 bool success = false;
6180 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
6181 if (CanPasteFromClipboard())
6182 {
6183 if (wxTheClipboard->Open())
6184 {
6185 if (wxTheClipboard->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())))
6186 {
6187 wxRichTextBufferDataObject data;
6188 wxTheClipboard->GetData(data);
6189 wxRichTextBuffer* richTextBuffer = data.GetRichTextBuffer();
6190 if (richTextBuffer)
6191 {
6192 InsertParagraphsWithUndo(position+1, *richTextBuffer, GetRichTextCtrl(), 0);
6193 if (GetRichTextCtrl())
6194 GetRichTextCtrl()->ShowPosition(position + richTextBuffer->GetRange().GetEnd());
6195 delete richTextBuffer;
6196 }
6197 }
6198 else if (wxTheClipboard->IsSupported(wxDF_TEXT) || wxTheClipboard->IsSupported(wxDF_UNICODETEXT))
6199 {
6200 wxTextDataObject data;
6201 wxTheClipboard->GetData(data);
6202 wxString text(data.GetText());
6203 #ifdef __WXMSW__
6204 wxString text2;
6205 text2.Alloc(text.Length()+1);
6206 size_t i;
6207 for (i = 0; i < text.Length(); i++)
6208 {
6209 wxChar ch = text[i];
6210 if (ch != wxT('\r'))
6211 text2 += ch;
6212 }
6213 #else
6214 wxString text2 = text;
6215 #endif
6216 InsertTextWithUndo(position+1, text2, GetRichTextCtrl(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE);
6217
6218 if (GetRichTextCtrl())
6219 GetRichTextCtrl()->ShowPosition(position + text2.Length());
6220
6221 success = true;
6222 }
6223 else if (wxTheClipboard->IsSupported(wxDF_BITMAP))
6224 {
6225 wxBitmapDataObject data;
6226 wxTheClipboard->GetData(data);
6227 wxBitmap bitmap(data.GetBitmap());
6228 wxImage image(bitmap.ConvertToImage());
6229
6230 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Image"), wxRICHTEXT_INSERT, this, GetRichTextCtrl(), false);
6231
6232 action->GetNewParagraphs().AddImage(image);
6233
6234 if (action->GetNewParagraphs().GetChildCount() == 1)
6235 action->GetNewParagraphs().SetPartialParagraph(true);
6236
6237 action->SetPosition(position+1);
6238
6239 // Set the range we'll need to delete in Undo
6240 action->SetRange(wxRichTextRange(position+1, position+1));
6241
6242 SubmitAction(action);
6243
6244 success = true;
6245 }
6246 wxTheClipboard->Close();
6247 }
6248 }
6249 #else
6250 wxUnusedVar(position);
6251 #endif
6252 return success;
6253 }
6254
6255 /// Can we paste from the clipboard?
6256 bool wxRichTextBuffer::CanPasteFromClipboard() const
6257 {
6258 bool canPaste = false;
6259 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
6260 if (!wxTheClipboard->IsOpened() && wxTheClipboard->Open())
6261 {
6262 if (wxTheClipboard->IsSupported(wxDF_TEXT) || wxTheClipboard->IsSupported(wxDF_UNICODETEXT) ||
6263 wxTheClipboard->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())) ||
6264 wxTheClipboard->IsSupported(wxDF_BITMAP))
6265 {
6266 canPaste = true;
6267 }
6268 wxTheClipboard->Close();
6269 }
6270 #endif
6271 return canPaste;
6272 }
6273
6274 /// Dumps contents of buffer for debugging purposes
6275 void wxRichTextBuffer::Dump()
6276 {
6277 wxString text;
6278 {
6279 wxStringOutputStream stream(& text);
6280 wxTextOutputStream textStream(stream);
6281 Dump(textStream);
6282 }
6283
6284 wxLogDebug(text);
6285 }
6286
6287 /// Add an event handler
6288 bool wxRichTextBuffer::AddEventHandler(wxEvtHandler* handler)
6289 {
6290 m_eventHandlers.Append(handler);
6291 return true;
6292 }
6293
6294 /// Remove an event handler
6295 bool wxRichTextBuffer::RemoveEventHandler(wxEvtHandler* handler, bool deleteHandler)
6296 {
6297 wxList::compatibility_iterator node = m_eventHandlers.Find(handler);
6298 if (node)
6299 {
6300 m_eventHandlers.Erase(node);
6301 if (deleteHandler)
6302 delete handler;
6303
6304 return true;
6305 }
6306 else
6307 return false;
6308 }
6309
6310 /// Clear event handlers
6311 void wxRichTextBuffer::ClearEventHandlers()
6312 {
6313 m_eventHandlers.Clear();
6314 }
6315
6316 /// Send event to event handlers. If sendToAll is true, will send to all event handlers,
6317 /// otherwise will stop at the first successful one.
6318 bool wxRichTextBuffer::SendEvent(wxEvent& event, bool sendToAll)
6319 {
6320 bool success = false;
6321 for (wxList::compatibility_iterator node = m_eventHandlers.GetFirst(); node; node = node->GetNext())
6322 {
6323 wxEvtHandler* handler = (wxEvtHandler*) node->GetData();
6324 if (handler->ProcessEvent(event))
6325 {
6326 success = true;
6327 if (!sendToAll)
6328 return true;
6329 }
6330 }
6331 return success;
6332 }
6333
6334 /// Set style sheet and notify of the change
6335 bool wxRichTextBuffer::SetStyleSheetAndNotify(wxRichTextStyleSheet* sheet)
6336 {
6337 wxRichTextStyleSheet* oldSheet = GetStyleSheet();
6338
6339 wxWindowID id = wxID_ANY;
6340 if (GetRichTextCtrl())
6341 id = GetRichTextCtrl()->GetId();
6342
6343 wxRichTextEvent event(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING, id);
6344 event.SetEventObject(GetRichTextCtrl());
6345 event.SetOldStyleSheet(oldSheet);
6346 event.SetNewStyleSheet(sheet);
6347 event.Allow();
6348
6349 if (SendEvent(event) && !event.IsAllowed())
6350 {
6351 if (sheet != oldSheet)
6352 delete sheet;
6353
6354 return false;
6355 }
6356
6357 if (oldSheet && oldSheet != sheet)
6358 delete oldSheet;
6359
6360 SetStyleSheet(sheet);
6361
6362 event.SetEventType(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED);
6363 event.SetOldStyleSheet(NULL);
6364 event.Allow();
6365
6366 return SendEvent(event);
6367 }
6368
6369 /// Set renderer, deleting old one
6370 void wxRichTextBuffer::SetRenderer(wxRichTextRenderer* renderer)
6371 {
6372 if (sm_renderer)
6373 delete sm_renderer;
6374 sm_renderer = renderer;
6375 }
6376
6377 bool wxRichTextStdRenderer::DrawStandardBullet(wxRichTextParagraph* paragraph, wxDC& dc, const wxTextAttr& bulletAttr, const wxRect& rect)
6378 {
6379 if (bulletAttr.GetTextColour().Ok())
6380 {
6381 wxCheckSetPen(dc, wxPen(bulletAttr.GetTextColour()));
6382 wxCheckSetBrush(dc, wxBrush(bulletAttr.GetTextColour()));
6383 }
6384 else
6385 {
6386 wxCheckSetPen(dc, *wxBLACK_PEN);
6387 wxCheckSetBrush(dc, *wxBLACK_BRUSH);
6388 }
6389
6390 wxFont font;
6391 if (bulletAttr.HasFont())
6392 {
6393 font = paragraph->GetBuffer()->GetFontTable().FindFont(bulletAttr);
6394 }
6395 else
6396 font = (*wxNORMAL_FONT);
6397
6398 wxCheckSetFont(dc, font);
6399
6400 int charHeight = dc.GetCharHeight();
6401
6402 int bulletWidth = (int) (((float) charHeight) * wxRichTextBuffer::GetBulletProportion());
6403 int bulletHeight = bulletWidth;
6404
6405 int x = rect.x;
6406
6407 // Calculate the top position of the character (as opposed to the whole line height)
6408 int y = rect.y + (rect.height - charHeight);
6409
6410 // Calculate where the bullet should be positioned
6411 y = y + (charHeight+1)/2 - (bulletHeight+1)/2;
6412
6413 // The margin between a bullet and text.
6414 int margin = paragraph->ConvertTenthsMMToPixels(dc, wxRichTextBuffer::GetBulletRightMargin());
6415
6416 if (bulletAttr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT)
6417 x = rect.x + rect.width - bulletWidth - margin;
6418 else if (bulletAttr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE)
6419 x = x + (rect.width)/2 - bulletWidth/2;
6420
6421 if (bulletAttr.GetBulletName() == wxT("standard/square"))
6422 {
6423 dc.DrawRectangle(x, y, bulletWidth, bulletHeight);
6424 }
6425 else if (bulletAttr.GetBulletName() == wxT("standard/diamond"))
6426 {
6427 wxPoint pts[5];
6428 pts[0].x = x; pts[0].y = y + bulletHeight/2;
6429 pts[1].x = x + bulletWidth/2; pts[1].y = y;
6430 pts[2].x = x + bulletWidth; pts[2].y = y + bulletHeight/2;
6431 pts[3].x = x + bulletWidth/2; pts[3].y = y + bulletHeight;
6432
6433 dc.DrawPolygon(4, pts);
6434 }
6435 else if (bulletAttr.GetBulletName() == wxT("standard/triangle"))
6436 {
6437 wxPoint pts[3];
6438 pts[0].x = x; pts[0].y = y;
6439 pts[1].x = x + bulletWidth; pts[1].y = y + bulletHeight/2;
6440 pts[2].x = x; pts[2].y = y + bulletHeight;
6441
6442 dc.DrawPolygon(3, pts);
6443 }
6444 else // "standard/circle", and catch-all
6445 {
6446 dc.DrawEllipse(x, y, bulletWidth, bulletHeight);
6447 }
6448
6449 return true;
6450 }
6451
6452 bool wxRichTextStdRenderer::DrawTextBullet(wxRichTextParagraph* paragraph, wxDC& dc, const wxTextAttr& attr, const wxRect& rect, const wxString& text)
6453 {
6454 if (!text.empty())
6455 {
6456 wxFont font;
6457 if ((attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL) && !attr.GetBulletFont().IsEmpty() && attr.HasFont())
6458 {
6459 wxTextAttr fontAttr;
6460 fontAttr.SetFontSize(attr.GetFontSize());
6461 fontAttr.SetFontStyle(attr.GetFontStyle());
6462 fontAttr.SetFontWeight(attr.GetFontWeight());
6463 fontAttr.SetFontUnderlined(attr.GetFontUnderlined());
6464 fontAttr.SetFontFaceName(attr.GetBulletFont());
6465 font = paragraph->GetBuffer()->GetFontTable().FindFont(fontAttr);
6466 }
6467 else if (attr.HasFont())
6468 font = paragraph->GetBuffer()->GetFontTable().FindFont(attr);
6469 else
6470 font = (*wxNORMAL_FONT);
6471
6472 wxCheckSetFont(dc, font);
6473
6474 if (attr.GetTextColour().Ok())
6475 dc.SetTextForeground(attr.GetTextColour());
6476
6477 dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT);
6478
6479 int charHeight = dc.GetCharHeight();
6480 wxCoord tw, th;
6481 dc.GetTextExtent(text, & tw, & th);
6482
6483 int x = rect.x;
6484
6485 // Calculate the top position of the character (as opposed to the whole line height)
6486 int y = rect.y + (rect.height - charHeight);
6487
6488 // The margin between a bullet and text.
6489 int margin = paragraph->ConvertTenthsMMToPixels(dc, wxRichTextBuffer::GetBulletRightMargin());
6490
6491 if (attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT)
6492 x = (rect.x + rect.width) - tw - margin;
6493 else if (attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE)
6494 x = x + (rect.width)/2 - tw/2;
6495
6496 dc.DrawText(text, x, y);
6497
6498 return true;
6499 }
6500 else
6501 return false;
6502 }
6503
6504 bool wxRichTextStdRenderer::DrawBitmapBullet(wxRichTextParagraph* WXUNUSED(paragraph), wxDC& WXUNUSED(dc), const wxTextAttr& WXUNUSED(attr), const wxRect& WXUNUSED(rect))
6505 {
6506 // Currently unimplemented. The intention is to store bitmaps by name in a media store associated
6507 // with the buffer. The store will allow retrieval from memory, disk or other means.
6508 return false;
6509 }
6510
6511 /// Enumerate the standard bullet names currently supported
6512 bool wxRichTextStdRenderer::EnumerateStandardBulletNames(wxArrayString& bulletNames)
6513 {
6514 bulletNames.Add(wxTRANSLATE("standard/circle"));
6515 bulletNames.Add(wxTRANSLATE("standard/square"));
6516 bulletNames.Add(wxTRANSLATE("standard/diamond"));
6517 bulletNames.Add(wxTRANSLATE("standard/triangle"));
6518
6519 return true;
6520 }
6521
6522 /*
6523 * Module to initialise and clean up handlers
6524 */
6525
6526 class wxRichTextModule: public wxModule
6527 {
6528 DECLARE_DYNAMIC_CLASS(wxRichTextModule)
6529 public:
6530 wxRichTextModule() {}
6531 bool OnInit()
6532 {
6533 wxRichTextBuffer::SetRenderer(new wxRichTextStdRenderer);
6534 wxRichTextBuffer::InitStandardHandlers();
6535 wxRichTextParagraph::InitDefaultTabs();
6536 return true;
6537 }
6538 void OnExit()
6539 {
6540 wxRichTextBuffer::CleanUpHandlers();
6541 wxRichTextDecimalToRoman(-1);
6542 wxRichTextParagraph::ClearDefaultTabs();
6543 wxRichTextCtrl::ClearAvailableFontNames();
6544 wxRichTextBuffer::SetRenderer(NULL);
6545 }
6546 };
6547
6548 IMPLEMENT_DYNAMIC_CLASS(wxRichTextModule, wxModule)
6549
6550
6551 // If the richtext lib is dynamically loaded after the app has already started
6552 // (such as from wxPython) then the built-in module system will not init this
6553 // module. Provide this function to do it manually.
6554 void wxRichTextModuleInit()
6555 {
6556 wxModule* module = new wxRichTextModule;
6557 module->Init();
6558 wxModule::RegisterModule(module);
6559 }
6560
6561
6562 /*!
6563 * Commands for undo/redo
6564 *
6565 */
6566
6567 wxRichTextCommand::wxRichTextCommand(const wxString& name, wxRichTextCommandId id, wxRichTextBuffer* buffer,
6568 wxRichTextCtrl* ctrl, bool ignoreFirstTime): wxCommand(true, name)
6569 {
6570 /* wxRichTextAction* action = */ new wxRichTextAction(this, name, id, buffer, ctrl, ignoreFirstTime);
6571 }
6572
6573 wxRichTextCommand::wxRichTextCommand(const wxString& name): wxCommand(true, name)
6574 {
6575 }
6576
6577 wxRichTextCommand::~wxRichTextCommand()
6578 {
6579 ClearActions();
6580 }
6581
6582 void wxRichTextCommand::AddAction(wxRichTextAction* action)
6583 {
6584 if (!m_actions.Member(action))
6585 m_actions.Append(action);
6586 }
6587
6588 bool wxRichTextCommand::Do()
6589 {
6590 for (wxList::compatibility_iterator node = m_actions.GetFirst(); node; node = node->GetNext())
6591 {
6592 wxRichTextAction* action = (wxRichTextAction*) node->GetData();
6593 action->Do();
6594 }
6595
6596 return true;
6597 }
6598
6599 bool wxRichTextCommand::Undo()
6600 {
6601 for (wxList::compatibility_iterator node = m_actions.GetLast(); node; node = node->GetPrevious())
6602 {
6603 wxRichTextAction* action = (wxRichTextAction*) node->GetData();
6604 action->Undo();
6605 }
6606
6607 return true;
6608 }
6609
6610 void wxRichTextCommand::ClearActions()
6611 {
6612 WX_CLEAR_LIST(wxList, m_actions);
6613 }
6614
6615 /*!
6616 * Individual action
6617 *
6618 */
6619
6620 wxRichTextAction::wxRichTextAction(wxRichTextCommand* cmd, const wxString& name, wxRichTextCommandId id, wxRichTextBuffer* buffer,
6621 wxRichTextCtrl* ctrl, bool ignoreFirstTime)
6622 {
6623 m_buffer = buffer;
6624 m_ignoreThis = ignoreFirstTime;
6625 m_cmdId = id;
6626 m_position = -1;
6627 m_ctrl = ctrl;
6628 m_name = name;
6629 m_newParagraphs.SetDefaultStyle(buffer->GetDefaultStyle());
6630 m_newParagraphs.SetBasicStyle(buffer->GetBasicStyle());
6631 if (cmd)
6632 cmd->AddAction(this);
6633 }
6634
6635 wxRichTextAction::~wxRichTextAction()
6636 {
6637 }
6638
6639 void wxRichTextAction::CalculateRefreshOptimizations(wxArrayInt& optimizationLineCharPositions, wxArrayInt& optimizationLineYPositions)
6640 {
6641 // Store a list of line start character and y positions so we can figure out which area
6642 // we need to refresh
6643
6644 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6645 // NOTE: we're assuming that the buffer is laid out correctly at this point.
6646 // If we had several actions, which only invalidate and leave layout until the
6647 // paint handler is called, then this might not be true. So we may need to switch
6648 // optimisation on only when we're simply adding text and not simultaneously
6649 // deleting a selection, for example. Or, we make sure the buffer is laid out correctly
6650 // first, but of course this means we'll be doing it twice.
6651 if (!m_buffer->GetDirty() && m_ctrl) // can only do optimisation if the buffer is already laid out correctly
6652 {
6653 wxSize clientSize = m_ctrl->GetClientSize();
6654 wxPoint firstVisiblePt = m_ctrl->GetFirstVisiblePoint();
6655 int lastY = firstVisiblePt.y + clientSize.y;
6656
6657 wxRichTextParagraph* para = m_buffer->GetParagraphAtPosition(GetRange().GetStart());
6658 wxRichTextObjectList::compatibility_iterator node = m_buffer->GetChildren().Find(para);
6659 while (node)
6660 {
6661 wxRichTextParagraph* child = (wxRichTextParagraph*) node->GetData();
6662 wxRichTextLineList::compatibility_iterator node2 = child->GetLines().GetFirst();
6663 while (node2)
6664 {
6665 wxRichTextLine* line = node2->GetData();
6666 wxPoint pt = line->GetAbsolutePosition();
6667 wxRichTextRange range = line->GetAbsoluteRange();
6668
6669 if (pt.y > lastY)
6670 {
6671 node2 = wxRichTextLineList::compatibility_iterator();
6672 node = wxRichTextObjectList::compatibility_iterator();
6673 }
6674 else if (range.GetStart() > GetPosition() && pt.y >= firstVisiblePt.y)
6675 {
6676 optimizationLineCharPositions.Add(range.GetStart());
6677 optimizationLineYPositions.Add(pt.y);
6678 }
6679
6680 if (node2)
6681 node2 = node2->GetNext();
6682 }
6683
6684 if (node)
6685 node = node->GetNext();
6686 }
6687 }
6688 #endif
6689 }
6690
6691 bool wxRichTextAction::Do()
6692 {
6693 m_buffer->Modify(true);
6694
6695 switch (m_cmdId)
6696 {
6697 case wxRICHTEXT_INSERT:
6698 {
6699 // Store a list of line start character and y positions so we can figure out which area
6700 // we need to refresh
6701 wxArrayInt optimizationLineCharPositions;
6702 wxArrayInt optimizationLineYPositions;
6703
6704 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6705 CalculateRefreshOptimizations(optimizationLineCharPositions, optimizationLineYPositions);
6706 #endif
6707
6708 m_buffer->InsertFragment(GetRange().GetStart(), m_newParagraphs);
6709 m_buffer->UpdateRanges();
6710 m_buffer->Invalidate(wxRichTextRange(wxMax(0, GetRange().GetStart()-1), GetRange().GetEnd()));
6711
6712 long newCaretPosition = GetPosition() + m_newParagraphs.GetRange().GetLength();
6713
6714 // Character position to caret position
6715 newCaretPosition --;
6716
6717 // Don't take into account the last newline
6718 if (m_newParagraphs.GetPartialParagraph())
6719 newCaretPosition --;
6720 else
6721 if (m_newParagraphs.GetChildren().GetCount() > 1)
6722 {
6723 wxRichTextObject* p = (wxRichTextObject*) m_newParagraphs.GetChildren().GetLast()->GetData();
6724 if (p->GetRange().GetLength() == 1)
6725 newCaretPosition --;
6726 }
6727
6728 newCaretPosition = wxMin(newCaretPosition, (m_buffer->GetRange().GetEnd()-1));
6729
6730 UpdateAppearance(newCaretPosition, true /* send update event */, & optimizationLineCharPositions, & optimizationLineYPositions, true /* do */);
6731
6732 wxRichTextEvent cmdEvent(
6733 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED,
6734 m_ctrl ? m_ctrl->GetId() : -1);
6735 cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
6736 cmdEvent.SetRange(GetRange());
6737 cmdEvent.SetPosition(GetRange().GetStart());
6738
6739 m_buffer->SendEvent(cmdEvent);
6740
6741 break;
6742 }
6743 case wxRICHTEXT_DELETE:
6744 {
6745 wxArrayInt optimizationLineCharPositions;
6746 wxArrayInt optimizationLineYPositions;
6747
6748 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6749 CalculateRefreshOptimizations(optimizationLineCharPositions, optimizationLineYPositions);
6750 #endif
6751
6752 m_buffer->DeleteRange(GetRange());
6753 m_buffer->UpdateRanges();
6754 m_buffer->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6755
6756 long caretPos = GetRange().GetStart()-1;
6757 if (caretPos >= m_buffer->GetRange().GetEnd())
6758 caretPos --;
6759
6760 UpdateAppearance(caretPos, true /* send update event */, & optimizationLineCharPositions, & optimizationLineYPositions, true /* do */);
6761
6762 wxRichTextEvent cmdEvent(
6763 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED,
6764 m_ctrl ? m_ctrl->GetId() : -1);
6765 cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
6766 cmdEvent.SetRange(GetRange());
6767 cmdEvent.SetPosition(GetRange().GetStart());
6768
6769 m_buffer->SendEvent(cmdEvent);
6770
6771 break;
6772 }
6773 case wxRICHTEXT_CHANGE_STYLE:
6774 {
6775 ApplyParagraphs(GetNewParagraphs());
6776 m_buffer->Invalidate(GetRange());
6777
6778 UpdateAppearance(GetPosition());
6779
6780 wxRichTextEvent cmdEvent(
6781 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED,
6782 m_ctrl ? m_ctrl->GetId() : -1);
6783 cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
6784 cmdEvent.SetRange(GetRange());
6785 cmdEvent.SetPosition(GetRange().GetStart());
6786
6787 m_buffer->SendEvent(cmdEvent);
6788
6789 break;
6790 }
6791 default:
6792 break;
6793 }
6794
6795 return true;
6796 }
6797
6798 bool wxRichTextAction::Undo()
6799 {
6800 m_buffer->Modify(true);
6801
6802 switch (m_cmdId)
6803 {
6804 case wxRICHTEXT_INSERT:
6805 {
6806 wxArrayInt optimizationLineCharPositions;
6807 wxArrayInt optimizationLineYPositions;
6808
6809 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6810 CalculateRefreshOptimizations(optimizationLineCharPositions, optimizationLineYPositions);
6811 #endif
6812
6813 m_buffer->DeleteRange(GetRange());
6814 m_buffer->UpdateRanges();
6815 m_buffer->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6816
6817 long newCaretPosition = GetPosition() - 1;
6818
6819 UpdateAppearance(newCaretPosition, true, /* send update event */ & optimizationLineCharPositions, & optimizationLineYPositions, false /* undo */);
6820
6821 wxRichTextEvent cmdEvent(
6822 wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED,
6823 m_ctrl ? m_ctrl->GetId() : -1);
6824 cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
6825 cmdEvent.SetRange(GetRange());
6826 cmdEvent.SetPosition(GetRange().GetStart());
6827
6828 m_buffer->SendEvent(cmdEvent);
6829
6830 break;
6831 }
6832 case wxRICHTEXT_DELETE:
6833 {
6834 wxArrayInt optimizationLineCharPositions;
6835 wxArrayInt optimizationLineYPositions;
6836
6837 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6838 CalculateRefreshOptimizations(optimizationLineCharPositions, optimizationLineYPositions);
6839 #endif
6840
6841 m_buffer->InsertFragment(GetRange().GetStart(), m_oldParagraphs);
6842 m_buffer->UpdateRanges();
6843 m_buffer->Invalidate(GetRange());
6844
6845 UpdateAppearance(GetPosition(), true, /* send update event */ & optimizationLineCharPositions, & optimizationLineYPositions, false /* undo */);
6846
6847 wxRichTextEvent cmdEvent(
6848 wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED,
6849 m_ctrl ? m_ctrl->GetId() : -1);
6850 cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
6851 cmdEvent.SetRange(GetRange());
6852 cmdEvent.SetPosition(GetRange().GetStart());
6853
6854 m_buffer->SendEvent(cmdEvent);
6855
6856 break;
6857 }
6858 case wxRICHTEXT_CHANGE_STYLE:
6859 {
6860 ApplyParagraphs(GetOldParagraphs());
6861 m_buffer->Invalidate(GetRange());
6862
6863 UpdateAppearance(GetPosition());
6864
6865 wxRichTextEvent cmdEvent(
6866 wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED,
6867 m_ctrl ? m_ctrl->GetId() : -1);
6868 cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
6869 cmdEvent.SetRange(GetRange());
6870 cmdEvent.SetPosition(GetRange().GetStart());
6871
6872 m_buffer->SendEvent(cmdEvent);
6873
6874 break;
6875 }
6876 default:
6877 break;
6878 }
6879
6880 return true;
6881 }
6882
6883 /// Update the control appearance
6884 void wxRichTextAction::UpdateAppearance(long caretPosition, bool sendUpdateEvent, wxArrayInt* optimizationLineCharPositions, wxArrayInt* optimizationLineYPositions, bool isDoCmd)
6885 {
6886 if (m_ctrl)
6887 {
6888 m_ctrl->SetCaretPosition(caretPosition);
6889 if (!m_ctrl->IsFrozen())
6890 {
6891 m_ctrl->LayoutContent();
6892
6893 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6894 // Find refresh rectangle if we are in a position to optimise refresh
6895 if ((m_cmdId == wxRICHTEXT_INSERT || m_cmdId == wxRICHTEXT_DELETE) && optimizationLineCharPositions)
6896 {
6897 size_t i;
6898
6899 wxSize clientSize = m_ctrl->GetClientSize();
6900 wxPoint firstVisiblePt = m_ctrl->GetFirstVisiblePoint();
6901
6902 // Start/end positions
6903 int firstY = 0;
6904 int lastY = firstVisiblePt.y + clientSize.y;
6905
6906 bool foundEnd = false;
6907
6908 // position offset - how many characters were inserted
6909 int positionOffset = GetRange().GetLength();
6910
6911 // Determine whether this is Do or Undo, and adjust positionOffset accordingly
6912 if ((m_cmdId == wxRICHTEXT_DELETE && isDoCmd) || (m_cmdId == wxRICHTEXT_INSERT && !isDoCmd))
6913 positionOffset = - positionOffset;
6914
6915 // find the first line which is being drawn at the same position as it was
6916 // before. Since we're talking about a simple insertion, we can assume
6917 // that the rest of the window does not need to be redrawn.
6918
6919 wxRichTextParagraph* para = m_buffer->GetParagraphAtPosition(GetPosition());
6920 if (para)
6921 {
6922 // Find line containing GetPosition().
6923 wxRichTextLine* line = NULL;
6924 wxRichTextLineList::compatibility_iterator node2 = para->GetLines().GetFirst();
6925 while (node2)
6926 {
6927 wxRichTextLine* l = node2->GetData();
6928 wxRichTextRange range = l->GetAbsoluteRange();
6929 if (range.Contains(GetRange().GetStart()-1))
6930 {
6931 line = l;
6932 break;
6933 }
6934 node2 = node2->GetNext();
6935 }
6936
6937 if (line)
6938 {
6939 // Step back a couple of lines to where we can be sure of reformatting correctly
6940 wxRichTextLineList::compatibility_iterator lineNode = para->GetLines().Find(line);
6941 if (lineNode)
6942 {
6943 lineNode = lineNode->GetPrevious();
6944 if (lineNode)
6945 {
6946 line = (wxRichTextLine*) lineNode->GetData();
6947 lineNode = lineNode->GetPrevious();
6948 if (lineNode)
6949 line = (wxRichTextLine*) lineNode->GetData();
6950 }
6951 }
6952
6953 firstY = line->GetAbsolutePosition().y;
6954 }
6955 }
6956
6957 wxRichTextObjectList::compatibility_iterator node = m_buffer->GetChildren().Find(para);
6958 while (node)
6959 {
6960 wxRichTextParagraph* child = (wxRichTextParagraph*) node->GetData();
6961 wxRichTextLineList::compatibility_iterator node2 = child->GetLines().GetFirst();
6962 while (node2)
6963 {
6964 wxRichTextLine* line = node2->GetData();
6965 wxPoint pt = line->GetAbsolutePosition();
6966 wxRichTextRange range = line->GetAbsoluteRange();
6967
6968 // we want to find the first line that is in the same position
6969 // as before. This will mean we're at the end of the changed text.
6970
6971 if (pt.y > lastY) // going past the end of the window, no more info
6972 {
6973 node2 = wxRichTextLineList::compatibility_iterator();
6974 node = wxRichTextObjectList::compatibility_iterator();
6975 }
6976 // Detect last line in the buffer
6977 else if (!node2->GetNext() && para->GetRange().Contains(m_buffer->GetRange().GetEnd()))
6978 {
6979 // If deleting text, make sure we refresh below as well as above
6980 if (positionOffset >= 0)
6981 {
6982 foundEnd = true;
6983 lastY = pt.y + line->GetSize().y;
6984 }
6985
6986 node2 = wxRichTextLineList::compatibility_iterator();
6987 node = wxRichTextObjectList::compatibility_iterator();
6988
6989 break;
6990 }
6991 else
6992 {
6993 // search for this line being at the same position as before
6994 for (i = 0; i < optimizationLineCharPositions->GetCount(); i++)
6995 {
6996 if (((*optimizationLineCharPositions)[i] + positionOffset == range.GetStart()) &&
6997 ((*optimizationLineYPositions)[i] == pt.y))
6998 {
6999 // Stop, we're now the same as we were
7000 foundEnd = true;
7001
7002 lastY = pt.y;
7003
7004 node2 = wxRichTextLineList::compatibility_iterator();
7005 node = wxRichTextObjectList::compatibility_iterator();
7006
7007 break;
7008 }
7009 }
7010 }
7011
7012 if (node2)
7013 node2 = node2->GetNext();
7014 }
7015
7016 if (node)
7017 node = node->GetNext();
7018 }
7019
7020 firstY = wxMax(firstVisiblePt.y, firstY);
7021 if (!foundEnd)
7022 lastY = firstVisiblePt.y + clientSize.y;
7023
7024 // Convert to device coordinates
7025 wxRect rect(m_ctrl->GetPhysicalPoint(wxPoint(firstVisiblePt.x, firstY)), wxSize(clientSize.x, lastY - firstY));
7026 m_ctrl->RefreshRect(rect);
7027 }
7028 else
7029 #endif
7030 m_ctrl->Refresh(false);
7031
7032 #if wxRICHTEXT_USE_OWN_CARET
7033 m_ctrl->PositionCaret();
7034 #endif
7035 if (sendUpdateEvent)
7036 wxTextCtrl::SendTextUpdatedEvent(m_ctrl);
7037 }
7038 }
7039 }
7040
7041 /// Replace the buffer paragraphs with the new ones.
7042 void wxRichTextAction::ApplyParagraphs(const wxRichTextParagraphLayoutBox& fragment)
7043 {
7044 wxRichTextObjectList::compatibility_iterator node = fragment.GetChildren().GetFirst();
7045 while (node)
7046 {
7047 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
7048 wxASSERT (para != NULL);
7049
7050 // We'll replace the existing paragraph by finding the paragraph at this position,
7051 // delete its node data, and setting a copy as the new node data.
7052 // TODO: make more efficient by simply swapping old and new paragraph objects.
7053
7054 wxRichTextParagraph* existingPara = m_buffer->GetParagraphAtPosition(para->GetRange().GetStart());
7055 if (existingPara)
7056 {
7057 wxRichTextObjectList::compatibility_iterator bufferParaNode = m_buffer->GetChildren().Find(existingPara);
7058 if (bufferParaNode)
7059 {
7060 wxRichTextParagraph* newPara = new wxRichTextParagraph(*para);
7061 newPara->SetParent(m_buffer);
7062
7063 bufferParaNode->SetData(newPara);
7064
7065 delete existingPara;
7066 }
7067 }
7068
7069 node = node->GetNext();
7070 }
7071 }
7072
7073
7074 /*!
7075 * wxRichTextRange
7076 * This stores beginning and end positions for a range of data.
7077 */
7078
7079 /// Limit this range to be within 'range'
7080 bool wxRichTextRange::LimitTo(const wxRichTextRange& range)
7081 {
7082 if (m_start < range.m_start)
7083 m_start = range.m_start;
7084
7085 if (m_end > range.m_end)
7086 m_end = range.m_end;
7087
7088 return true;
7089 }
7090
7091 /*!
7092 * wxRichTextImage implementation
7093 * This object represents an image.
7094 */
7095
7096 IMPLEMENT_DYNAMIC_CLASS(wxRichTextImage, wxRichTextObject)
7097
7098 wxRichTextImage::wxRichTextImage(const wxImage& image, wxRichTextObject* parent, wxTextAttr* charStyle):
7099 wxRichTextObject(parent)
7100 {
7101 m_image = image;
7102 if (charStyle)
7103 SetAttributes(*charStyle);
7104 }
7105
7106 wxRichTextImage::wxRichTextImage(const wxRichTextImageBlock& imageBlock, wxRichTextObject* parent, wxTextAttr* charStyle):
7107 wxRichTextObject(parent)
7108 {
7109 m_imageBlock = imageBlock;
7110 m_imageBlock.Load(m_image);
7111 if (charStyle)
7112 SetAttributes(*charStyle);
7113 }
7114
7115 /// Load wxImage from the block
7116 bool wxRichTextImage::LoadFromBlock()
7117 {
7118 m_imageBlock.Load(m_image);
7119 return m_imageBlock.Ok();
7120 }
7121
7122 /// Make block from the wxImage
7123 bool wxRichTextImage::MakeBlock()
7124 {
7125 wxBitmapType type = m_imageBlock.GetImageType();
7126 if ( type == wxBITMAP_TYPE_ANY || type == wxBITMAP_TYPE_INVALID )
7127 m_imageBlock.SetImageType(type = wxBITMAP_TYPE_PNG);
7128
7129 m_imageBlock.MakeImageBlock(m_image, type);
7130 return m_imageBlock.Ok();
7131 }
7132
7133
7134 /// Draw the item
7135 bool wxRichTextImage::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextRange& selectionRange, const wxRect& rect, int WXUNUSED(descent), int WXUNUSED(style))
7136 {
7137 if (!m_image.Ok() && m_imageBlock.Ok())
7138 LoadFromBlock();
7139
7140 if (!m_image.Ok())
7141 return false;
7142
7143 if (m_image.Ok() && !m_bitmap.Ok())
7144 m_bitmap = wxBitmap(m_image);
7145
7146 int y = rect.y + (rect.height - m_image.GetHeight());
7147
7148 if (m_bitmap.Ok())
7149 dc.DrawBitmap(m_bitmap, rect.x, y, true);
7150
7151 if (selectionRange.Contains(range.GetStart()))
7152 {
7153 wxCheckSetBrush(dc, *wxBLACK_BRUSH);
7154 wxCheckSetPen(dc, *wxBLACK_PEN);
7155 dc.SetLogicalFunction(wxINVERT);
7156 dc.DrawRectangle(rect);
7157 dc.SetLogicalFunction(wxCOPY);
7158 }
7159
7160 return true;
7161 }
7162
7163 /// Lay the item out
7164 bool wxRichTextImage::Layout(wxDC& WXUNUSED(dc), const wxRect& rect, int WXUNUSED(style))
7165 {
7166 if (!m_image.Ok())
7167 LoadFromBlock();
7168
7169 if (m_image.Ok())
7170 {
7171 SetCachedSize(wxSize(m_image.GetWidth(), m_image.GetHeight()));
7172 SetPosition(rect.GetPosition());
7173 }
7174
7175 return true;
7176 }
7177
7178 /// Get/set the object size for the given range. Returns false if the range
7179 /// is invalid for this object.
7180 bool wxRichTextImage::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& WXUNUSED(descent), wxDC& WXUNUSED(dc), int WXUNUSED(flags), wxPoint WXUNUSED(position), wxArrayInt* partialExtents) const
7181 {
7182 if (!range.IsWithin(GetRange()))
7183 return false;
7184
7185 if (!m_image.Ok())
7186 ((wxRichTextImage*) this)->LoadFromBlock();
7187
7188 if (partialExtents)
7189 {
7190 if (m_image.Ok())
7191 partialExtents->Add(m_image.GetWidth());
7192 else
7193 partialExtents->Add(0);
7194 }
7195
7196 if (!m_image.Ok())
7197 return false;
7198
7199 size.x = m_image.GetWidth();
7200 size.y = m_image.GetHeight();
7201
7202 return true;
7203 }
7204
7205 /// Copy
7206 void wxRichTextImage::Copy(const wxRichTextImage& obj)
7207 {
7208 wxRichTextObject::Copy(obj);
7209
7210 m_image = obj.m_image;
7211 m_imageBlock = obj.m_imageBlock;
7212 }
7213
7214 /*!
7215 * Utilities
7216 *
7217 */
7218
7219 /// Compare two attribute objects
7220 bool wxTextAttrEq(const wxTextAttr& attr1, const wxTextAttr& attr2)
7221 {
7222 return (attr1 == attr2);
7223 }
7224
7225 // Partial equality test taking flags into account
7226 bool wxTextAttrEqPartial(const wxTextAttr& attr1, const wxTextAttr& attr2, int flags)
7227 {
7228 return attr1.EqPartial(attr2, flags);
7229 }
7230
7231 /// Compare tabs
7232 bool wxRichTextTabsEq(const wxArrayInt& tabs1, const wxArrayInt& tabs2)
7233 {
7234 if (tabs1.GetCount() != tabs2.GetCount())
7235 return false;
7236
7237 size_t i;
7238 for (i = 0; i < tabs1.GetCount(); i++)
7239 {
7240 if (tabs1[i] != tabs2[i])
7241 return false;
7242 }
7243 return true;
7244 }
7245
7246 bool wxRichTextApplyStyle(wxTextAttr& destStyle, const wxTextAttr& style, wxTextAttr* compareWith)
7247 {
7248 return destStyle.Apply(style, compareWith);
7249 }
7250
7251 // Remove attributes
7252 bool wxRichTextRemoveStyle(wxTextAttr& destStyle, const wxTextAttr& style)
7253 {
7254 return wxTextAttr::RemoveStyle(destStyle, style);
7255 }
7256
7257 /// Combine two bitlists, specifying the bits of interest with separate flags.
7258 bool wxRichTextCombineBitlists(int& valueA, int valueB, int& flagsA, int flagsB)
7259 {
7260 return wxTextAttr::CombineBitlists(valueA, valueB, flagsA, flagsB);
7261 }
7262
7263 /// Compare two bitlists
7264 bool wxRichTextBitlistsEqPartial(int valueA, int valueB, int flags)
7265 {
7266 return wxTextAttr::BitlistsEqPartial(valueA, valueB, flags);
7267 }
7268
7269 /// Split into paragraph and character styles
7270 bool wxRichTextSplitParaCharStyles(const wxTextAttr& style, wxTextAttr& parStyle, wxTextAttr& charStyle)
7271 {
7272 return wxTextAttr::SplitParaCharStyles(style, parStyle, charStyle);
7273 }
7274
7275 /// Convert a decimal to Roman numerals
7276 wxString wxRichTextDecimalToRoman(long n)
7277 {
7278 static wxArrayInt decimalNumbers;
7279 static wxArrayString romanNumbers;
7280
7281 // Clean up arrays
7282 if (n == -1)
7283 {
7284 decimalNumbers.Clear();
7285 romanNumbers.Clear();
7286 return wxEmptyString;
7287 }
7288
7289 if (decimalNumbers.GetCount() == 0)
7290 {
7291 #define wxRichTextAddDecRom(n, r) decimalNumbers.Add(n); romanNumbers.Add(r);
7292
7293 wxRichTextAddDecRom(1000, wxT("M"));
7294 wxRichTextAddDecRom(900, wxT("CM"));
7295 wxRichTextAddDecRom(500, wxT("D"));
7296 wxRichTextAddDecRom(400, wxT("CD"));
7297 wxRichTextAddDecRom(100, wxT("C"));
7298 wxRichTextAddDecRom(90, wxT("XC"));
7299 wxRichTextAddDecRom(50, wxT("L"));
7300 wxRichTextAddDecRom(40, wxT("XL"));
7301 wxRichTextAddDecRom(10, wxT("X"));
7302 wxRichTextAddDecRom(9, wxT("IX"));
7303 wxRichTextAddDecRom(5, wxT("V"));
7304 wxRichTextAddDecRom(4, wxT("IV"));
7305 wxRichTextAddDecRom(1, wxT("I"));
7306 }
7307
7308 int i = 0;
7309 wxString roman;
7310
7311 while (n > 0 && i < 13)
7312 {
7313 if (n >= decimalNumbers[i])
7314 {
7315 n -= decimalNumbers[i];
7316 roman += romanNumbers[i];
7317 }
7318 else
7319 {
7320 i ++;
7321 }
7322 }
7323 if (roman.IsEmpty())
7324 roman = wxT("0");
7325 return roman;
7326 }
7327
7328 /*!
7329 * wxRichTextFileHandler
7330 * Base class for file handlers
7331 */
7332
7333 IMPLEMENT_CLASS(wxRichTextFileHandler, wxObject)
7334
7335 #if wxUSE_FFILE && wxUSE_STREAMS
7336 bool wxRichTextFileHandler::LoadFile(wxRichTextBuffer *buffer, const wxString& filename)
7337 {
7338 wxFFileInputStream stream(filename);
7339 if (stream.Ok())
7340 return LoadFile(buffer, stream);
7341
7342 return false;
7343 }
7344
7345 bool wxRichTextFileHandler::SaveFile(wxRichTextBuffer *buffer, const wxString& filename)
7346 {
7347 wxFFileOutputStream stream(filename);
7348 if (stream.Ok())
7349 return SaveFile(buffer, stream);
7350
7351 return false;
7352 }
7353 #endif // wxUSE_FFILE && wxUSE_STREAMS
7354
7355 /// Can we handle this filename (if using files)? By default, checks the extension.
7356 bool wxRichTextFileHandler::CanHandle(const wxString& filename) const
7357 {
7358 wxString path, file, ext;
7359 wxFileName::SplitPath(filename, & path, & file, & ext);
7360
7361 return (ext.Lower() == GetExtension());
7362 }
7363
7364 /*!
7365 * wxRichTextTextHandler
7366 * Plain text handler
7367 */
7368
7369 IMPLEMENT_CLASS(wxRichTextPlainTextHandler, wxRichTextFileHandler)
7370
7371 #if wxUSE_STREAMS
7372 bool wxRichTextPlainTextHandler::DoLoadFile(wxRichTextBuffer *buffer, wxInputStream& stream)
7373 {
7374 if (!stream.IsOk())
7375 return false;
7376
7377 wxString str;
7378 int lastCh = 0;
7379
7380 while (!stream.Eof())
7381 {
7382 int ch = stream.GetC();
7383
7384 if (!stream.Eof())
7385 {
7386 if (ch == 10 && lastCh != 13)
7387 str += wxT('\n');
7388
7389 if (ch > 0 && ch != 10)
7390 str += wxChar(ch);
7391
7392 lastCh = ch;
7393 }
7394 }
7395
7396 buffer->ResetAndClearCommands();
7397 buffer->Clear();
7398 buffer->AddParagraphs(str);
7399 buffer->UpdateRanges();
7400
7401 return true;
7402 }
7403
7404 bool wxRichTextPlainTextHandler::DoSaveFile(wxRichTextBuffer *buffer, wxOutputStream& stream)
7405 {
7406 if (!stream.IsOk())
7407 return false;
7408
7409 wxString text = buffer->GetText();
7410
7411 wxString newLine = wxRichTextLineBreakChar;
7412 text.Replace(newLine, wxT("\n"));
7413
7414 wxCharBuffer buf = text.ToAscii();
7415
7416 stream.Write((const char*) buf, text.length());
7417 return true;
7418 }
7419 #endif // wxUSE_STREAMS
7420
7421 /*
7422 * Stores information about an image, in binary in-memory form
7423 */
7424
7425 wxRichTextImageBlock::wxRichTextImageBlock()
7426 {
7427 Init();
7428 }
7429
7430 wxRichTextImageBlock::wxRichTextImageBlock(const wxRichTextImageBlock& block):wxObject()
7431 {
7432 Init();
7433 Copy(block);
7434 }
7435
7436 wxRichTextImageBlock::~wxRichTextImageBlock()
7437 {
7438 wxDELETEA(m_data);
7439 }
7440
7441 void wxRichTextImageBlock::Init()
7442 {
7443 m_data = NULL;
7444 m_dataSize = 0;
7445 m_imageType = wxBITMAP_TYPE_INVALID;
7446 }
7447
7448 void wxRichTextImageBlock::Clear()
7449 {
7450 wxDELETEA(m_data);
7451 m_dataSize = 0;
7452 m_imageType = wxBITMAP_TYPE_INVALID;
7453 }
7454
7455
7456 // Load the original image into a memory block.
7457 // If the image is not a JPEG, we must convert it into a JPEG
7458 // to conserve space.
7459 // If it's not a JPEG we can make use of 'image', already scaled, so we don't have to
7460 // load the image a 2nd time.
7461
7462 bool wxRichTextImageBlock::MakeImageBlock(const wxString& filename, wxBitmapType imageType,
7463 wxImage& image, bool convertToJPEG)
7464 {
7465 m_imageType = imageType;
7466
7467 wxString filenameToRead(filename);
7468 bool removeFile = false;
7469
7470 if (imageType == wxBITMAP_TYPE_INVALID)
7471 return false; // Could not determine image type
7472
7473 if ((imageType != wxBITMAP_TYPE_JPEG) && convertToJPEG)
7474 {
7475 wxString tempFile =
7476 wxFileName::CreateTempFileName(_("image"));
7477
7478 wxASSERT(!tempFile.IsEmpty());
7479
7480 image.SaveFile(tempFile, wxBITMAP_TYPE_JPEG);
7481 filenameToRead = tempFile;
7482 removeFile = true;
7483
7484 m_imageType = wxBITMAP_TYPE_JPEG;
7485 }
7486 wxFile file;
7487 if (!file.Open(filenameToRead))
7488 return false;
7489
7490 m_dataSize = (size_t) file.Length();
7491 file.Close();
7492
7493 if (m_data)
7494 delete[] m_data;
7495 m_data = ReadBlock(filenameToRead, m_dataSize);
7496
7497 if (removeFile)
7498 wxRemoveFile(filenameToRead);
7499
7500 return (m_data != NULL);
7501 }
7502
7503 // Make an image block from the wxImage in the given
7504 // format.
7505 bool wxRichTextImageBlock::MakeImageBlock(wxImage& image, wxBitmapType imageType, int quality)
7506 {
7507 m_imageType = imageType;
7508 image.SetOption(wxT("quality"), quality);
7509
7510 if (imageType == wxBITMAP_TYPE_INVALID)
7511 return false; // Could not determine image type
7512
7513 wxString tempFile = wxFileName::CreateTempFileName(_("image")) ;
7514 wxASSERT(!tempFile.IsEmpty());
7515
7516 if (!image.SaveFile(tempFile, m_imageType))
7517 {
7518 if (wxFileExists(tempFile))
7519 wxRemoveFile(tempFile);
7520 return false;
7521 }
7522
7523 wxFile file;
7524 if (!file.Open(tempFile))
7525 return false;
7526
7527 m_dataSize = (size_t) file.Length();
7528 file.Close();
7529
7530 if (m_data)
7531 delete[] m_data;
7532 m_data = ReadBlock(tempFile, m_dataSize);
7533
7534 wxRemoveFile(tempFile);
7535
7536 return (m_data != NULL);
7537 }
7538
7539
7540 // Write to a file
7541 bool wxRichTextImageBlock::Write(const wxString& filename)
7542 {
7543 return WriteBlock(filename, m_data, m_dataSize);
7544 }
7545
7546 void wxRichTextImageBlock::Copy(const wxRichTextImageBlock& block)
7547 {
7548 m_imageType = block.m_imageType;
7549 wxDELETEA(m_data);
7550 m_dataSize = block.m_dataSize;
7551 if (m_dataSize == 0)
7552 return;
7553
7554 m_data = new unsigned char[m_dataSize];
7555 unsigned int i;
7556 for (i = 0; i < m_dataSize; i++)
7557 m_data[i] = block.m_data[i];
7558 }
7559
7560 //// Operators
7561 void wxRichTextImageBlock::operator=(const wxRichTextImageBlock& block)
7562 {
7563 Copy(block);
7564 }
7565
7566 // Load a wxImage from the block
7567 bool wxRichTextImageBlock::Load(wxImage& image)
7568 {
7569 if (!m_data)
7570 return false;
7571
7572 // Read in the image.
7573 #if wxUSE_STREAMS
7574 wxMemoryInputStream mstream(m_data, m_dataSize);
7575 bool success = image.LoadFile(mstream, GetImageType());
7576 #else
7577 wxString tempFile = wxFileName::CreateTempFileName(_("image"));
7578 wxASSERT(!tempFile.IsEmpty());
7579
7580 if (!WriteBlock(tempFile, m_data, m_dataSize))
7581 {
7582 return false;
7583 }
7584 success = image.LoadFile(tempFile, GetImageType());
7585 wxRemoveFile(tempFile);
7586 #endif
7587
7588 return success;
7589 }
7590
7591 // Write data in hex to a stream
7592 bool wxRichTextImageBlock::WriteHex(wxOutputStream& stream)
7593 {
7594 const int bufSize = 512;
7595 char buf[bufSize+1];
7596
7597 int left = m_dataSize;
7598 int n, i, j;
7599 j = 0;
7600 while (left > 0)
7601 {
7602 if (left*2 > bufSize)
7603 {
7604 n = bufSize; left -= (bufSize/2);
7605 }
7606 else
7607 {
7608 n = left*2; left = 0;
7609 }
7610
7611 char* b = buf;
7612 for (i = 0; i < (n/2); i++)
7613 {
7614 wxDecToHex(m_data[j], b, b+1);
7615 b += 2; j ++;
7616 }
7617
7618 buf[n] = 0;
7619 stream.Write((const char*) buf, n);
7620 }
7621 return true;
7622 }
7623
7624 // Read data in hex from a stream
7625 bool wxRichTextImageBlock::ReadHex(wxInputStream& stream, int length, wxBitmapType imageType)
7626 {
7627 int dataSize = length/2;
7628
7629 if (m_data)
7630 delete[] m_data;
7631
7632 // create a null terminated temporary string:
7633 char str[3];
7634 str[2] = '\0';
7635
7636 m_data = new unsigned char[dataSize];
7637 int i;
7638 for (i = 0; i < dataSize; i ++)
7639 {
7640 str[0] = (char)stream.GetC();
7641 str[1] = (char)stream.GetC();
7642
7643 m_data[i] = (unsigned char)wxHexToDec(str);
7644 }
7645
7646 m_dataSize = dataSize;
7647 m_imageType = imageType;
7648
7649 return true;
7650 }
7651
7652 // Allocate and read from stream as a block of memory
7653 unsigned char* wxRichTextImageBlock::ReadBlock(wxInputStream& stream, size_t size)
7654 {
7655 unsigned char* block = new unsigned char[size];
7656 if (!block)
7657 return NULL;
7658
7659 stream.Read(block, size);
7660
7661 return block;
7662 }
7663
7664 unsigned char* wxRichTextImageBlock::ReadBlock(const wxString& filename, size_t size)
7665 {
7666 wxFileInputStream stream(filename);
7667 if (!stream.Ok())
7668 return NULL;
7669
7670 return ReadBlock(stream, size);
7671 }
7672
7673 // Write memory block to stream
7674 bool wxRichTextImageBlock::WriteBlock(wxOutputStream& stream, unsigned char* block, size_t size)
7675 {
7676 stream.Write((void*) block, size);
7677 return stream.IsOk();
7678
7679 }
7680
7681 // Write memory block to file
7682 bool wxRichTextImageBlock::WriteBlock(const wxString& filename, unsigned char* block, size_t size)
7683 {
7684 wxFileOutputStream outStream(filename);
7685 if (!outStream.Ok())
7686 return false;
7687
7688 return WriteBlock(outStream, block, size);
7689 }
7690
7691 // Gets the extension for the block's type
7692 wxString wxRichTextImageBlock::GetExtension() const
7693 {
7694 wxImageHandler* handler = wxImage::FindHandler(GetImageType());
7695 if (handler)
7696 return handler->GetExtension();
7697 else
7698 return wxEmptyString;
7699 }
7700
7701 #if wxUSE_DATAOBJ
7702
7703 /*!
7704 * The data object for a wxRichTextBuffer
7705 */
7706
7707 const wxChar *wxRichTextBufferDataObject::ms_richTextBufferFormatId = wxT("wxShape");
7708
7709 wxRichTextBufferDataObject::wxRichTextBufferDataObject(wxRichTextBuffer* richTextBuffer)
7710 {
7711 m_richTextBuffer = richTextBuffer;
7712
7713 // this string should uniquely identify our format, but is otherwise
7714 // arbitrary
7715 m_formatRichTextBuffer.SetId(GetRichTextBufferFormatId());
7716
7717 SetFormat(m_formatRichTextBuffer);
7718 }
7719
7720 wxRichTextBufferDataObject::~wxRichTextBufferDataObject()
7721 {
7722 delete m_richTextBuffer;
7723 }
7724
7725 // after a call to this function, the richTextBuffer is owned by the caller and it
7726 // is responsible for deleting it!
7727 wxRichTextBuffer* wxRichTextBufferDataObject::GetRichTextBuffer()
7728 {
7729 wxRichTextBuffer* richTextBuffer = m_richTextBuffer;
7730 m_richTextBuffer = NULL;
7731
7732 return richTextBuffer;
7733 }
7734
7735 wxDataFormat wxRichTextBufferDataObject::GetPreferredFormat(Direction WXUNUSED(dir)) const
7736 {
7737 return m_formatRichTextBuffer;
7738 }
7739
7740 size_t wxRichTextBufferDataObject::GetDataSize() const
7741 {
7742 if (!m_richTextBuffer)
7743 return 0;
7744
7745 wxString bufXML;
7746
7747 {
7748 wxStringOutputStream stream(& bufXML);
7749 if (!m_richTextBuffer->SaveFile(stream, wxRICHTEXT_TYPE_XML))
7750 {
7751 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
7752 return 0;
7753 }
7754 }
7755
7756 #if wxUSE_UNICODE
7757 wxCharBuffer buffer = bufXML.mb_str(wxConvUTF8);
7758 return strlen(buffer) + 1;
7759 #else
7760 return bufXML.Length()+1;
7761 #endif
7762 }
7763
7764 bool wxRichTextBufferDataObject::GetDataHere(void *pBuf) const
7765 {
7766 if (!pBuf || !m_richTextBuffer)
7767 return false;
7768
7769 wxString bufXML;
7770
7771 {
7772 wxStringOutputStream stream(& bufXML);
7773 if (!m_richTextBuffer->SaveFile(stream, wxRICHTEXT_TYPE_XML))
7774 {
7775 wxLogError(wxT("Could not write the buffer to an XML stream.\nYou may have forgotten to add the XML file handler."));
7776 return 0;
7777 }
7778 }
7779
7780 #if wxUSE_UNICODE
7781 wxCharBuffer buffer = bufXML.mb_str(wxConvUTF8);
7782 size_t len = strlen(buffer);
7783 memcpy((char*) pBuf, (const char*) buffer, len);
7784 ((char*) pBuf)[len] = 0;
7785 #else
7786 size_t len = bufXML.Length();
7787 memcpy((char*) pBuf, (const char*) bufXML.c_str(), len);
7788 ((char*) pBuf)[len] = 0;
7789 #endif
7790
7791 return true;
7792 }
7793
7794 bool wxRichTextBufferDataObject::SetData(size_t WXUNUSED(len), const void *buf)
7795 {
7796 wxDELETE(m_richTextBuffer);
7797
7798 wxString bufXML((const char*) buf, wxConvUTF8);
7799
7800 m_richTextBuffer = new wxRichTextBuffer;
7801
7802 wxStringInputStream stream(bufXML);
7803 if (!m_richTextBuffer->LoadFile(stream, wxRICHTEXT_TYPE_XML))
7804 {
7805 wxLogError(wxT("Could not read the buffer from an XML stream.\nYou may have forgotten to add the XML file handler."));
7806
7807 wxDELETE(m_richTextBuffer);
7808
7809 return false;
7810 }
7811 return true;
7812 }
7813
7814 #endif
7815 // wxUSE_DATAOBJ
7816
7817
7818 /*
7819 * wxRichTextFontTable
7820 * Manages quick access to a pool of fonts for rendering rich text
7821 */
7822
7823 WX_DECLARE_STRING_HASH_MAP_WITH_DECL(wxFont, wxRichTextFontTableHashMap, class WXDLLIMPEXP_RICHTEXT);
7824
7825 class wxRichTextFontTableData: public wxObjectRefData
7826 {
7827 public:
7828 wxRichTextFontTableData() {}
7829
7830 wxFont FindFont(const wxTextAttr& fontSpec);
7831
7832 wxRichTextFontTableHashMap m_hashMap;
7833 };
7834
7835 wxFont wxRichTextFontTableData::FindFont(const wxTextAttr& fontSpec)
7836 {
7837 wxString facename(fontSpec.GetFontFaceName());
7838 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()));
7839 wxRichTextFontTableHashMap::iterator entry = m_hashMap.find(spec);
7840
7841 if ( entry == m_hashMap.end() )
7842 {
7843 wxFont font(fontSpec.GetFontSize(), wxDEFAULT, fontSpec.GetFontStyle(), fontSpec.GetFontWeight(), fontSpec.GetFontUnderlined(), facename.c_str());
7844 m_hashMap[spec] = font;
7845 return font;
7846 }
7847 else
7848 {
7849 return entry->second;
7850 }
7851 }
7852
7853 IMPLEMENT_DYNAMIC_CLASS(wxRichTextFontTable, wxObject)
7854
7855 wxRichTextFontTable::wxRichTextFontTable()
7856 {
7857 m_refData = new wxRichTextFontTableData;
7858 }
7859
7860 wxRichTextFontTable::wxRichTextFontTable(const wxRichTextFontTable& table)
7861 : wxObject()
7862 {
7863 (*this) = table;
7864 }
7865
7866 wxRichTextFontTable::~wxRichTextFontTable()
7867 {
7868 UnRef();
7869 }
7870
7871 bool wxRichTextFontTable::operator == (const wxRichTextFontTable& table) const
7872 {
7873 return (m_refData == table.m_refData);
7874 }
7875
7876 void wxRichTextFontTable::operator= (const wxRichTextFontTable& table)
7877 {
7878 Ref(table);
7879 }
7880
7881 wxFont wxRichTextFontTable::FindFont(const wxTextAttr& fontSpec)
7882 {
7883 wxRichTextFontTableData* data = (wxRichTextFontTableData*) m_refData;
7884 if (data)
7885 return data->FindFont(fontSpec);
7886 else
7887 return wxFont();
7888 }
7889
7890 void wxRichTextFontTable::Clear()
7891 {
7892 wxRichTextFontTableData* data = (wxRichTextFontTableData*) m_refData;
7893 if (data)
7894 data->m_hashMap.clear();
7895 }
7896
7897 #endif
7898 // wxUSE_RICHTEXT