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