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