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