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