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