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