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