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