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