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