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