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