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