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