wxRTC no longer derives from wxTextCtrlBase; added wxRichTextAttr deriving from wxTex...
[wxWidgets.git] / src / richtext / richtextbuffer.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/richtext/richtextbuffer.cpp
3 // Purpose: Buffer for wxRichTextCtrl
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 2005-09-30
7 // RCS-ID: $Id$
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__
16 #pragma hdrstop
17 #endif
18
19 #if wxUSE_RICHTEXT
20
21 #include "wx/richtext/richtextbuffer.h"
22
23 #ifndef WX_PRECOMP
24 #include "wx/dc.h"
25 #include "wx/intl.h"
26 #include "wx/log.h"
27 #include "wx/dataobj.h"
28 #include "wx/module.h"
29 #endif
30
31 #include "wx/settings.h"
32 #include "wx/filename.h"
33 #include "wx/clipbrd.h"
34 #include "wx/wfstream.h"
35 #include "wx/mstream.h"
36 #include "wx/sstream.h"
37 #include "wx/textfile.h"
38 #include "wx/hashmap.h"
39 #include "wx/dynarray.h"
40
41 #include "wx/richtext/richtextctrl.h"
42 #include "wx/richtext/richtextstyles.h"
43 #include "wx/richtext/richtextimagedlg.h"
44
45 #include "wx/listimpl.cpp"
46
47 WX_DEFINE_LIST(wxRichTextObjectList)
48 WX_DEFINE_LIST(wxRichTextLineList)
49
50 // Switch off if the platform doesn't like it for some reason
51 #define wxRICHTEXT_USE_OPTIMIZED_DRAWING 1
52
53 // Use GetPartialTextExtents for platforms that support it natively
54 #define wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS 1
55
56 const wxChar wxRichTextLineBreakChar = (wxChar) 29;
57
58 // Helper classes for floating layout
59 struct 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
74 WX_DEFINE_SORTED_ARRAY(wxRichTextFloatRectMap*, wxRichTextFloatRectMapArray);
75
76 int wxRichTextFloatRectMapCmp(wxRichTextFloatRectMap* r1, wxRichTextFloatRectMap* r2)
77 {
78 return r1->startY - r2->startY;
79 }
80
81 class wxRichTextFloatCollector
82 {
83 public:
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);
114
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);
120
121 private:
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 */
134 int 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
167 int 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
185 wxRichTextFloatCollector::wxRichTextFloatCollector(int width) : m_left(wxRichTextFloatRectMapCmp), m_right(wxRichTextFloatRectMapCmp)
186 {
187 m_width = width;
188 m_para = NULL;
189 }
190
191 void wxRichTextFloatCollector::FreeFloatRectMapArray(wxRichTextFloatRectMapArray& array)
192 {
193 int len = array.GetCount();
194 for (int i = 0; i < len; i++)
195 delete array[i];
196 }
197
198 wxRichTextFloatCollector::~wxRichTextFloatCollector()
199 {
200 FreeFloatRectMapArray(m_left);
201 FreeFloatRectMapArray(m_right);
202 }
203
204 int 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
222 int wxRichTextFloatCollector::GetFitPosition(int direction, int start, int height) const
223 {
224 if (direction == wxTEXT_BOX_ATTR_FLOAT_LEFT)
225 return GetFitPosition(m_left, start, height);
226 else if (direction == wxTEXT_BOX_ATTR_FLOAT_RIGHT)
227 return GetFitPosition(m_right, start, height);
228 else
229 {
230 wxASSERT("Never should be here");
231 return start;
232 }
233 }
234
235 void wxRichTextFloatCollector::CollectFloat(wxRichTextParagraph* para, wxRichTextObject* floating)
236 {
237 int direction = floating->GetFloatDirection();
238
239 wxPoint pos = floating->GetPosition();
240 wxSize size = floating->GetCachedSize();
241 wxRichTextFloatRectMap *map = new wxRichTextFloatRectMap(pos.y, pos.y + size.y, size.x, floating);
242 switch (direction)
243 {
244 case wxTEXT_BOX_ATTR_FLOAT_NONE:
245 delete map;
246 break;
247 case wxTEXT_BOX_ATTR_FLOAT_LEFT:
248 // Just a not-enough simple assertion
249 wxASSERT (m_left.Index(map) == wxNOT_FOUND);
250 m_left.Add(map);
251 break;
252 case wxTEXT_BOX_ATTR_FLOAT_RIGHT:
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
264 void wxRichTextFloatCollector::CollectFloat(wxRichTextParagraph* para)
265 {
266 wxRichTextObjectList::compatibility_iterator node = para->GetChildren().GetFirst();
267 while (node)
268 {
269 wxRichTextObject* floating = node->GetData();
270
271 if (floating->IsFloating())
272 {
273 wxRichTextAnchoredObject* anchor = wxDynamicCast(floating, wxRichTextAnchoredObject);
274 if (anchor)
275 {
276 CollectFloat(para, floating);
277 }
278 }
279
280 node = node->GetNext();
281 }
282
283 m_para = para;
284 }
285
286 wxRichTextParagraph* wxRichTextFloatCollector::LastParagraph()
287 {
288 return m_para;
289 }
290
291 wxRect 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
310 int 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
325 void 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 }
344
345 void 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
353 int 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 }
372
373 return wxRICHTEXT_HITTEST_NONE;
374 }
375
376 int 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
386 // Helpers for efficiency
387 inline void wxCheckSetFont(wxDC& dc, const wxFont& font)
388 {
389 // JACS: did I do this some time ago when testing? Should we re-enable it?
390 #if 0
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() &&
398 font1.GetUnderlined() == font.GetUnderlined() &&
399 font1.GetFamily() == font.GetFamily() &&
400 font1.GetFaceName() == font.GetFaceName())
401 return;
402 }
403 #endif
404 dc.SetFont(font);
405 }
406
407 inline 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
420 inline 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
432 /*!
433 * wxRichTextObject
434 * This is the base for drawable objects.
435 */
436
437 IMPLEMENT_CLASS(wxRichTextObject, wxObject)
438
439 wxRichTextObject::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
451 wxRichTextObject::~wxRichTextObject()
452 {
453 }
454
455 void wxRichTextObject::Dereference()
456 {
457 m_refCount --;
458 if (m_refCount <= 0)
459 delete this;
460 }
461
462 /// Copy
463 void 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;
471 }
472
473 void wxRichTextObject::SetMargins(int margin)
474 {
475 m_leftMargin = m_rightMargin = m_topMargin = m_bottomMargin = margin;
476 }
477
478 void 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
486 // Convert units in tenths of a millimetre to device units
487 int wxRichTextObject::ConvertTenthsMMToPixels(wxDC& dc, int units) const
488 {
489 int p = ConvertTenthsMMToPixels(dc.GetPPI().x, units);
490
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
499 int wxRichTextObject::ConvertTenthsMMToPixels(int ppi, int units)
500 {
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
508 // Convert units in pixels to tenths of a millimetre
509 int 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
517 int 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
525 /// Dump to output stream for debugging
526 void 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
533 /// Gets the containing buffer
534 wxRichTextBuffer* 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 }
541
542 /*!
543 * wxRichTextCompositeObject
544 * This is the base for drawable objects.
545 */
546
547 IMPLEMENT_CLASS(wxRichTextCompositeObject, wxRichTextObject)
548
549 wxRichTextCompositeObject::wxRichTextCompositeObject(wxRichTextObject* parent):
550 wxRichTextObject(parent)
551 {
552 }
553
554 wxRichTextCompositeObject::~wxRichTextCompositeObject()
555 {
556 DeleteChildren();
557 }
558
559 /// Get the nth child
560 wxRichTextObject* 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
568 size_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
576 bool 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
591 bool wxRichTextCompositeObject::RemoveChild(wxRichTextObject* child, bool deleteChild)
592 {
593 wxRichTextObjectList::compatibility_iterator node = m_children.Find(child);
594 if (node)
595 {
596 wxRichTextObject* obj = node->GetData();
597 m_children.Erase(node);
598 if (deleteChild)
599 delete obj;
600
601 return true;
602 }
603 return false;
604 }
605
606 /// Delete all children
607 bool 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();
618 m_children.Erase(oldNode);
619 }
620
621 return true;
622 }
623
624 /// Get the child count
625 size_t wxRichTextCompositeObject::GetChildCount() const
626 {
627 return m_children.GetCount();
628 }
629
630 /// Copy
631 void 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();
641 wxRichTextObject* newChild = child->Clone();
642 newChild->SetParent(this);
643 m_children.Append(newChild);
644
645 node = node->GetNext();
646 }
647 }
648
649 /// Hit-testing: returns a flag indicating hit test details, plus
650 /// information about position
651 int 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
665 textPosition = GetRange().GetEnd()-1;
666 return wxRICHTEXT_HITTEST_AFTER|wxRICHTEXT_HITTEST_OUTSIDE;
667 }
668
669 /// Finds the absolute position and row height for the given character position
670 bool 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
687 void 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.
716 bool wxRichTextCompositeObject::DeleteRange(const wxRichTextRange& range)
717 {
718 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
719
720 while (node)
721 {
722 wxRichTextObject* obj = (wxRichTextObject*) node->GetData();
723 wxRichTextObjectList::compatibility_iterator next = node->GetNext();
724
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.
733
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.
744 RemoveChild(obj, true);
745 }
746 }
747
748 node = next;
749 }
750
751 return true;
752 }
753
754 /// Get any text in this object for the given range
755 wxString 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());
766
767 wxString childText = child->GetTextForRange(childRange);
768
769 text += childText;
770 }
771 node = node->GetNext();
772 }
773
774 return text;
775 }
776
777 /// Recursively merge all pieces that can be merged.
778 bool wxRichTextCompositeObject::Defragment(const wxRichTextRange& range)
779 {
780 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
781 while (node)
782 {
783 wxRichTextObject* child = node->GetData();
784 if (range == wxRICHTEXT_ALL || !child->GetRange().IsOutside(range))
785 {
786 wxRichTextCompositeObject* composite = wxDynamicCast(child, wxRichTextCompositeObject);
787 if (composite)
788 composite->Defragment();
789
790 if (node->GetNext())
791 {
792 wxRichTextObject* nextChild = node->GetNext()->GetData();
793 if (child->CanMerge(nextChild) && child->Merge(nextChild))
794 {
795 nextChild->Dereference();
796 m_children.Erase(node->GetNext());
797
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();
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
815 void 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
832 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBox, wxRichTextCompositeObject)
833
834 wxRichTextBox::wxRichTextBox(wxRichTextObject* parent):
835 wxRichTextCompositeObject(parent)
836 {
837 }
838
839 /// Draw the item
840 bool 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
856 bool wxRichTextBox::Layout(wxDC& dc, const wxRect& rect, int style)
857 {
858 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
859 while (node)
860 {
861 wxRichTextObject* child = node->GetData();
862 child->Layout(dc, rect, style);
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.
871 bool wxRichTextBox::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, int flags, wxPoint position, wxArrayInt* partialExtents) const
872 {
873 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
874 if (node)
875 {
876 wxRichTextObject* child = node->GetData();
877 return child->GetRangeSize(range, size, descent, dc, flags, position, partialExtents);
878 }
879 else
880 return false;
881 }
882
883 /// Copy
884 void 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
895 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraphLayoutBox, wxRichTextBox)
896
897 wxRichTextParagraphLayoutBox::wxRichTextParagraphLayoutBox(wxRichTextObject* parent):
898 wxRichTextBox(parent)
899 {
900 Init();
901 }
902
903 wxRichTextParagraphLayoutBox::~wxRichTextParagraphLayoutBox()
904 {
905 if (m_floatCollector)
906 {
907 delete m_floatCollector;
908 m_floatCollector = NULL;
909 }
910 }
911
912 /// Initialize the object.
913 void 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
920 m_invalidRange.SetRange(-1, -1);
921 m_leftMargin = 4;
922 m_rightMargin = 4;
923 m_topMargin = 4;
924 m_bottomMargin = 4;
925 m_partialParagraph = false;
926 m_floatCollector = NULL;
927 }
928
929 // Gather information about floating objects
930 bool 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 }
944
945 return true;
946 }
947
948 // HitTest
949 int 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);
954
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
962 void 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
968 void wxRichTextParagraphLayoutBox::MoveAnchoredObjectToParagraph(wxRichTextParagraph* from, wxRichTextParagraph* to, wxRichTextAnchoredObject* obj)
969 {
970 if (from == to)
971 return;
972
973 from->RemoveChild(obj);
974 to->AppendChild(obj);
975 }
976
977 /// Draw the item
978 bool wxRichTextParagraphLayoutBox::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextRange& selectionRange, const wxRect& rect, int descent, int style)
979 {
980 DrawFloats(dc, range, selectionRange, rect, descent, style);
981 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
982 while (node)
983 {
984 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
985 wxASSERT (child != NULL);
986
987 if (child && !child->GetRange().IsOutside(range))
988 {
989 wxRect childRect(child->GetPosition(), child->GetCachedSize());
990
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())
997 {
998 // Skip
999 }
1000 else
1001 child->Draw(dc, range, selectionRange, rect, descent, style);
1002 }
1003
1004 node = node->GetNext();
1005 }
1006 return true;
1007 }
1008
1009 /// Lay the item out
1010 bool wxRichTextParagraphLayoutBox::Layout(wxDC& dc, const wxRect& rect, int style)
1011 {
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:
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.
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,
1040 rect.y + m_topMargin,
1041 rect.width - m_leftMargin - m_rightMargin,
1042 rect.height - m_topMargin - m_bottomMargin);
1043
1044 int maxWidth = 0;
1045
1046 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
1047
1048 bool layoutAll = true;
1049
1050 // Get invalid range, rounding to paragraph start/end.
1051 wxRichTextRange invalidRange = GetInvalidRange(true);
1052
1053 if (invalidRange == wxRICHTEXT_NONE && !formatRect)
1054 return true;
1055
1056 if (invalidRange == wxRICHTEXT_ALL)
1057 layoutAll = true;
1058 else // If we know what range is affected, start laying out from that point on.
1059 if (invalidRange.GetStart() >= GetRange().GetStart())
1060 {
1061 wxRichTextParagraph* firstParagraph = GetParagraphAtPosition(invalidRange.GetStart());
1062 if (firstParagraph)
1063 {
1064 wxRichTextObjectList::compatibility_iterator firstNode = m_children.Find(firstParagraph);
1065 wxRichTextObjectList::compatibility_iterator previousNode;
1066 if ( firstNode )
1067 previousNode = firstNode->GetPrevious();
1068 if (firstNode)
1069 {
1070 if (previousNode)
1071 {
1072 wxRichTextParagraph* previousParagraph = wxDynamicCast(previousNode->GetData(), wxRichTextParagraph);
1073 availableSpace.y = previousParagraph->GetPosition().y + previousParagraph->GetCachedSize().y;
1074 }
1075
1076 // Now we're going to start iterating from the first affected paragraph.
1077 node = firstNode;
1078
1079 layoutAll = false;
1080 }
1081 }
1082 }
1083
1084 UpdateFloatingObjects(availableSpace.width, node ? node->GetData() : (wxRichTextObject*) NULL);
1085
1086 // A way to force speedy rest-of-buffer layout (the 'else' below)
1087 bool forceQuickLayout = false;
1088
1089 while (node)
1090 {
1091 // Assume this box only contains paragraphs
1092
1093 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
1094 wxCHECK_MSG( child, false, wxT("Unknown object in layout") );
1095
1096 // TODO: what if the child hasn't been laid out (e.g. involved in Undo) but still has 'old' lines
1097 if ( !forceQuickLayout &&
1098 (layoutAll ||
1099 child->GetLines().IsEmpty() ||
1100 !child->GetRange().IsOutside(invalidRange)) )
1101 {
1102 child->Layout(dc, availableSpace, style);
1103
1104 // Layout must set the cached size
1105 availableSpace.y += child->GetCachedSize().y;
1106 maxWidth = wxMax(maxWidth, child->GetCachedSize().x);
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;
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.
1120
1121 int inc = availableSpace.y - child->GetPosition().y;
1122
1123 while (node)
1124 {
1125 wxRichTextParagraph* child = wxDynamicCast(node->GetData(), wxRichTextParagraph);
1126 if (child)
1127 {
1128 if (child->GetLines().GetCount() == 0)
1129 child->Layout(dc, availableSpace, style);
1130 else
1131 child->SetPosition(wxPoint(child->GetPosition().x, child->GetPosition().y + inc));
1132
1133 availableSpace.y += child->GetCachedSize().y;
1134 maxWidth = wxMax(maxWidth, child->GetCachedSize().x);
1135 }
1136
1137 node = node->GetNext();
1138 }
1139 break;
1140 }
1141
1142 node = node->GetNext();
1143 }
1144
1145 SetCachedSize(wxSize(maxWidth, availableSpace.y));
1146
1147 m_dirty = false;
1148 m_invalidRange = wxRICHTEXT_NONE;
1149
1150 return true;
1151 }
1152
1153 /// Copy
1154 void wxRichTextParagraphLayoutBox::Copy(const wxRichTextParagraphLayoutBox& obj)
1155 {
1156 wxRichTextBox::Copy(obj);
1157
1158 m_partialParagraph = obj.m_partialParagraph;
1159 m_defaultAttributes = obj.m_defaultAttributes;
1160 }
1161
1162 /// Get/set the size for the given range.
1163 bool wxRichTextParagraphLayoutBox::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, int flags, wxPoint position, wxArrayInt* WXUNUSED(partialExtents)) const
1164 {
1165 wxSize sz;
1166
1167 wxRichTextObjectList::compatibility_iterator startPara = wxRichTextObjectList::compatibility_iterator();
1168 wxRichTextObjectList::compatibility_iterator endPara = wxRichTextObjectList::compatibility_iterator();
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;
1219 child->GetRangeSize(rangeToFind, childSize, childDescent, dc, flags, position);
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
1236 wxRichTextParagraph* 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
1262 wxRichTextLine* 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 {
1271 wxRichTextObject* obj = (wxRichTextObject*) node->GetData();
1272 if (obj->GetRange().Contains(pos))
1273 {
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();
1282
1283 wxRichTextRange range = line->GetAbsoluteRange();
1284
1285 if (range.Contains(pos) ||
1286
1287 // If the position is end-of-paragraph, then return the last line of
1288 // of the paragraph.
1289 ((range.GetEnd() == child->GetRange().GetEnd()-1) && (pos == child->GetRange().GetEnd())))
1290 return line;
1291
1292 node2 = node2->GetNext();
1293 }
1294 }
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.
1307 wxRichTextLine* 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();
1326 }
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
1340 int 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
1358 wxRichTextParagraph* wxRichTextParagraphLayoutBox::GetParagraphForLine(wxRichTextLine* line) const
1359 {
1360 return GetParagraphAtPosition(line->GetAbsoluteRange().GetStart());
1361 }
1362
1363 /// Get the line size at the given position
1364 wxSize 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
1377 wxRichTextRange wxRichTextParagraphLayoutBox::AddParagraph(const wxString& text, wxRichTextAttr* paraStyle)
1378 {
1379 // Don't use the base style, just the default style, and the base style will
1380 // be combined at display time.
1381 // Divide into paragraph and character styles.
1382
1383 wxRichTextAttr defaultCharStyle;
1384 wxRichTextAttr defaultParaStyle;
1385
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
1397 wxRichTextAttr* pStyle = paraStyle ? paraStyle : (wxRichTextAttr*) & defaultParaStyle;
1398 wxRichTextAttr* cStyle = & defaultCharStyle;
1399
1400 wxRichTextParagraph* para = new wxRichTextParagraph(text, this, pStyle, cStyle);
1401
1402 AppendChild(para);
1403
1404 UpdateRanges();
1405 SetDirty(true);
1406
1407 return para->GetRange();
1408 }
1409
1410 /// Adds multiple paragraphs, based on newlines.
1411 wxRichTextRange wxRichTextParagraphLayoutBox::AddParagraphs(const wxString& text, wxRichTextAttr* paraStyle)
1412 {
1413 // Don't use the base style, just the default style, and the base style will
1414 // be combined at display time.
1415 // Divide into paragraph and character styles.
1416
1417 wxRichTextAttr defaultCharStyle;
1418 wxRichTextAttr defaultParaStyle;
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);
1430
1431 wxRichTextAttr* pStyle = paraStyle ? paraStyle : (wxRichTextAttr*) & defaultParaStyle;
1432 wxRichTextAttr* cStyle = & defaultCharStyle;
1433
1434 wxRichTextParagraph* firstPara = NULL;
1435 wxRichTextParagraph* lastPara = NULL;
1436
1437 wxRichTextRange range(-1, -1);
1438
1439 size_t i = 0;
1440 size_t len = text.length();
1441 wxString line;
1442 wxRichTextParagraph* para = new wxRichTextParagraph(wxEmptyString, this, pStyle, cStyle);
1443
1444 AppendChild(para);
1445
1446 firstPara = para;
1447 lastPara = para;
1448
1449 while (i < len)
1450 {
1451 wxChar ch = text[i];
1452 if (ch == wxT('\n') || ch == wxT('\r'))
1453 {
1454 if (i != (len-1))
1455 {
1456 wxRichTextPlainText* plainText = (wxRichTextPlainText*) para->GetChildren().GetFirst()->GetData();
1457 plainText->SetText(line);
1458
1459 para = new wxRichTextParagraph(wxEmptyString, this, pStyle, cStyle);
1460
1461 AppendChild(para);
1462
1463 lastPara = para;
1464 line = wxEmptyString;
1465 }
1466 }
1467 else
1468 line += ch;
1469
1470 i ++;
1471 }
1472
1473 if (!line.empty())
1474 {
1475 wxRichTextPlainText* plainText = (wxRichTextPlainText*) para->GetChildren().GetFirst()->GetData();
1476 plainText->SetText(line);
1477 }
1478
1479 UpdateRanges();
1480
1481 SetDirty(false);
1482
1483 return wxRichTextRange(firstPara->GetRange().GetStart(), lastPara->GetRange().GetEnd());
1484 }
1485
1486 /// Convenience function to add an image
1487 wxRichTextRange wxRichTextParagraphLayoutBox::AddImage(const wxImage& image, wxRichTextAttr* paraStyle)
1488 {
1489 // Don't use the base style, just the default style, and the base style will
1490 // be combined at display time.
1491 // Divide into paragraph and character styles.
1492
1493 wxRichTextAttr defaultCharStyle;
1494 wxRichTextAttr defaultParaStyle;
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);
1506
1507 wxRichTextAttr* pStyle = paraStyle ? paraStyle : (wxRichTextAttr*) & defaultParaStyle;
1508 wxRichTextAttr* cStyle = & defaultCharStyle;
1509
1510 wxRichTextParagraph* para = new wxRichTextParagraph(this, pStyle);
1511 AppendChild(para);
1512 para->AppendChild(new wxRichTextImage(image, this, cStyle));
1513
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.
1524
1525 bool wxRichTextParagraphLayoutBox::InsertFragment(long position, wxRichTextParagraphLayoutBox& fragment)
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 {
1533 wxRichTextAttr originalAttr = para->GetAttributes();
1534
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();
1559
1560 if (!nextObject)
1561 {
1562 // Append
1563 para->AppendChild(newObj);
1564 }
1565 else
1566 {
1567 // Insert before nextObject
1568 para->InsertChild(newObj, nextObject);
1569 }
1570
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
1602 if (!(fragment.GetAttributes().GetFlags() & wxTEXT_ATTR_KEEP_FIRST_PARA_STYLE))
1603 para->SetAttributes(firstPara->GetAttributes());
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.
1608 wxRichTextAttr emptyParagraphAttributes;
1609
1610 wxRichTextObjectList::compatibility_iterator objectNode = firstPara->GetChildren().GetFirst();
1611
1612 if (objectNode && firstPara->GetChildren().GetCount() == 1 && objectNode->GetData()->IsEmpty())
1613 emptyParagraphAttributes = objectNode->GetData()->GetAttributes();
1614
1615 while (objectNode)
1616 {
1617 wxRichTextObject* newObj = objectNode->GetData()->Clone();
1618
1619 // Append
1620 para->AppendChild(newObj);
1621
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
1634 bool needExtraPara = (!i || !fragment.GetPartialParagraph());
1635
1636 // If there was only one paragraph, we need to insert a new one.
1637 while (i)
1638 {
1639 wxRichTextParagraph* para = wxDynamicCast(i->GetData(), wxRichTextParagraph);
1640 wxASSERT( para != NULL );
1641
1642 finalPara = (wxRichTextParagraph*) para->Clone();
1643
1644 if (nextParagraph)
1645 InsertChild(finalPara, nextParagraph);
1646 else
1647 AppendChild(finalPara);
1648
1649 i = i->GetNext();
1650 }
1651
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;
1657
1658 if (nextParagraph)
1659 InsertChild(finalPara, nextParagraph);
1660 else
1661 AppendChild(finalPara);
1662 }
1663
1664 // 4. Add back the remaining content.
1665 if (finalPara)
1666 {
1667 if (nextObject)
1668 finalPara->MoveFromList(savedObjects);
1669
1670 // Ensure there's at least one object
1671 if (finalPara->GetChildCount() == 0)
1672 {
1673 wxRichTextPlainText* text = new wxRichTextPlainText(wxEmptyString);
1674 text->SetAttributes(emptyParagraphAttributes);
1675
1676 finalPara->AppendChild(text);
1677 }
1678 }
1679
1680 if ((fragment.GetAttributes().GetFlags() & wxTEXT_ATTR_KEEP_FIRST_PARA_STYLE) && firstPara)
1681 finalPara->SetAttributes(firstPara->GetAttributes());
1682 else if (finalPara && finalPara != para)
1683 finalPara->SetAttributes(originalAttr);
1684
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 );
1696
1697 AppendChild(para->Clone());
1698
1699 i = i->GetNext();
1700 }
1701
1702 return true;
1703 }
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.
1708 bool wxRichTextParagraphLayoutBox::CopyFragment(const wxRichTextRange& range, wxRichTextParagraphLayoutBox& fragment)
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());
1719 }
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.
1777 long 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();
1796 wxRichTextRange lineRange = line->GetAbsoluteRange();
1797
1798 if (lineRange.Contains(pos) || pos == lineRange.GetStart())
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).
1803 if (lineRange.GetStart() == pos && !startOfLine && child->GetRange().GetStart() != pos)
1804 return lineCount - 1;
1805 else
1806 return lineCount;
1807 }
1808
1809 lineCount ++;
1810
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.
1828 wxRichTextLine* 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();
1844
1845 if (lineCount == lineNumber)
1846 return line;
1847
1848 lineCount ++;
1849
1850 node2 = node2->GetNext();
1851 }
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.
1864 bool wxRichTextParagraphLayoutBox::DeleteRange(const wxRichTextRange& range)
1865 {
1866 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
1867
1868 wxRichTextParagraph* firstPara = NULL;
1869 while (node)
1870 {
1871 wxRichTextParagraph* obj = wxDynamicCast(node->GetData(), wxRichTextParagraph);
1872 wxASSERT (obj != NULL);
1873
1874 wxRichTextObjectList::compatibility_iterator next = node->GetNext();
1875
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
1883 wxRichTextRange thisRange = obj->GetRange();
1884 wxRichTextAttr thisAttr = obj->GetAttributes();
1885
1886 // If the whole paragraph is within the range to delete,
1887 // delete the whole thing.
1888 if (range.GetStart() <= thisRange.GetStart() && range.GetEnd() >= thisRange.GetEnd())
1889 {
1890 // Delete the whole object
1891 RemoveChild(obj, true);
1892 obj = NULL;
1893 }
1894 else if (!firstPara)
1895 firstPara = obj;
1896
1897 // If the range includes the paragraph end, we need to join this
1898 // and the next paragraph.
1899 if (range.GetEnd() <= thisRange.GetEnd())
1900 {
1901 // We need to move the objects from the next paragraph
1902 // to this paragraph
1903
1904 wxRichTextParagraph* nextParagraph = NULL;
1905 if ((range.GetEnd() < thisRange.GetEnd()) && obj)
1906 nextParagraph = obj;
1907 else
1908 {
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 }
1913
1914 bool applyFinalParagraphStyle = firstPara && nextParagraph && nextParagraph != firstPara;
1915
1916 wxRichTextAttr nextParaAttr;
1917 if (applyFinalParagraphStyle)
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 }
1926
1927 if (firstPara && nextParagraph && firstPara != nextParagraph)
1928 {
1929 // Move the objects to the previous para
1930 wxRichTextObjectList::compatibility_iterator node1 = nextParagraph->GetChildren().GetFirst();
1931
1932 while (node1)
1933 {
1934 wxRichTextObject* obj1 = node1->GetData();
1935
1936 firstPara->AppendChild(obj1);
1937
1938 wxRichTextObjectList::compatibility_iterator next1 = node1->GetNext();
1939 nextParagraph->GetChildren().Erase(node1);
1940
1941 node1 = next1;
1942 }
1943
1944 // Delete the paragraph
1945 RemoveChild(nextParagraph, true);
1946 }
1947
1948 // Avoid empty paragraphs
1949 if (firstPara && firstPara->GetChildren().GetCount() == 0)
1950 {
1951 wxRichTextPlainText* text = new wxRichTextPlainText(wxEmptyString);
1952 firstPara->AppendChild(text);
1953 }
1954
1955 if (applyFinalParagraphStyle)
1956 firstPara->SetAttributes(nextParaAttr);
1957
1958 return true;
1959 }
1960 }
1961
1962 node = next;
1963 }
1964
1965 return true;
1966 }
1967
1968 /// Get any text in this object for the given range
1969 wxString 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 {
1979 wxRichTextRange childRange = range;
1980 childRange.LimitTo(child->GetRange());
1981
1982 wxString childText = child->GetTextForRange(childRange);
1983
1984 text += childText;
1985
1986 if ((childRange.GetEnd() == child->GetRange().GetEnd()) && node->GetNext())
1987 text += wxT("\n");
1988
1989 lineCount ++;
1990 }
1991 node = node->GetNext();
1992 }
1993
1994 return text;
1995 }
1996
1997 /// Get all the text
1998 wxString wxRichTextParagraphLayoutBox::GetText() const
1999 {
2000 return GetTextForRange(GetRange());
2001 }
2002
2003 /// Get the paragraph by number
2004 wxRichTextParagraph* wxRichTextParagraphLayoutBox::GetParagraphAtLine(long paragraphNumber) const
2005 {
2006 if ((size_t) paragraphNumber >= GetChildCount())
2007 return NULL;
2008
2009 return (wxRichTextParagraph*) GetChild((size_t) paragraphNumber);
2010 }
2011
2012 /// Get the length of the paragraph
2013 int 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
2023 wxString 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.
2033 long 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
2045 bool 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.
2072 wxRichTextObject* wxRichTextParagraphLayoutBox::GetLeafObjectAtPosition(long position) const
2073 {
2074 wxRichTextParagraph* para = GetParagraphAtPosition(position);
2075 if (para)
2076 {
2077 wxRichTextObjectList::compatibility_iterator node = para->GetChildren().GetFirst();
2078
2079 while (node)
2080 {
2081 wxRichTextObject* child = node->GetData();
2082 if (child->GetRange().Contains(position))
2083 return child;
2084
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
2094 bool wxRichTextParagraphLayoutBox::SetStyle(const wxRichTextRange& range, const wxRichTextAttr& style, int flags)
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
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);
2108 bool resetExistingStyle = ((flags & wxRICHTEXT_SETSTYLE_RESET) != 0);
2109 bool removeStyle = ((flags & wxRICHTEXT_SETSTYLE_REMOVE) != 0);
2110
2111 // Apply paragraph style first, if any
2112 wxRichTextAttr wholeStyle(style);
2113
2114 if (!removeStyle && wholeStyle.HasParagraphStyleName() && GetStyleSheet())
2115 {
2116 wxRichTextParagraphStyleDefinition* def = GetStyleSheet()->FindParagraphStyle(wholeStyle.GetParagraphStyleName());
2117 if (def)
2118 wxRichTextApplyStyle(wholeStyle, def->GetStyleMergedWithBase(GetStyleSheet()));
2119 }
2120
2121 // Limit the attributes to be set to the content to only character attributes.
2122 wxRichTextAttr characterAttributes(wholeStyle);
2123 characterAttributes.SetFlags(characterAttributes.GetFlags() & (wxTEXT_ATTR_CHARACTER));
2124
2125 if (!removeStyle && characterAttributes.HasCharacterStyleName() && GetStyleSheet())
2126 {
2127 wxRichTextCharacterStyleDefinition* def = GetStyleSheet()->FindCharacterStyle(characterAttributes.GetCharacterStyleName());
2128 if (def)
2129 wxRichTextApplyStyle(characterAttributes, def->GetStyleMergedWithBase(GetStyleSheet()));
2130 }
2131
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;
2138
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.
2162 wxRichTextParagraph* newPara wxDUMMY_INITIALIZE(NULL);
2163
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;
2174
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)
2178 {
2179 if (removeStyle)
2180 {
2181 // Removes the given style from the paragraph
2182 wxRichTextRemoveStyle(newPara->GetAttributes(), style);
2183 }
2184 else if (resetExistingStyle)
2185 newPara->GetAttributes() = wholeStyle;
2186 else
2187 {
2188 if (applyMinimal)
2189 {
2190 // Only apply attributes that will make a difference to the combined
2191 // style as seen on the display
2192 wxRichTextAttr combinedAttr(para->GetCombinedAttributes());
2193 wxRichTextApplyStyle(newPara->GetAttributes(), wholeStyle, & combinedAttr);
2194 }
2195 else
2196 wxRichTextApplyStyle(newPara->GetAttributes(), wholeStyle);
2197 }
2198 }
2199
2200 // When applying paragraph styles dynamically, don't change the text objects' attributes
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
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
2210 if (!parasOnly && (characterStyle|charactersOnly) && range.GetStart() != newPara->GetRange().GetEnd())
2211 {
2212 wxRichTextRange childRange(range);
2213 childRange.LimitTo(newPara->GetRange());
2214
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
2219 wxRichTextObject* firstObject wxDUMMY_INITIALIZE(NULL);
2220 wxRichTextObject* lastObject wxDUMMY_INITIALIZE(NULL);
2221
2222 if (childRange.GetStart() == newPara->GetRange().GetStart())
2223 firstObject = newPara->GetChildren().GetFirst()->GetData();
2224 else
2225 firstObject = newPara->SplitAt(range.GetStart());
2226
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 ++;
2231
2232 // Find last object
2233 if (splitPoint == newPara->GetRange().GetEnd())
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);
2239
2240 wxASSERT(firstObject != NULL);
2241 wxASSERT(lastObject != NULL);
2242
2243 if (!firstObject || !lastObject)
2244 continue;
2245
2246 wxRichTextObjectList::compatibility_iterator firstNode = newPara->GetChildren().Find(firstObject);
2247 wxRichTextObjectList::compatibility_iterator lastNode = newPara->GetChildren().Find(lastObject);
2248
2249 wxASSERT(firstNode);
2250 wxASSERT(lastNode);
2251
2252 wxRichTextObjectList::compatibility_iterator node2 = firstNode;
2253
2254 while (node2)
2255 {
2256 wxRichTextObject* child = node2->GetData();
2257
2258 if (removeStyle)
2259 {
2260 // Removes the given style from the paragraph
2261 wxRichTextRemoveStyle(child->GetAttributes(), style);
2262 }
2263 else if (resetExistingStyle)
2264 child->GetAttributes() = characterAttributes;
2265 else
2266 {
2267 if (applyMinimal)
2268 {
2269 // Only apply attributes that will make a difference to the combined
2270 // style as seen on the display
2271 wxRichTextAttr combinedAttr(newPara->GetCombinedAttributes(child->GetAttributes()));
2272 wxRichTextApplyStyle(child->GetAttributes(), characterAttributes, & combinedAttr);
2273 }
2274 else
2275 wxRichTextApplyStyle(child->GetAttributes(), characterAttributes);
2276 }
2277
2278 if (node2 == lastNode)
2279 break;
2280
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
2297 void wxRichTextParagraphLayoutBox::SetImageStyle(wxRichTextImage *image, const wxRichTextAttr& textAttr, int flags)
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;
2304 wxRichTextAttr oldTextAttr = image->GetAttributes();
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());
2311 image->SetAttributes(textAttr);
2312
2313 // Set the new attribute
2314 newPara = new wxRichTextParagraph(*para);
2315 action->GetNewParagraphs().AppendChild(newPara);
2316 // Change back to the old one
2317 image->SetAttributes(oldTextAttr);
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
2327 /// Get the text attributes for this position.
2328 bool wxRichTextParagraphLayoutBox::GetStyle(long position, wxRichTextAttr& style)
2329 {
2330 return DoGetStyle(position, style, true);
2331 }
2332
2333 bool wxRichTextParagraphLayoutBox::GetUncombinedStyle(long position, wxRichTextAttr& style)
2334 {
2335 return DoGetStyle(position, style, false);
2336 }
2337
2338 /// Implementation helper for GetStyle. If combineStyles is true, combine base, paragraph and
2339 /// context attributes.
2340 bool wxRichTextParagraphLayoutBox::DoGetStyle(long position, wxRichTextAttr& style, bool combineStyles)
2341 {
2342 wxRichTextObject* obj wxDUMMY_INITIALIZE(NULL);
2343
2344 if (style.IsParagraphStyle())
2345 {
2346 obj = GetParagraphAtPosition(position);
2347 if (obj)
2348 {
2349 if (combineStyles)
2350 {
2351 // Start with the base style
2352 style = GetAttributes();
2353
2354 // Apply the paragraph style
2355 wxRichTextApplyStyle(style, obj->GetAttributes());
2356 }
2357 else
2358 style = obj->GetAttributes();
2359
2360 return true;
2361 }
2362 }
2363 else
2364 {
2365 obj = GetLeafObjectAtPosition(position);
2366 if (obj)
2367 {
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();
2375
2376 return true;
2377 }
2378 }
2379 return false;
2380 }
2381
2382 static 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.
2389 bool 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.
2400 bool wxRichTextParagraphLayoutBox::GetStyleForRange(const wxRichTextRange& range, wxRichTextAttr& style)
2401 {
2402 style = wxRichTextAttr();
2403
2404 wxRichTextAttr clashingAttr;
2405 wxRichTextAttr absentAttrPara, absentAttrChar;
2406
2407 wxRichTextObjectList::compatibility_iterator node = GetChildren().GetFirst();
2408 while (node)
2409 {
2410 wxRichTextParagraph* para = (wxRichTextParagraph*) node->GetData();
2411 if (!(para->GetRange().GetStart() > range.GetEnd() || para->GetRange().GetEnd() < range.GetStart()))
2412 {
2413 if (para->GetChildren().GetCount() == 0)
2414 {
2415 wxRichTextAttr paraStyle = para->GetCombinedAttributes();
2416
2417 CollectStyle(style, paraStyle, clashingAttr, absentAttrPara);
2418 }
2419 else
2420 {
2421 wxRichTextRange paraRange(para->GetRange());
2422 paraRange.LimitTo(range);
2423
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);
2428
2429 wxRichTextObjectList::compatibility_iterator childNode = para->GetChildren().GetFirst();
2430
2431 while (childNode)
2432 {
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());
2437
2438 // Now collect character attributes only
2439 childStyle.SetFlags(childStyle.GetFlags() & wxTEXT_ATTR_CHARACTER);
2440
2441 CollectStyle(style, childStyle, clashingAttr, absentAttrChar);
2442 }
2443
2444 childNode = childNode->GetNext();
2445 }
2446 }
2447 }
2448 node = node->GetNext();
2449 }
2450 return true;
2451 }
2452
2453 /// Set default style
2454 bool wxRichTextParagraphLayoutBox::SetDefaultStyle(const wxRichTextAttr& style)
2455 {
2456 m_defaultAttributes = style;
2457 return true;
2458 }
2459
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.
2464 bool wxRichTextParagraphLayoutBox::HasCharacterAttributes(const wxRichTextRange& range, const wxRichTextAttr& style) const
2465 {
2466 int foundCount = 0;
2467 int matchingCount = 0;
2468
2469 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
2470 while (node)
2471 {
2472 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
2473 wxASSERT (para != NULL);
2474
2475 if (para)
2476 {
2477 // Stop searching if we're beyond the range of interest
2478 if (para->GetRange().GetStart() > range.GetEnd())
2479 return foundCount == matchingCount && foundCount != 0;
2480
2481 if (!para->GetRange().IsOutside(range))
2482 {
2483 wxRichTextObjectList::compatibility_iterator node2 = para->GetChildren().GetFirst();
2484
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);
2492
2493 if (!childRange.IsOutside(range) && child->IsKindOf(CLASSINFO(wxRichTextPlainText)))
2494 {
2495 foundCount ++;
2496 wxRichTextAttr textAttr = para->GetCombinedAttributes(child->GetAttributes());
2497
2498 if (wxTextAttrEqPartial(textAttr, style))
2499 matchingCount ++;
2500 }
2501
2502 node2 = node2->GetNext();
2503 }
2504 }
2505 }
2506
2507 node = node->GetNext();
2508 }
2509
2510 return foundCount == matchingCount && foundCount != 0;
2511 }
2512
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.
2517 bool 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)
2524 {
2525 wxRichTextParagraph* para = wxDynamicCast(node->GetData(), wxRichTextParagraph);
2526 wxASSERT (para != NULL);
2527
2528 if (para)
2529 {
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))
2535 {
2536 wxRichTextAttr textAttr = GetAttributes();
2537 // Apply the paragraph style
2538 wxRichTextApplyStyle(textAttr, para->GetAttributes());
2539
2540 foundCount ++;
2541 if (wxTextAttrEqPartial(textAttr, style))
2542 matchingCount ++;
2543 }
2544 }
2545
2546 node = node->GetNext();
2547 }
2548 return foundCount == matchingCount && foundCount != 0;
2549 }
2550
2551 void wxRichTextParagraphLayoutBox::Clear()
2552 {
2553 DeleteChildren();
2554 }
2555
2556 void wxRichTextParagraphLayoutBox::Reset()
2557 {
2558 Clear();
2559
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
2569 AddParagraph(wxEmptyString);
2570
2571 Invalidate(wxRICHTEXT_ALL);
2572 }
2573
2574 /// Invalidate the buffer. With no argument, invalidates whole buffer.
2575 void wxRichTextParagraphLayoutBox::Invalidate(const wxRichTextRange& invalidRange)
2576 {
2577 SetDirty(true);
2578
2579 if (invalidRange == wxRICHTEXT_ALL)
2580 {
2581 m_invalidRange = wxRICHTEXT_ALL;
2582 return;
2583 }
2584
2585 // Already invalidating everything
2586 if (m_invalidRange == wxRICHTEXT_ALL)
2587 return;
2588
2589 if ((invalidRange.GetStart() < m_invalidRange.GetStart()) || m_invalidRange.GetStart() == -1)
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.
2596 wxRichTextRange wxRichTextParagraphLayoutBox::GetInvalidRange(bool wholeParagraphs) const
2597 {
2598 if (m_invalidRange == wxRICHTEXT_ALL || m_invalidRange == wxRICHTEXT_NONE)
2599 return m_invalidRange;
2600
2601 wxRichTextRange range = m_invalidRange;
2602
2603 if (wholeParagraphs)
2604 {
2605 wxRichTextParagraph* para1 = GetParagraphAtPosition(range.GetStart());
2606 if (para1)
2607 range.SetStart(para1->GetRange().GetStart());
2608 // floating layout make all child should be relayout
2609 range.SetEnd(GetRange().GetEnd());
2610 }
2611 return range;
2612 }
2613
2614 /// Apply the style sheet to the buffer, for example if the styles have changed.
2615 bool wxRichTextParagraphLayoutBox::ApplyStyleSheet(wxRichTextStyleSheet* styleSheet)
2616 {
2617 wxASSERT(styleSheet != NULL);
2618 if (!styleSheet)
2619 return false;
2620
2621 int foundCount = 0;
2622
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
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 {
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.
2662
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
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 {
2678 para->GetAttributes() = paraDef->GetStyleMergedWithBase(styleSheet);
2679 foundCount ++;
2680 }
2681 else if (listDef && !paraDef)
2682 {
2683 // Set overall style defined for the list style definition
2684 para->GetAttributes() = listDef->GetStyleMergedWithBase(styleSheet);
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
2693 para->GetAttributes() = listDef->CombineWithParagraphStyle(currentIndent, paraDef->GetStyleMergedWithBase(styleSheet));
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
2703 // Overall list definition style
2704 para->GetAttributes() = listDef->GetStyleMergedWithBase(styleSheet);
2705
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())
2712 {
2713 wxRichTextParagraphStyleDefinition* def = styleSheet->FindParagraphStyle(para->GetAttributes().GetParagraphStyleName());
2714 if (def)
2715 {
2716 para->GetAttributes() = def->GetStyleMergedWithBase(styleSheet);
2717 foundCount ++;
2718 }
2719 }
2720
2721 if (outline != -1)
2722 para->GetAttributes().SetOutlineLevel(outline);
2723 if (num != -1)
2724 para->GetAttributes().SetBulletNumber(num);
2725 }
2726
2727 node = node->GetNext();
2728 }
2729 return foundCount != 0;
2730 }
2731
2732 /// Set list style
2733 bool wxRichTextParagraphLayoutBox::SetListStyle(const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags, int startFrom, int specifiedLevel)
2734 {
2735 wxRichTextStyleSheet* styleSheet = GetStyleSheet();
2736
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);
2741
2742 // Current number, if numbering
2743 int n = startFrom;
2744
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;
2789
2790 if (def)
2791 {
2792 int thisIndent = newPara->GetAttributes().GetLeftIndent();
2793 int thisLevel = specifyLevel ? specifiedLevel : def->FindLevelForIndent(thisIndent);
2794
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
2804 wxRichTextAttr listStyle(def->GetCombinedStyleForLevel(thisLevel, styleSheet));
2805 wxRichTextApplyStyle(newPara->GetAttributes(), listStyle);
2806
2807 // Now we need to do numbering
2808 if (renumber)
2809 {
2810 newPara->GetAttributes().SetBulletNumber(n);
2811 }
2812
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);
2822 newPara->GetAttributes().SetBulletText(wxEmptyString);
2823
2824 // Eliminate the main list-related attributes
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);
2826
2827 if (styleSheet && !newPara->GetAttributes().GetParagraphStyleName().IsEmpty())
2828 {
2829 wxRichTextParagraphStyleDefinition* def = styleSheet->FindParagraphStyle(newPara->GetAttributes().GetParagraphStyleName());
2830 if (def)
2831 {
2832 newPara->GetAttributes() = def->GetStyleMergedWithBase(styleSheet);
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
2849 bool 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
2861 bool 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
2867 bool 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
2873 bool wxRichTextParagraphLayoutBox::DoNumberList(const wxRichTextRange& range, const wxRichTextRange& promotionRange, int promoteBy,
2874 wxRichTextListStyleDefinition* def, int flags, int startFrom, int specifiedLevel)
2875 {
2876 wxRichTextStyleSheet* styleSheet = GetStyleSheet();
2877
2878 bool withUndo = ((flags & wxRICHTEXT_SETSTYLE_WITH_UNDO) != 0);
2879 // bool applyMinimal = ((flags & wxRICHTEXT_SETSTYLE_OPTIMIZE) != 0);
2880 #if wxDEBUG_LEVEL
2881 bool specifyLevel = ((flags & wxRICHTEXT_SETSTYLE_SPECIFY_LEVEL) != 0);
2882 #endif
2883
2884 bool renumber = ((flags & wxRICHTEXT_SETSTYLE_RENUMBER) != 0);
2885
2886 // Max number of levels
2887 const int maxLevels = 10;
2888
2889 // The level we're looking at now
2890 int currentLevel = -1;
2891
2892 // The item number for each level
2893 int levels[maxLevels];
2894 int i;
2895
2896 // Reset all numbering
2897 for (i = 0; i < maxLevels; i++)
2898 {
2899 if (startFrom != -1)
2900 levels[i] = startFrom-1;
2901 else if (renumber) // start again
2902 levels[i] = 0;
2903 else
2904 levels[i] = -1; // start from the number we found, if any
2905 }
2906
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;
2951
2952 wxRichTextListStyleDefinition* defToUse = def;
2953 if (!defToUse)
2954 {
2955 if (styleSheet && !newPara->GetAttributes().GetListStyleName().IsEmpty())
2956 defToUse = styleSheet->FindListStyle(newPara->GetAttributes().GetListStyleName());
2957 }
2958
2959 if (defToUse)
2960 {
2961 int thisIndent = newPara->GetAttributes().GetLeftIndent();
2962 int thisLevel = defToUse->FindLevelForIndent(thisIndent);
2963
2964 // If we've specified a level to apply to all, change the level.
2965 if (specifiedLevel != -1)
2966 thisLevel = specifiedLevel;
2967
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 }
2977
2978 // Apply the overall list style, and item style for this level
2979 wxRichTextAttr listStyle(defToUse->GetCombinedStyleForLevel(thisLevel, styleSheet));
2980 wxRichTextApplyStyle(newPara->GetAttributes(), listStyle);
2981
2982 // OK, we've (re)applied the style, now let's get the numbering right.
2983
2984 if (currentLevel == -1)
2985 currentLevel = thisLevel;
2986
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 {
2996 levels[i] = 0;
2997 }
2998 currentLevel = thisLevel;
2999 }
3000 else if (thisLevel < currentLevel)
3001 {
3002 currentLevel = thisLevel;
3003 }
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 }
3013 else
3014 {
3015 levels[currentLevel] ++;
3016 }
3017
3018 newPara->GetAttributes().SetBulletNumber(levels[currentLevel]);
3019
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 }
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
3046 bool 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
3059 bool 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.
3070
3071 // For now, only renumber within the promotion range.
3072
3073 return DoNumberList(range, range, promoteBy, def, flags, 1, specifiedLevel);
3074 }
3075
3076 bool 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
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.
3090 bool wxRichTextParagraphLayoutBox::FindNextParagraphNumber(wxRichTextParagraph* previousParagraph, wxRichTextAttr& attr) const
3091 {
3092 if (!previousParagraph->GetAttributes().HasFlag(wxTEXT_ATTR_BULLET_STYLE) || previousParagraph->GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE)
3093 return false;
3094
3095 wxRichTextStyleSheet* styleSheet = GetStyleSheet();
3096 if (styleSheet && !previousParagraph->GetAttributes().GetListStyleName().IsEmpty())
3097 {
3098 wxRichTextListStyleDefinition* def = styleSheet->FindListStyle(previousParagraph->GetAttributes().GetListStyleName());
3099 if (def)
3100 {
3101 // int thisIndent = previousParagraph->GetAttributes().GetLeftIndent();
3102 // int thisLevel = def->FindLevelForIndent(thisIndent);
3103
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());
3111
3112 int nextNumber = previousParagraph->GetAttributes().GetBulletNumber() + 1;
3113 attr.SetBulletNumber(nextNumber);
3114
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 }
3133
3134 return true;
3135 }
3136 else
3137 return false;
3138 }
3139 else
3140 return false;
3141 }
3142
3143 /*!
3144 * wxRichTextParagraph
3145 * This object represents a single paragraph (or in a straight text editor, a line).
3146 */
3147
3148 IMPLEMENT_DYNAMIC_CLASS(wxRichTextParagraph, wxRichTextBox)
3149
3150 wxArrayInt wxRichTextParagraph::sm_defaultTabs;
3151
3152 wxRichTextParagraph::wxRichTextParagraph(wxRichTextObject* parent, wxRichTextAttr* style):
3153 wxRichTextBox(parent)
3154 {
3155 if (style)
3156 SetAttributes(*style);
3157 }
3158
3159 wxRichTextParagraph::wxRichTextParagraph(const wxString& text, wxRichTextObject* parent, wxRichTextAttr* paraStyle, wxRichTextAttr* charStyle):
3160 wxRichTextBox(parent)
3161 {
3162 if (paraStyle)
3163 SetAttributes(*paraStyle);
3164
3165 AppendChild(new wxRichTextPlainText(text, this, charStyle));
3166 }
3167
3168 wxRichTextParagraph::~wxRichTextParagraph()
3169 {
3170 ClearLines();
3171 }
3172
3173 /// Draw the item
3174 bool wxRichTextParagraph::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextRange& selectionRange, const wxRect& rect, int WXUNUSED(descent), int style)
3175 {
3176 wxRichTextAttr attr = GetCombinedAttributes();
3177
3178 // Draw the bullet, if any
3179 if (attr.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE)
3180 {
3181 if (attr.GetLeftSubIndent() != 0)
3182 {
3183 int spaceBeforePara = ConvertTenthsMMToPixels(dc, attr.GetParagraphSpacingBefore());
3184 int leftIndent = ConvertTenthsMMToPixels(dc, attr.GetLeftIndent());
3185
3186 wxRichTextAttr bulletAttr(GetCombinedAttributes());
3187
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();
3192 if (!firstObj->IsFloatable() && firstObj->GetAttributes().HasFont())
3193 {
3194 wxRichTextApplyStyle(bulletAttr, firstObj->GetAttributes());
3195 }
3196 }
3197
3198 // Get line height from first line, if any
3199 wxRichTextLine* line = m_cachedLines.GetFirst() ? (wxRichTextLine* ) m_cachedLines.GetFirst()->GetData() : NULL;
3200
3201 wxPoint linePos;
3202 int lineHeight wxDUMMY_INITIALIZE(0);
3203 if (line)
3204 {
3205 lineHeight = line->GetSize().y;
3206 linePos = line->GetPosition() + GetPosition();
3207 }
3208 else
3209 {
3210 wxFont font;
3211 if (bulletAttr.HasFont() && GetBuffer())
3212 font = GetBuffer()->GetFontTable().FindFont(bulletAttr);
3213 else
3214 font = (*wxNORMAL_FONT);
3215
3216 wxCheckSetFont(dc, font);
3217
3218 lineHeight = dc.GetCharHeight();
3219 linePos = GetPosition();
3220 linePos.y += spaceBeforePara;
3221 }
3222
3223 wxRect bulletRect(GetPosition().x + leftIndent, linePos.y, linePos.x - (GetPosition().x + leftIndent), lineHeight);
3224
3225 if (attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP)
3226 {
3227 if (wxRichTextBuffer::GetRenderer())
3228 wxRichTextBuffer::GetRenderer()->DrawBitmapBullet(this, dc, bulletAttr, bulletRect);
3229 }
3230 else if (attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_STANDARD)
3231 {
3232 if (wxRichTextBuffer::GetRenderer())
3233 wxRichTextBuffer::GetRenderer()->DrawStandardBullet(this, dc, bulletAttr, bulletRect);
3234 }
3235 else
3236 {
3237 wxString bulletText = GetBulletText();
3238
3239 if (!bulletText.empty() && wxRichTextBuffer::GetRenderer())
3240 wxRichTextBuffer::GetRenderer()->DrawTextBullet(this, dc, bulletAttr, bulletRect, bulletText);
3241 }
3242 }
3243 }
3244
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();
3251 wxRichTextRange lineRange = line->GetAbsoluteRange();
3252
3253 // Lines are specified relative to the paragraph
3254
3255 wxPoint linePosition = line->GetPosition() + GetPosition();
3256
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))
3259 {
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();
3265
3266 int i = 0;
3267 while (node2)
3268 {
3269 wxRichTextObject* child = node2->GetData();
3270
3271 if (!child->IsFloating() && child->GetRange().GetLength() > 0 && !child->GetRange().IsOutside(lineRange) && !lineRange.IsOutside(range))
3272 {
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
3284 #endif
3285 {
3286 int descent = 0;
3287 child->GetRangeSize(objectRange, objectSize, descent, dc, wxRICHTEXT_UNFORMATTED, objectPosition);
3288 }
3289
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);
3293
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;
3300
3301 node2 = node2->GetNext();
3302 }
3303 }
3304
3305 node = node->GetNext();
3306 }
3307
3308 return true;
3309 }
3310
3311 // Get the range width using partial extents calculated for the whole paragraph.
3312 static int wxRichTextGetRangeWidth(const wxRichTextParagraph& para, const wxRichTextRange& range, const wxArrayInt& partialExtents)
3313 {
3314 wxASSERT(partialExtents.GetCount() >= (size_t) range.GetLength());
3315
3316 if (partialExtents.GetCount() < (size_t) range.GetLength())
3317 return 0;
3318
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
3330 /// Lay the item out
3331 bool wxRichTextParagraph::Layout(wxDC& dc, const wxRect& rect, int style)
3332 {
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
3340 wxRichTextAttr attr = GetCombinedAttributes();
3341
3342 // ClearLines();
3343
3344 // Increase the size of the paragraph due to spacing
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());
3350
3351 int lineSpacing = 0;
3352
3353 // Let's assume line spacing of 10 is normal, 15 is 1.5, 20 is 2, etc.
3354 if (attr.HasLineSpacing() && attr.GetLineSpacing() > 0 && attr.GetFont().Ok())
3355 {
3356 wxCheckSetFont(dc, attr.GetFont());
3357 lineSpacing = (int) (double(dc.GetCharHeight()) * (double(attr.GetLineSpacing())/10.0 - 1.0));
3358 }
3359
3360 // Start position for each line relative to the paragraph
3361 int startPositionFirstLine = leftIndent;
3362 int startPositionSubsequentLines = leftIndent + leftSubIndent;
3363 wxRect availableRect;
3364
3365 // If we have a bullet in this paragraph, the start position for the first line's text
3366 // is actually leftIndent + leftSubIndent.
3367 if (attr.GetBulletStyle() != wxTEXT_ATTR_BULLET_STYLE_NONE)
3368 startPositionFirstLine = startPositionSubsequentLines;
3369
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;
3379 int maxAscent = 0;
3380 int maxDescent = 0;
3381 int lineCount = 0;
3382 int lineAscent = 0;
3383 int lineDescent = 0;
3384
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();
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
3408 #endif
3409
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
3416 node = m_children.GetFirst();
3417 while (node)
3418 {
3419 wxRichTextObject* child = node->GetData();
3420
3421 // If floating, ignore. We already laid out floats.
3422 if (child->IsFloating() || child->GetRange().GetLength() == 0)
3423 {
3424 node = node->GetNext();
3425 continue;
3426 }
3427
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
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.
3438
3439 long nextBreakPos = GetFirstLineBreakPosition(lastEndPos+1);
3440 long lastPosToUse = child->GetRange().GetEnd();
3441 bool lineBreakInThisObject = (nextBreakPos > -1 && nextBreakPos <= child->GetRange().GetEnd());
3442
3443 if (lineBreakInThisObject)
3444 lastPosToUse = nextBreakPos;
3445
3446 wxSize childSize;
3447 int childDescent = 0;
3448
3449 if ((nextBreakPos == -1) && (lastEndPos == child->GetRange().GetStart() - 1)) // i.e. we want to get the whole thing
3450 {
3451 childSize = child->GetCachedSize();
3452 childDescent = child->GetDescent();
3453 }
3454 else
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
3461 GetRangeSize(wxRichTextRange(lastEndPos+1, lastPosToUse), childSize, childDescent, dc, wxRICHTEXT_UNFORMATTED, rect.GetPosition());
3462 #endif
3463 }
3464
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
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)
3481
3482 if ((lineBreakInThisObject && (childSize.x + currentWidth <= availableRect.width)) ||
3483 (childSize.x + currentWidth > availableRect.width))
3484 {
3485 long wrapPosition = 0;
3486
3487 int indent = lineCount == 0 ? startPositionFirstLine : startPositionSubsequentLines;
3488 indent += rightIndent;
3489 // Find a place to wrap. This may walk back to previous children,
3490 // for example if a word spans several objects.
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))
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);
3505
3506 // Let's find the actual size of the current line now
3507 wxSize actualSize;
3508 wxRichTextRange actualRange(lastCompletedEndPos+1, wrapPosition);
3509
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
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
3519 GetRangeSize(actualRange, actualSize, childDescent, dc, wxRICHTEXT_UNFORMATTED);
3520 #endif
3521
3522 currentWidth = actualSize.x;
3523 maxDescent = wxMax(childDescent, maxDescent);
3524 maxAscent = wxMax(actualSize.y-childDescent, maxAscent);
3525 lineHeight = maxDescent + maxAscent;
3526
3527 // Add a new line
3528 wxRichTextLine* line = AllocateLine(lineCount);
3529
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()));
3532 line->SetPosition(currentPosition);
3533 line->SetSize(wxSize(currentWidth, lineHeight));
3534 line->SetDescent(maxDescent);
3535
3536 // Now move down a line. TODO: add margins, spacing
3537 currentPosition.y += lineHeight;
3538 currentPosition.y += lineSpacing;
3539 currentWidth = 0;
3540 maxDescent = 0;
3541 maxAscent = 0;
3542 maxWidth = wxMax(maxWidth, currentWidth);
3543
3544 lineCount ++;
3545
3546 // TODO: account for zero-length objects, such as fields
3547 wxASSERT(wrapPosition > lastCompletedEndPos);
3548
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;
3565 maxDescent = wxMax(childDescent, maxDescent);
3566 maxAscent = wxMax(childSize.y-childDescent, maxAscent);
3567 lineHeight = maxDescent + maxAscent;
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 {
3580 currentPosition.x = (lineCount == 0 ? availableRect.x + startPositionFirstLine : availableRect.x + startPositionSubsequentLines);
3581
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()));
3588
3589 line->SetPosition(currentPosition);
3590
3591 if (lineHeight == 0 && GetBuffer())
3592 {
3593 wxFont font(GetBuffer()->GetFontTable().FindFont(attr));
3594 wxCheckSetFont(dc, font);
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 ++;
3608 }
3609
3610 // Remove remaining unused line objects, if any
3611 ClearUnusedLines(lineCount);
3612
3613 // Apply styles to wrapped lines
3614 ApplyParagraphStyle(attr, rect, dc);
3615
3616 SetCachedSize(wxSize(maxWidth, currentPosition.y + spaceAfterPara));
3617
3618 m_dirty = false;
3619
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
3636 if (child->GetRange().GetLength() > 0 && !child->GetRange().IsOutside(lineRange))
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
3662 return true;
3663 }
3664
3665 /// Apply paragraph styles, such as centering, to wrapped lines
3666 void wxRichTextParagraph::ApplyParagraphStyle(const wxRichTextAttr& attr, const wxRect& rect, wxDC& dc)
3667 {
3668 if (!attr.HasAlignment())
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
3680 if (attr.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_CENTRE)
3681 {
3682 int rightIndent = ConvertTenthsMMToPixels(dc, attr.GetRightIndent());
3683 pos.x = (rect.GetWidth() - pos.x - rightIndent - size.x)/2 + pos.x;
3684 line->SetPosition(pos);
3685 }
3686 else if (attr.HasAlignment() && GetAttributes().GetAlignment() == wxTEXT_ALIGNMENT_RIGHT)
3687 {
3688 int rightIndent = ConvertTenthsMMToPixels(dc, attr.GetRightIndent());
3689 pos.x = rect.GetWidth() - size.x - rightIndent;
3690 line->SetPosition(pos);
3691 }
3692
3693 node = node->GetNext();
3694 }
3695 }
3696
3697 /// Insert text at the given position
3698 bool wxRichTextParagraph::InsertText(long pos, const wxString& text)
3699 {
3700 wxRichTextObject* childToUse = NULL;
3701 wxRichTextObjectList::compatibility_iterator nodeToUse = wxRichTextObjectList::compatibility_iterator();
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
3728 int textLength = text.length();
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));
3742
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
3767 void wxRichTextParagraph::Copy(const wxRichTextParagraph& obj)
3768 {
3769 wxRichTextBox::Copy(obj);
3770 }
3771
3772 /// Clear the cached lines
3773 void 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.
3780 bool wxRichTextParagraph::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, int flags, wxPoint position, wxArrayInt* partialExtents) const
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
3792 wxArrayInt childExtents;
3793 wxArrayInt* p;
3794 if (partialExtents)
3795 p = & childExtents;
3796 else
3797 p = NULL;
3798
3799 wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
3800 while (node)
3801 {
3802
3803 wxRichTextObject* child = node->GetData();
3804 if (!child->GetRange().IsOutside(range))
3805 {
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 {
3822 wxSize childSize;
3823
3824 wxRichTextRange rangeToUse = range;
3825 rangeToUse.LimitTo(child->GetRange());
3826 int childDescent = 0;
3827
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))
3840 {
3841 sz.y = wxMax(sz.y, childSize.y);
3842 sz.x += childSize.x;
3843 descent = wxMax(descent, childDescent);
3844
3845 if ((flags & wxRICHTEXT_CACHE_SIZE) && (rangeToUse == child->GetRange()))
3846 {
3847 child->SetCachedSize(childSize);
3848 child->SetDescent(childDescent);
3849 }
3850
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 }
3865 }
3866 }
3867
3868 if (p)
3869 p->Clear();
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();
3892 wxRichTextRange lineRange = line->GetAbsoluteRange();
3893 if (!lineRange.IsOutside(range))
3894 {
3895 wxSize lineSize;
3896
3897 wxRichTextObjectList::compatibility_iterator node2 = m_children.GetFirst();
3898 while (node2)
3899 {
3900 wxRichTextObject* child = node2->GetData();
3901
3902 if (!child->IsFloating() && !child->GetRange().IsOutside(lineRange))
3903 {
3904 wxRichTextRange rangeToUse = lineRange;
3905 rangeToUse.LimitTo(child->GetRange());
3906
3907 wxSize childSize;
3908 int childDescent = 0;
3909 if (child->GetRangeSize(rangeToUse, childSize, childDescent, dc, flags, wxPoint(position.x + sz.x, position.y)))
3910 {
3911 lineSize.y = wxMax(lineSize.y, childSize.y);
3912 lineSize.x += childSize.x;
3913 }
3914 descent = wxMax(descent, childDescent);
3915 }
3916
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
3932 bool 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
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();
3981 wxRichTextRange lineRange = line->GetAbsoluteRange();
3982 if (index >= lineRange.GetStart() && index <= lineRange.GetEnd())
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.
3987 if (index == lineRange.GetEnd() && forceLineStart)
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
4000 wxRichTextRange r(lineRange.GetStart(), index);
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
4008 if (GetRangeSize(r, rangeSize, descent, dc, wxRICHTEXT_UNFORMATTED, line->GetPosition()+ GetPosition()))
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
4026 int 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();
4036 wxRichTextRange lineRange = line->GetAbsoluteRange();
4037
4038 if (pt.y <= linePos.y + lineSize.y)
4039 {
4040 if (pt.x < linePos.x)
4041 {
4042 textPosition = lineRange.GetStart();
4043 return wxRICHTEXT_HITTEST_BEFORE|wxRICHTEXT_HITTEST_OUTSIDE;
4044 }
4045 else if (pt.x >= (linePos.x + lineSize.x))
4046 {
4047 textPosition = lineRange.GetEnd();
4048 return wxRICHTEXT_HITTEST_AFTER|wxRICHTEXT_HITTEST_OUTSIDE;
4049 }
4050 else
4051 {
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
4075 int midPoint = (nextX + lastX)/2;
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
4085 long i;
4086 int lastX = linePos.x;
4087 for (i = lineRange.GetStart(); i <= lineRange.GetEnd(); i++)
4088 {
4089 wxSize childSize;
4090 int descent = 0;
4091
4092 wxRichTextRange rangeToUse(lineRange.GetStart(), i);
4093
4094 GetRangeSize(rangeToUse, childSize, descent, dc, wxRICHTEXT_UNFORMATTED, linePos);
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
4106 int midPoint = (nextX + lastX)/2;
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 }
4117 #endif
4118 }
4119 }
4120
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.
4129 wxRichTextObject* 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)
4139 {
4140 if (node->GetPrevious())
4141 *previousObject = node->GetPrevious()->GetData();
4142 else
4143 *previousObject = NULL;
4144 }
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
4185 void 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
4202 void wxRichTextParagraph::MoveFromList(wxList& list)
4203 {
4204 for (wxList::compatibility_iterator node = list.GetFirst(); node; node = node->GetNext())
4205 {
4206 AppendChild((wxRichTextObject*) node->GetData());
4207 }
4208 }
4209
4210 /// Calculate range
4211 void 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
4222 wxRichTextObject* 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;
4230
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.
4238 bool 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
4256 {
4257 text += wxT(" ");
4258 }
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
4278 {
4279 text = wxT(" ") + text;
4280 }
4281 }
4282
4283 node = node->GetPrevious();
4284 }
4285 }
4286
4287 return true;
4288 }
4289
4290 /// Find a suitable wrap position.
4291 bool wxRichTextParagraph::FindWrapPosition(const wxRichTextRange& range, wxDC& dc, int availableSpace, long& wrapPosition, wxArrayInt* partialExtents)
4292 {
4293 if (range.GetLength() <= 0)
4294 return false;
4295
4296 // Find the first position where the line exceeds the available space.
4297 wxSize sz;
4298 long breakPosition = range.GetEnd();
4299
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
4302 {
4303 int widthBefore;
4304
4305 if (range.GetStart() > GetRange().GetStart())
4306 widthBefore = (*partialExtents)[range.GetStart() - GetRange().GetStart() - 1];
4307 else
4308 widthBefore = 0;
4309
4310 size_t i;
4311 for (i = (size_t) range.GetStart(); i <= (size_t) range.GetEnd(); i++)
4312 {
4313 int widthFromStartOfThisRange = (*partialExtents)[i - GetRange().GetStart()] - widthBefore;
4314
4315 if (widthFromStartOfThisRange > availableSpace)
4316 {
4317 breakPosition = i-1;
4318 break;
4319 }
4320 }
4321 }
4322 else
4323 #endif
4324 {
4325 // Binary chop for speed
4326 long minPos = range.GetStart();
4327 long maxPos = range.GetEnd();
4328 while (true)
4329 {
4330 if (minPos == maxPos)
4331 {
4332 int descent = 0;
4333 GetRangeSize(wxRichTextRange(range.GetStart(), minPos), sz, descent, dc, wxRICHTEXT_UNFORMATTED);
4334
4335 if (sz.x > availableSpace)
4336 breakPosition = minPos - 1;
4337 break;
4338 }
4339 else if ((maxPos - minPos) == 1)
4340 {
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;
4353 }
4354 else
4355 {
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 }
4369 }
4370 }
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 {
4379 int newLinePos = plainText.Find(wxRichTextLineBreakChar);
4380 if (newLinePos != wxNOT_FOUND)
4381 {
4382 breakPosition = wxMax(0, range.GetStart() + newLinePos);
4383 }
4384 else
4385 {
4386 int spacePos = plainText.Find(wxT(' '), true);
4387 int tabPos = plainText.Find(wxT('\t'), true);
4388 int pos = wxMax(spacePos, tabPos);
4389 if (pos != wxNOT_FOUND)
4390 {
4391 int positionsFromEndOfString = plainText.length() - pos - 1;
4392 breakPosition = breakPosition - positionsFromEndOfString;
4393 }
4394 }
4395 }
4396
4397 wrapPosition = breakPosition;
4398
4399 return true;
4400 }
4401
4402 /// Get the bullet text for this paragraph.
4403 wxString 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;
4412 if ((GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ARABIC) || (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE))
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 {
4428 text = wxRichTextDecimalToRoman(number);
4429 }
4430 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER)
4431 {
4432 text = wxRichTextDecimalToRoman(number);
4433 text.MakeLower();
4434 }
4435 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL)
4436 {
4437 text = GetAttributes().GetBulletText();
4438 }
4439
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();
4448 }
4449
4450 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PARENTHESES)
4451 {
4452 text = wxT("(") + text + wxT(")");
4453 }
4454 else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS)
4455 {
4456 text = text + wxT(")");
4457 }
4458
4459 if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PERIOD)
4460 {
4461 text += wxT(".");
4462 }
4463
4464 return text;
4465 }
4466
4467 /// Allocate or reuse a line object
4468 wxRichTextLine* 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
4485 bool 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
4501 /// Get combined attributes of the base style, paragraph style and character style. We use this to dynamically
4502 /// retrieve the actual style.
4503 wxRichTextAttr wxRichTextParagraph::GetCombinedAttributes(const wxRichTextAttr& contentStyle) const
4504 {
4505 wxRichTextAttr attr;
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.
4520 wxRichTextAttr wxRichTextParagraph::GetCombinedAttributes() const
4521 {
4522 wxRichTextAttr attr;
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 }
4534
4535 /// Create default tabstop array
4536 void 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
4546 void wxRichTextParagraph::ClearDefaultTabs()
4547 {
4548 sm_defaultTabs.Clear();
4549 }
4550
4551 void 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);
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);
4574
4575 /* Update the offset */
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);
4586
4587 if (anchored->GetAttributes().GetTextBoxAttr().GetFloatMode() == wxTEXT_BOX_ATTR_FLOAT_LEFT)
4588 x = 0;
4589 else if (anchored->GetAttributes().GetTextBoxAttr().GetFloatMode() == wxTEXT_BOX_ATTR_FLOAT_RIGHT)
4590 x = rect.width - size.x;
4591
4592 anchored->SetPosition(wxPoint(x, pos));
4593 anchored->SetCachedSize(size);
4594 floatCollector->CollectFloat(this, anchored);
4595 }
4596
4597 node = node->GetNext();
4598 }
4599 }
4600
4601 /// Get the first position from pos that has a line break character.
4602 long 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 }
4622
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
4630 wxRichTextLine::wxRichTextLine(wxRichTextParagraph* parent)
4631 {
4632 Init(parent);
4633 }
4634
4635 /// Initialisation
4636 void wxRichTextLine::Init(wxRichTextParagraph* parent)
4637 {
4638 m_parent = parent;
4639 m_range.SetRange(-1, -1);
4640 m_pos = wxPoint(0, 0);
4641 m_size = wxSize(0, 0);
4642 m_descent = 0;
4643 #if wxRICHTEXT_USE_OPTIMIZED_LINE_DRAWING
4644 m_objectSizes.Clear();
4645 #endif
4646 }
4647
4648 /// Copy
4649 void wxRichTextLine::Copy(const wxRichTextLine& obj)
4650 {
4651 m_range = obj.m_range;
4652 #if wxRICHTEXT_USE_OPTIMIZED_LINE_DRAWING
4653 m_objectSizes = obj.m_objectSizes;
4654 #endif
4655 }
4656
4657 /// Get the absolute object position
4658 wxPoint wxRichTextLine::GetAbsolutePosition() const
4659 {
4660 return m_parent->GetPosition() + m_pos;
4661 }
4662
4663 /// Get the absolute range
4664 wxRichTextRange 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
4671 /*!
4672 * wxRichTextPlainText
4673 * This object represents a single piece of text.
4674 */
4675
4676 IMPLEMENT_DYNAMIC_CLASS(wxRichTextPlainText, wxRichTextObject)
4677
4678 wxRichTextPlainText::wxRichTextPlainText(const wxString& text, wxRichTextObject* parent, wxRichTextAttr* style):
4679 wxRichTextObject(parent)
4680 {
4681 if (style)
4682 SetAttributes(*style);
4683
4684 m_text = text;
4685 }
4686
4687 #define USE_KERNING_FIX 1
4688
4689 // If insufficient tabs are defined, this is the tab width used
4690 #define WIDTH_FOR_DEFAULT_TABS 50
4691
4692 /// Draw the item
4693 bool wxRichTextPlainText::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextRange& selectionRange, const wxRect& rect, int descent, int WXUNUSED(style))
4694 {
4695 wxRichTextParagraph* para = wxDynamicCast(GetParent(), wxRichTextParagraph);
4696 wxASSERT (para != NULL);
4697
4698 wxRichTextAttr textAttr(para ? para->GetCombinedAttributes(GetAttributes()) : GetAttributes());
4699
4700 int offset = GetRange().GetStart();
4701
4702 // Replace line break characters with spaces
4703 wxString str = m_text;
4704 wxString toRemove = wxRichTextLineBreakChar;
4705 str.Replace(toRemove, wxT(" "));
4706 if (textAttr.HasTextEffects() && (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS))
4707 str.MakeUpper();
4708
4709 long len = range.GetLength();
4710 wxString stringChunk = str.Mid(range.GetStart() - offset, (size_t) len);
4711
4712 // Test for the optimized situations where all is selected, or none
4713 // is selected.
4714
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 }
4750
4751 // (a) All selected.
4752 if (selectionRange.GetStart() <= range.GetStart() && selectionRange.GetEnd() >= range.GetEnd())
4753 {
4754 DrawTabbedString(dc, textAttr, rect, stringChunk, x, y, true);
4755 }
4756 // (b) None selected.
4757 else if (selectionRange.GetEnd() < range.GetStart() || selectionRange.GetStart() > range.GetEnd())
4758 {
4759 // Draw all unselected
4760 DrawTabbedString(dc, textAttr, rect, stringChunk, x, y, false);
4761 }
4762 else
4763 {
4764 // (c) Part selected, part not
4765 // Let's draw unselected chunk, selected chunk, then unselected chunk.
4766
4767 dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT);
4768
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)
4776 {
4777 wxLogDebug(wxT("Mid(%d, %d"), (int)(r1 - offset), (int)fragmentLen);
4778 }
4779 wxString stringFragment = str.Mid(r1 - offset, fragmentLen);
4780
4781 DrawTabbedString(dc, textAttr, rect, stringFragment, x, y, false);
4782
4783 #if USE_KERNING_FIX
4784 if (stringChunk.Find(wxT("\t")) == wxNOT_FOUND)
4785 {
4786 // Compensate for kerning difference
4787 wxString stringFragment2(str.Mid(r1 - offset, fragmentLen+1));
4788 wxString stringFragment3(str.Mid(r1 - offset + fragmentLen, 1));
4789
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);
4794
4795 int kerningDiff = (w1 + w3) - w2;
4796 x = x - kerningDiff;
4797 }
4798 #endif
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)
4809 {
4810 wxLogDebug(wxT("Mid(%d, %d"), (int)(s1 - offset), (int)fragmentLen);
4811 }
4812 wxString stringFragment = str.Mid(s1 - offset, fragmentLen);
4813
4814 DrawTabbedString(dc, textAttr, rect, stringFragment, x, y, true);
4815
4816 #if USE_KERNING_FIX
4817 if (stringChunk.Find(wxT("\t")) == wxNOT_FOUND)
4818 {
4819 // Compensate for kerning difference
4820 wxString stringFragment2(str.Mid(s1 - offset, fragmentLen+1));
4821 wxString stringFragment3(str.Mid(s1 - offset + fragmentLen, 1));
4822
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);
4827
4828 int kerningDiff = (w1 + w3) - w2;
4829 x = x - kerningDiff;
4830 }
4831 #endif
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)
4842 {
4843 wxLogDebug(wxT("Mid(%d, %d"), (int)(s2 - offset), (int)fragmentLen);
4844 }
4845 wxString stringFragment = str.Mid(s2 - offset, fragmentLen);
4846
4847 DrawTabbedString(dc, textAttr, rect, stringFragment, x, y, false);
4848 }
4849 }
4850
4851 return true;
4852 }
4853
4854 bool wxRichTextPlainText::DrawTabbedString(wxDC& dc, const wxRichTextAttr& attr, const wxRect& rect,wxString& str, wxCoord& x, wxCoord& y, bool selected)
4855 {
4856 bool hasTabs = (str.Find(wxT('\t')) != wxNOT_FOUND);
4857
4858 wxArrayInt tabArray;
4859 int tabCount;
4860 if (hasTabs)
4861 {
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)
4869 {
4870 int pos = tabArray[i];
4871 pos = ConvertTenthsMMToPixels(dc, pos);
4872 tabArray[i] = pos;
4873 }
4874 }
4875 else
4876 tabCount = 0;
4877
4878 int nextTabPos = -1;
4879 int tabPos = -1;
4880 wxCoord w, h;
4881
4882 if (selected)
4883 {
4884 wxColour highlightColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT));
4885 wxColour highlightTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT));
4886
4887 wxCheckSetBrush(dc, wxBrush(highlightColour));
4888 wxCheckSetPen(dc, wxPen(highlightColour));
4889 dc.SetTextForeground(highlightTextColour);
4890 dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT);
4891 }
4892 else
4893 {
4894 dc.SetTextForeground(attr.GetTextColour());
4895
4896 if (attr.HasFlag(wxTEXT_ATTR_BACKGROUND_COLOUR) && attr.GetBackgroundColour().IsOk())
4897 {
4898 dc.SetBackgroundMode(wxBRUSHSTYLE_SOLID);
4899 dc.SetTextBackground(attr.GetBackgroundColour());
4900 }
4901 else
4902 dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT);
4903 }
4904
4905 wxCoord x_orig = x;
4906 while (hasTabs)
4907 {
4908 // the string has a tab
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);
4913 tabPos = x + w;
4914 bool not_found = true;
4915 for (int i = 0; i < tabCount && not_found; ++i)
4916 {
4917 nextTabPos = tabArray.Item(i) + x_orig;
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)))
4923 {
4924 if (nextTabPos <= tabPos)
4925 {
4926 int defaultTabWidth = ConvertTenthsMMToPixels(dc, WIDTH_FOR_DEFAULT_TABS);
4927 nextTabPos = tabPos + defaultTabWidth;
4928 }
4929
4930 not_found = false;
4931 if (selected)
4932 {
4933 w = nextTabPos - x;
4934 wxRect selRect(x, rect.y, w, rect.GetHeight());
4935 dc.DrawRectangle(selRect);
4936 }
4937 dc.DrawText(stringChunk, x, y);
4938
4939 if (attr.HasTextEffects() && (attr.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH))
4940 {
4941 wxPen oldPen = dc.GetPen();
4942 wxCheckSetPen(dc, wxPen(attr.GetTextColour(), 1));
4943 dc.DrawLine(x, (int) (y+(h/2)+0.5), x+w, (int) (y+(h/2)+0.5));
4944 wxCheckSetPen(dc, oldPen);
4945 }
4946
4947 x = nextTabPos;
4948 }
4949 }
4950 hasTabs = (str.Find(wxT('\t')) != wxNOT_FOUND);
4951 }
4952
4953 if (!str.IsEmpty())
4954 {
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);
4962
4963 if (attr.HasTextEffects() && (attr.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH))
4964 {
4965 wxPen oldPen = dc.GetPen();
4966 wxCheckSetPen(dc, wxPen(attr.GetTextColour(), 1));
4967 dc.DrawLine(x, (int) (y+(h/2)+0.5), x+w, (int) (y+(h/2)+0.5));
4968 wxCheckSetPen(dc, oldPen);
4969 }
4970
4971 x += w;
4972 }
4973 return true;
4974
4975 }
4976
4977 /// Lay the item out
4978 bool wxRichTextPlainText::Layout(wxDC& dc, const wxRect& WXUNUSED(rect), int WXUNUSED(style))
4979 {
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));
4983
4984 return true;
4985 }
4986
4987 /// Copy
4988 void 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.
4997 bool wxRichTextPlainText::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, int WXUNUSED(flags), wxPoint position, wxArrayInt* partialExtents) const
4998 {
4999 if (!range.IsWithin(GetRange()))
5000 return false;
5001
5002 wxRichTextParagraph* para = wxDynamicCast(GetParent(), wxRichTextParagraph);
5003 wxASSERT (para != NULL);
5004
5005 wxRichTextAttr textAttr(para ? para->GetCombinedAttributes(GetAttributes()) : GetAttributes());
5006
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
5011 bool bScript(false);
5012 wxFont font(GetBuffer()->GetFontTable().FindFont(textAttr));
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 }
5029
5030 bool haveDescent = false;
5031 int startPos = range.GetStart() - GetRange().GetStart();
5032 long len = range.GetLength();
5033
5034 wxString str(m_text);
5035 wxString toReplace = wxRichTextLineBreakChar;
5036 str.Replace(toReplace, wxT(" "));
5037
5038 wxString stringChunk = str.Mid(startPos, (size_t) len);
5039
5040 if (textAttr.HasTextEffects() && (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_CAPITALS))
5041 stringChunk.MakeUpper();
5042
5043 wxCoord w, h;
5044 int width = 0;
5045 if (stringChunk.Find(wxT('\t')) != wxNOT_FOUND)
5046 {
5047 // the string has a tab
5048 wxArrayInt tabArray;
5049 if (textAttr.GetTabs().IsEmpty())
5050 tabArray = wxRichTextParagraph::GetDefaultTabs();
5051 else
5052 tabArray = textAttr.GetTabs();
5053
5054 int tabCount = tabArray.GetCount();
5055
5056 for (int i = 0; i < tabCount; ++i)
5057 {
5058 int pos = tabArray[i];
5059 pos = ((wxRichTextPlainText*) this)->ConvertTenthsMMToPixels(dc, pos);
5060 tabArray[i] = pos;
5061 }
5062
5063 int nextTabPos = -1;
5064
5065 while (stringChunk.Find(wxT('\t')) >= 0)
5066 {
5067 int absoluteWidth = 0;
5068
5069 // the string has a tab
5070 // break up the string at the Tab
5071 wxString stringFragment = stringChunk.BeforeFirst(wxT('\t'));
5072 stringChunk = stringChunk.AfterFirst(wxT('\t'));
5073
5074 if (partialExtents)
5075 {
5076 int oldWidth;
5077 if (partialExtents->GetCount() > 0)
5078 oldWidth = (*partialExtents)[partialExtents->GetCount()-1];
5079 else
5080 oldWidth = 0;
5081
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]);
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;
5100 }
5101
5102 bool notFound = true;
5103 for (int i = 0; i < tabCount && notFound; ++i)
5104 {
5105 nextTabPos = tabArray.Item(i);
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)))
5111 {
5112 if (nextTabPos <= absoluteWidth)
5113 {
5114 int defaultTabWidth = ((wxRichTextPlainText*) this)->ConvertTenthsMMToPixels(dc, WIDTH_FOR_DEFAULT_TABS);
5115 nextTabPos = absoluteWidth + defaultTabWidth;
5116 }
5117
5118 notFound = false;
5119 width = nextTabPos - position.x;
5120
5121 if (partialExtents)
5122 partialExtents->Add(width);
5123 }
5124 }
5125 }
5126 }
5127
5128 if (!stringChunk.IsEmpty())
5129 {
5130 if (partialExtents)
5131 {
5132 int oldWidth;
5133 if (partialExtents->GetCount() > 0)
5134 oldWidth = (*partialExtents)[partialExtents->GetCount()-1];
5135 else
5136 oldWidth = 0;
5137
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 }
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());
5165 }
5166
5167 if (!haveDescent)
5168 dc.GetTextExtent(wxT("X"), & w, & h, & descent);
5169
5170 if ( bScript )
5171 dc.SetFont(font);
5172
5173 return true;
5174 }
5175
5176 /// Do a split, returning an object containing the second part, and setting
5177 /// the first part in 'this'.
5178 wxRichTextObject* wxRichTextPlainText::DoSplit(long pos)
5179 {
5180 long index = pos - GetRange().GetStart();
5181
5182 if (index < 0 || index >= (int) m_text.length())
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);
5195
5196 return newObject;
5197 }
5198
5199 /// Calculate range
5200 void wxRichTextPlainText::CalculateRange(long start, long& end)
5201 {
5202 end = start + m_text.length() - 1;
5203 m_range.SetRange(start, end);
5204 }
5205
5206 /// Delete range
5207 bool 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.
5227 wxString 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.
5240 bool wxRichTextPlainText::CanMerge(wxRichTextObject* object) const
5241 {
5242 return object->GetClassInfo() == CLASSINFO(wxRichTextPlainText) &&
5243 (m_text.empty() || wxTextAttrEq(GetAttributes(), object->GetAttributes()));
5244 }
5245
5246 /// Returns true if this object merged itself with the given one.
5247 /// The calling code will then delete the given object.
5248 bool 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();
5256 wxRichTextApplyStyle(m_attributes, textObject->GetAttributes());
5257 return true;
5258 }
5259 else
5260 return false;
5261 }
5262
5263 /// Dump to output stream for debugging
5264 void wxRichTextPlainText::Dump(wxTextOutputStream& stream)
5265 {
5266 wxRichTextObject::Dump(stream);
5267 stream << m_text << wxT("\n");
5268 }
5269
5270 /// Get the first position from pos that has a line break character.
5271 long 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
5287 /*!
5288 * wxRichTextBuffer
5289 * This is a kind of box, used to represent the whole buffer
5290 */
5291
5292 IMPLEMENT_DYNAMIC_CLASS(wxRichTextBuffer, wxRichTextParagraphLayoutBox)
5293
5294 wxList wxRichTextBuffer::sm_handlers;
5295 wxRichTextRenderer* wxRichTextBuffer::sm_renderer = NULL;
5296 int wxRichTextBuffer::sm_bulletRightMargin = 20;
5297 float wxRichTextBuffer::sm_bulletProportion = (float) 0.3;
5298
5299 /// Initialisation
5300 void 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;
5308 m_handlerFlags = 0;
5309 m_scale = 1.0;
5310 }
5311
5312 /// Initialisation
5313 wxRichTextBuffer::~wxRichTextBuffer()
5314 {
5315 delete m_commandProcessor;
5316 delete m_batchedCommand;
5317
5318 ClearStyleStack();
5319 ClearEventHandlers();
5320 }
5321
5322 void wxRichTextBuffer::ResetAndClearCommands()
5323 {
5324 Reset();
5325
5326 GetCommandProcessor()->ClearCommands();
5327
5328 Modify(false);
5329 Invalidate(wxRICHTEXT_ALL);
5330 }
5331
5332 void 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
5343 /// Push style sheet to top of stack
5344 bool wxRichTextBuffer::PushStyleSheet(wxRichTextStyleSheet* styleSheet)
5345 {
5346 if (m_styleSheet)
5347 styleSheet->InsertSheet(m_styleSheet);
5348
5349 SetStyleSheet(styleSheet);
5350
5351 return true;
5352 }
5353
5354 /// Pop style sheet from top of stack
5355 wxRichTextStyleSheet* wxRichTextBuffer::PopStyleSheet()
5356 {
5357 if (m_styleSheet)
5358 {
5359 wxRichTextStyleSheet* oldSheet = m_styleSheet;
5360 m_styleSheet = oldSheet->GetNextSheet();
5361 oldSheet->Unlink();
5362
5363 return oldSheet;
5364 }
5365 else
5366 return NULL;
5367 }
5368
5369 /// Submit command to insert paragraphs
5370 bool 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
5374 wxRichTextAttr attr(GetDefaultStyle());
5375
5376 wxRichTextAttr* p = NULL;
5377 wxRichTextAttr paraAttr;
5378 if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
5379 {
5380 paraAttr = GetStyleForNewParagraph(pos);
5381 if (!paraAttr.IsDefault())
5382 p = & paraAttr;
5383 }
5384 else
5385 p = & attr;
5386
5387 action->GetNewParagraphs() = paragraphs;
5388
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
5398 action->SetPosition(pos);
5399
5400 wxRichTextRange range = wxRichTextRange(pos, pos + paragraphs.GetRange().GetEnd() - 1);
5401 if (!paragraphs.GetPartialParagraph())
5402 range.SetEnd(range.GetEnd()+1);
5403
5404 // Set the range we'll need to delete in Undo
5405 action->SetRange(range);
5406
5407 SubmitAction(action);
5408
5409 return true;
5410 }
5411
5412 /// Submit command to insert the given text
5413 bool wxRichTextBuffer::InsertTextWithUndo(long pos, const wxString& text, wxRichTextCtrl* ctrl, int flags)
5414 {
5415 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Text"), wxRICHTEXT_INSERT, this, ctrl, false);
5416
5417 wxRichTextAttr* p = NULL;
5418 wxRichTextAttr paraAttr;
5419 if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
5420 {
5421 // Get appropriate paragraph style
5422 paraAttr = GetStyleForNewParagraph(pos, false, false);
5423 if (!paraAttr.IsDefault())
5424 p = & paraAttr;
5425 }
5426
5427 action->GetNewParagraphs().AddParagraphs(text, p);
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 --;
5435 action->GetNewParagraphs().SetPartialParagraph(true);
5436 }
5437 else if (text.length() > 0 && text.Last() == wxT('\n'))
5438 length --;
5439
5440 action->SetPosition(pos);
5441
5442 // Set the range we'll need to delete in Undo
5443 action->SetRange(wxRichTextRange(pos, pos + length - 1));
5444
5445 SubmitAction(action);
5446
5447 return true;
5448 }
5449
5450 /// Submit command to insert the given text
5451 bool wxRichTextBuffer::InsertNewlineWithUndo(long pos, wxRichTextCtrl* ctrl, int flags)
5452 {
5453 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Text"), wxRICHTEXT_INSERT, this, ctrl, false);
5454
5455 wxRichTextAttr* p = NULL;
5456 wxRichTextAttr paraAttr;
5457 if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
5458 {
5459 paraAttr = GetStyleForNewParagraph(pos, false, true /* look for next paragraph style */);
5460 if (!paraAttr.IsDefault())
5461 p = & paraAttr;
5462 }
5463
5464 wxRichTextAttr attr(GetDefaultStyle());
5465
5466 wxRichTextParagraph* newPara = new wxRichTextParagraph(wxEmptyString, this, & attr);
5467 action->GetNewParagraphs().AppendChild(newPara);
5468 action->GetNewParagraphs().UpdateRanges();
5469 action->GetNewParagraphs().SetPartialParagraph(false);
5470 wxRichTextParagraph* para = GetParagraphAtPosition(pos, false);
5471 long pos1 = pos;
5472
5473 if (p)
5474 newPara->SetAttributes(*p);
5475
5476 if (flags & wxRICHTEXT_INSERT_INTERACTIVE)
5477 {
5478 if (para && para->GetRange().GetEnd() == pos)
5479 pos1 ++;
5480
5481 // Now see if we need to number the paragraph.
5482 if (newPara->GetAttributes().HasBulletNumber())
5483 {
5484 wxRichTextAttr numberingAttr;
5485 if (FindNextParagraphNumber(para, numberingAttr))
5486 wxRichTextApplyStyle(newPara->GetAttributes(), (const wxRichTextAttr&) numberingAttr);
5487 }
5488 }
5489
5490 action->SetPosition(pos);
5491
5492 // Use the default character style
5493 // Use the default character style
5494 if (!GetDefaultStyle().IsDefault() && newPara->GetChildren().GetFirst())
5495 {
5496 // Check whether the default style merely reflects the paragraph/basic style,
5497 // in which case don't apply it.
5498 wxRichTextAttr defaultStyle(GetDefaultStyle());
5499 wxRichTextAttr toApply;
5500 if (para)
5501 {
5502 wxRichTextAttr combinedAttr = para->GetCombinedAttributes();
5503 wxRichTextAttr newAttr;
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 }
5514
5515 // Set the range we'll need to delete in Undo
5516 action->SetRange(wxRichTextRange(pos1, pos1));
5517
5518 SubmitAction(action);
5519
5520 return true;
5521 }
5522
5523 /// Submit command to insert the given image
5524 bool wxRichTextBuffer::InsertImageWithUndo(long pos, const wxRichTextImageBlock& imageBlock, wxRichTextCtrl* ctrl, int flags,
5525 const wxRichTextAttr& textAttr)
5526 {
5527 wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Image"), wxRICHTEXT_INSERT, this, ctrl, false);
5528
5529 wxRichTextAttr* p = NULL;
5530 wxRichTextAttr paraAttr;
5531 if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
5532 {
5533 paraAttr = GetStyleForNewParagraph(pos);
5534 if (!paraAttr.IsDefault())
5535 p = & paraAttr;
5536 }
5537
5538 wxRichTextAttr attr(GetDefaultStyle());
5539
5540 wxRichTextParagraph* newPara = new wxRichTextParagraph(this, & attr);
5541 if (p)
5542 newPara->SetAttributes(*p);
5543
5544 wxRichTextImage* imageObject = new wxRichTextImage(imageBlock, newPara);
5545 newPara->AppendChild(imageObject);
5546 imageObject->SetAttributes(textAttr);
5547 //imageObject->SetAnchoredAttr(floatAttr);
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));
5557
5558 SubmitAction(action);
5559
5560 return true;
5561 }
5562
5563 // Insert an object with no change of it
5564 bool 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
5568 wxRichTextAttr* p = NULL;
5569 wxRichTextAttr paraAttr;
5570 if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
5571 {
5572 paraAttr = GetStyleForNewParagraph(pos);
5573 if (!paraAttr.IsDefault())
5574 p = & paraAttr;
5575 }
5576
5577 wxRichTextAttr attr(GetDefaultStyle());
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 }
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.
5601 wxRichTextAttr wxRichTextBuffer::GetStyleForNewParagraph(long pos, bool caretPosition, bool lookUpNewParaStyle) const
5602 {
5603 wxRichTextParagraph* para = GetParagraphAtPosition(pos, caretPosition);
5604 if (para)
5605 {
5606 wxRichTextAttr attr;
5607 bool foundAttributes = false;
5608
5609 // Look for a matching paragraph style
5610 if (lookUpNewParaStyle && !para->GetAttributes().GetParagraphStyleName().IsEmpty() && GetStyleSheet())
5611 {
5612 wxRichTextParagraphStyleDefinition* paraDef = GetStyleSheet()->FindParagraphStyle(para->GetAttributes().GetParagraphStyleName());
5613 if (paraDef)
5614 {
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())
5617 {
5618 wxRichTextParagraphStyleDefinition* nextParaDef = GetStyleSheet()->FindParagraphStyle(paraDef->GetNextStyle());
5619 if (nextParaDef)
5620 {
5621 foundAttributes = true;
5622 attr = nextParaDef->GetStyleMergedWithBase(GetStyleSheet());
5623 }
5624 }
5625
5626 // If we didn't find the 'next style', use this style instead.
5627 if (!foundAttributes)
5628 {
5629 foundAttributes = true;
5630 attr = paraDef->GetStyleMergedWithBase(GetStyleSheet());
5631 }
5632 }
5633 }
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 }
5651 }
5652
5653 if (!foundAttributes)
5654 {
5655 attr = para->GetAttributes();
5656 int flags = attr.GetFlags();
5657
5658 // Eliminate character styles
5659 flags &= ( (~ wxTEXT_ATTR_FONT) |
5660 (~ wxTEXT_ATTR_TEXT_COLOUR) |
5661 (~ wxTEXT_ATTR_BACKGROUND_COLOUR) );
5662 attr.SetFlags(flags);
5663 }
5664
5665 return attr;
5666 }
5667 else
5668 return wxRichTextAttr();
5669 }
5670
5671 /// Submit command to delete this range
5672 bool wxRichTextBuffer::DeleteRangeWithUndo(const wxRichTextRange& range, wxRichTextCtrl* ctrl)
5673 {
5674 wxRichTextAction* action = new wxRichTextAction(NULL, _("Delete"), wxRICHTEXT_DELETE, this, ctrl);
5675
5676 action->SetPosition(ctrl->GetCaretPosition());
5677
5678 // Set the range to delete
5679 action->SetRange(range);
5680
5681 // Copy the fragment that we'll need to restore in Undo
5682 CopyFragment(range, action->GetOldParagraphs());
5683
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())
5687 {
5688 wxRichTextParagraph* para = GetParagraphAtPosition(range.GetStart());
5689 if (para && para->GetRange().GetEnd() == range.GetEnd())
5690 {
5691 wxRichTextParagraph* nextPara = GetParagraphAtPosition(range.GetStart()+1);
5692 if (nextPara && nextPara != para)
5693 {
5694 action->GetOldParagraphs().GetChildren().GetFirst()->GetData()->SetAttributes(nextPara->GetAttributes());
5695 action->GetOldParagraphs().GetAttributes().SetFlags(action->GetOldParagraphs().GetAttributes().GetFlags() | wxTEXT_ATTR_KEEP_FIRST_PARA_STYLE);
5696 }
5697 }
5698 }
5699
5700 SubmitAction(action);
5701
5702 return true;
5703 }
5704
5705 /// Collapse undo/redo commands
5706 bool wxRichTextBuffer::BeginBatchUndo(const wxString& cmdName)
5707 {
5708 if (m_batchedCommandDepth == 0)
5709 {
5710 wxASSERT(m_batchedCommand == NULL);
5711 if (m_batchedCommand)
5712 {
5713 GetCommandProcessor()->Store(m_batchedCommand);
5714 }
5715 m_batchedCommand = new wxRichTextCommand(cmdName);
5716 }
5717
5718 m_batchedCommandDepth ++;
5719
5720 return true;
5721 }
5722
5723 /// Collapse undo/redo commands
5724 bool wxRichTextBuffer::EndBatchUndo()
5725 {
5726 m_batchedCommandDepth --;
5727
5728 wxASSERT(m_batchedCommandDepth >= 0);
5729 wxASSERT(m_batchedCommand != NULL);
5730
5731 if (m_batchedCommandDepth == 0)
5732 {
5733 GetCommandProcessor()->Store(m_batchedCommand);
5734 m_batchedCommand = NULL;
5735 }
5736
5737 return true;
5738 }
5739
5740 /// Submit immediately, or delay according to whether collapsing is on
5741 bool wxRichTextBuffer::SubmitAction(wxRichTextAction* action)
5742 {
5743 if (BatchingUndo() && m_batchedCommand && !SuppressingUndo())
5744 {
5745 wxRichTextCommand* cmd = new wxRichTextCommand(action->GetName());
5746 cmd->AddAction(action);
5747 cmd->Do();
5748 cmd->GetActions().Clear();
5749 delete cmd;
5750
5751 m_batchedCommand->AddAction(action);
5752 }
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.
5766 bool wxRichTextBuffer::BeginSuppressUndo()
5767 {
5768 m_suppressUndo ++;
5769
5770 return true;
5771 }
5772
5773 /// End suppressing undo/redo commands.
5774 bool wxRichTextBuffer::EndSuppressUndo()
5775 {
5776 m_suppressUndo --;
5777
5778 return true;
5779 }
5780
5781 /// Begin using a style
5782 bool wxRichTextBuffer::BeginStyle(const wxRichTextAttr& style)
5783 {
5784 wxRichTextAttr newStyle(GetDefaultStyle());
5785
5786 // Save the old default style
5787 m_attributeStack.Append((wxObject*) new wxRichTextAttr(GetDefaultStyle()));
5788
5789 wxRichTextApplyStyle(newStyle, style);
5790 newStyle.SetFlags(style.GetFlags()|newStyle.GetFlags());
5791
5792 SetDefaultStyle(newStyle);
5793
5794 return true;
5795 }
5796
5797 /// End the style
5798 bool wxRichTextBuffer::EndStyle()
5799 {
5800 if (!m_attributeStack.GetFirst())
5801 {
5802 wxLogDebug(_("Too many EndStyle calls!"));
5803 return false;
5804 }
5805
5806 wxList::compatibility_iterator node = m_attributeStack.GetLast();
5807 wxRichTextAttr* attr = (wxRichTextAttr*)node->GetData();
5808 m_attributeStack.Erase(node);
5809
5810 SetDefaultStyle(*attr);
5811
5812 delete attr;
5813 return true;
5814 }
5815
5816 /// End all styles
5817 bool wxRichTextBuffer::EndAllStyles()
5818 {
5819 while (m_attributeStack.GetCount() != 0)
5820 EndStyle();
5821 return true;
5822 }
5823
5824 /// Clear the style stack
5825 void wxRichTextBuffer::ClearStyleStack()
5826 {
5827 for (wxList::compatibility_iterator node = m_attributeStack.GetFirst(); node; node = node->GetNext())
5828 delete (wxRichTextAttr*) node->GetData();
5829 m_attributeStack.Clear();
5830 }
5831
5832 /// Begin using bold
5833 bool wxRichTextBuffer::BeginBold()
5834 {
5835 wxRichTextAttr attr;
5836 attr.SetFontWeight(wxFONTWEIGHT_BOLD);
5837
5838 return BeginStyle(attr);
5839 }
5840
5841 /// Begin using italic
5842 bool wxRichTextBuffer::BeginItalic()
5843 {
5844 wxRichTextAttr attr;
5845 attr.SetFontStyle(wxFONTSTYLE_ITALIC);
5846
5847 return BeginStyle(attr);
5848 }
5849
5850 /// Begin using underline
5851 bool wxRichTextBuffer::BeginUnderline()
5852 {
5853 wxRichTextAttr attr;
5854 attr.SetFontUnderlined(true);
5855
5856 return BeginStyle(attr);
5857 }
5858
5859 /// Begin using point size
5860 bool wxRichTextBuffer::BeginFontSize(int pointSize)
5861 {
5862 wxRichTextAttr attr;
5863 attr.SetFontSize(pointSize);
5864
5865 return BeginStyle(attr);
5866 }
5867
5868 /// Begin using this font
5869 bool wxRichTextBuffer::BeginFont(const wxFont& font)
5870 {
5871 wxRichTextAttr attr;
5872 attr.SetFont(font);
5873
5874 return BeginStyle(attr);
5875 }
5876
5877 /// Begin using this colour
5878 bool wxRichTextBuffer::BeginTextColour(const wxColour& colour)
5879 {
5880 wxRichTextAttr attr;
5881 attr.SetFlags(wxTEXT_ATTR_TEXT_COLOUR);
5882 attr.SetTextColour(colour);
5883
5884 return BeginStyle(attr);
5885 }
5886
5887 /// Begin using alignment
5888 bool wxRichTextBuffer::BeginAlignment(wxTextAttrAlignment alignment)
5889 {
5890 wxRichTextAttr attr;
5891 attr.SetFlags(wxTEXT_ATTR_ALIGNMENT);
5892 attr.SetAlignment(alignment);
5893
5894 return BeginStyle(attr);
5895 }
5896
5897 /// Begin left indent
5898 bool wxRichTextBuffer::BeginLeftIndent(int leftIndent, int leftSubIndent)
5899 {
5900 wxRichTextAttr attr;
5901 attr.SetFlags(wxTEXT_ATTR_LEFT_INDENT);
5902 attr.SetLeftIndent(leftIndent, leftSubIndent);
5903
5904 return BeginStyle(attr);
5905 }
5906
5907 /// Begin right indent
5908 bool wxRichTextBuffer::BeginRightIndent(int rightIndent)
5909 {
5910 wxRichTextAttr attr;
5911 attr.SetFlags(wxTEXT_ATTR_RIGHT_INDENT);
5912 attr.SetRightIndent(rightIndent);
5913
5914 return BeginStyle(attr);
5915 }
5916
5917 /// Begin paragraph spacing
5918 bool 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
5926 wxRichTextAttr attr;
5927 attr.SetFlags(flags);
5928 attr.SetParagraphSpacingBefore(before);
5929 attr.SetParagraphSpacingAfter(after);
5930
5931 return BeginStyle(attr);
5932 }
5933
5934 /// Begin line spacing
5935 bool wxRichTextBuffer::BeginLineSpacing(int lineSpacing)
5936 {
5937 wxRichTextAttr attr;
5938 attr.SetFlags(wxTEXT_ATTR_LINE_SPACING);
5939 attr.SetLineSpacing(lineSpacing);
5940
5941 return BeginStyle(attr);
5942 }
5943
5944 /// Begin numbered bullet
5945 bool wxRichTextBuffer::BeginNumberedBullet(int bulletNumber, int leftIndent, int leftSubIndent, int bulletStyle)
5946 {
5947 wxRichTextAttr attr;
5948 attr.SetFlags(wxTEXT_ATTR_BULLET_STYLE|wxTEXT_ATTR_LEFT_INDENT);
5949 attr.SetBulletStyle(bulletStyle);
5950 attr.SetBulletNumber(bulletNumber);
5951 attr.SetLeftIndent(leftIndent, leftSubIndent);
5952
5953 return BeginStyle(attr);
5954 }
5955
5956 /// Begin symbol bullet
5957 bool wxRichTextBuffer::BeginSymbolBullet(const wxString& symbol, int leftIndent, int leftSubIndent, int bulletStyle)
5958 {
5959 wxRichTextAttr attr;
5960 attr.SetFlags(wxTEXT_ATTR_BULLET_STYLE|wxTEXT_ATTR_LEFT_INDENT);
5961 attr.SetBulletStyle(bulletStyle);
5962 attr.SetLeftIndent(leftIndent, leftSubIndent);
5963 attr.SetBulletText(symbol);
5964
5965 return BeginStyle(attr);
5966 }
5967
5968 /// Begin standard bullet
5969 bool wxRichTextBuffer::BeginStandardBullet(const wxString& bulletName, int leftIndent, int leftSubIndent, int bulletStyle)
5970 {
5971 wxRichTextAttr attr;
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
5980 /// Begin named character style
5981 bool wxRichTextBuffer::BeginCharacterStyle(const wxString& characterStyle)
5982 {
5983 if (GetStyleSheet())
5984 {
5985 wxRichTextCharacterStyleDefinition* def = GetStyleSheet()->FindCharacterStyle(characterStyle);
5986 if (def)
5987 {
5988 wxRichTextAttr attr = def->GetStyleMergedWithBase(GetStyleSheet());
5989 return BeginStyle(attr);
5990 }
5991 }
5992 return false;
5993 }
5994
5995 /// Begin named paragraph style
5996 bool wxRichTextBuffer::BeginParagraphStyle(const wxString& paragraphStyle)
5997 {
5998 if (GetStyleSheet())
5999 {
6000 wxRichTextParagraphStyleDefinition* def = GetStyleSheet()->FindParagraphStyle(paragraphStyle);
6001 if (def)
6002 {
6003 wxRichTextAttr attr = def->GetStyleMergedWithBase(GetStyleSheet());
6004 return BeginStyle(attr);
6005 }
6006 }
6007 return false;
6008 }
6009
6010 /// Begin named list style
6011 bool wxRichTextBuffer::BeginListStyle(const wxString& listStyle, int level, int number)
6012 {
6013 if (GetStyleSheet())
6014 {
6015 wxRichTextListStyleDefinition* def = GetStyleSheet()->FindListStyle(listStyle);
6016 if (def)
6017 {
6018 wxRichTextAttr attr(def->GetCombinedStyleForLevel(level));
6019
6020 attr.SetBulletNumber(number);
6021
6022 return BeginStyle(attr);
6023 }
6024 }
6025 return false;
6026 }
6027
6028 /// Begin URL
6029 bool wxRichTextBuffer::BeginURL(const wxString& url, const wxString& characterStyle)
6030 {
6031 wxRichTextAttr attr;
6032
6033 if (!characterStyle.IsEmpty() && GetStyleSheet())
6034 {
6035 wxRichTextCharacterStyleDefinition* def = GetStyleSheet()->FindCharacterStyle(characterStyle);
6036 if (def)
6037 {
6038 attr = def->GetStyleMergedWithBase(GetStyleSheet());
6039 }
6040 }
6041 attr.SetURL(url);
6042
6043 return BeginStyle(attr);
6044 }
6045
6046 /// Adds a handler to the end
6047 void wxRichTextBuffer::AddHandler(wxRichTextFileHandler *handler)
6048 {
6049 sm_handlers.Append(handler);
6050 }
6051
6052 /// Inserts a handler at the front
6053 void wxRichTextBuffer::InsertHandler(wxRichTextFileHandler *handler)
6054 {
6055 sm_handlers.Insert( handler );
6056 }
6057
6058 /// Removes a handler
6059 bool 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
6073 wxRichTextFileHandler *wxRichTextBuffer::FindHandlerFilenameOrType(const wxString& filename,
6074 wxRichTextFileType imageType)
6075 {
6076 if (imageType != wxRICHTEXT_TYPE_ANY)
6077 return FindHandler(imageType);
6078 else if (!filename.IsEmpty())
6079 {
6080 wxString path, file, ext;
6081 wxFileName::SplitPath(filename, & path, & file, & ext);
6082 return FindHandler(ext, imageType);
6083 }
6084 else
6085 return NULL;
6086 }
6087
6088
6089 /// Finds a handler by name
6090 wxRichTextFileHandler* 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
6104 wxRichTextFileHandler* wxRichTextBuffer::FindHandler(const wxString& extension, wxRichTextFileType type)
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
6119 wxRichTextFileHandler* wxRichTextBuffer::FindHandler(wxRichTextFileType type)
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
6131 void wxRichTextBuffer::InitStandardHandlers()
6132 {
6133 if (!FindHandler(wxRICHTEXT_TYPE_TEXT))
6134 AddHandler(new wxRichTextPlainTextHandler);
6135 }
6136
6137 void 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
6151 wxString wxRichTextBuffer::GetExtWildcard(bool combine, bool save, wxArrayInt* types)
6152 {
6153 if (types)
6154 types->Clear();
6155
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();
6163 if (handler->IsVisible() && ((save && handler->CanSave()) || (!save && handler->CanLoad())))
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();
6182 if (types)
6183 types->Add(handler->GetType());
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
6197 bool wxRichTextBuffer::LoadFile(const wxString& filename, wxRichTextFileType type)
6198 {
6199 wxRichTextFileHandler* handler = FindHandlerFilenameOrType(filename, type);
6200 if (handler)
6201 {
6202 SetDefaultStyle(wxRichTextAttr());
6203 handler->SetFlags(GetHandlerFlags());
6204 bool success = handler->LoadFile(this, filename);
6205 Invalidate(wxRICHTEXT_ALL);
6206 return success;
6207 }
6208 else
6209 return false;
6210 }
6211
6212 /// Save a file
6213 bool wxRichTextBuffer::SaveFile(const wxString& filename, wxRichTextFileType type)
6214 {
6215 wxRichTextFileHandler* handler = FindHandlerFilenameOrType(filename, type);
6216 if (handler)
6217 {
6218 handler->SetFlags(GetHandlerFlags());
6219 return handler->SaveFile(this, filename);
6220 }
6221 else
6222 return false;
6223 }
6224
6225 /// Load from a stream
6226 bool wxRichTextBuffer::LoadFile(wxInputStream& stream, wxRichTextFileType type)
6227 {
6228 wxRichTextFileHandler* handler = FindHandler(type);
6229 if (handler)
6230 {
6231 SetDefaultStyle(wxRichTextAttr());
6232 handler->SetFlags(GetHandlerFlags());
6233 bool success = handler->LoadFile(this, stream);
6234 Invalidate(wxRICHTEXT_ALL);
6235 return success;
6236 }
6237 else
6238 return false;
6239 }
6240
6241 /// Save to a stream
6242 bool wxRichTextBuffer::SaveFile(wxOutputStream& stream, wxRichTextFileType type)
6243 {
6244 wxRichTextFileHandler* handler = FindHandler(type);
6245 if (handler)
6246 {
6247 handler->SetFlags(GetHandlerFlags());
6248 return handler->SaveFile(this, stream);
6249 }
6250 else
6251 return false;
6252 }
6253
6254 /// Copy the range to the clipboard
6255 bool wxRichTextBuffer::CopyToClipboard(const wxRichTextRange& range)
6256 {
6257 bool success = false;
6258 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
6259
6260 if (!wxTheClipboard->IsOpened() && wxTheClipboard->Open())
6261 {
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
6291 wxTheClipboard->Close();
6292 }
6293
6294 #else
6295 wxUnusedVar(range);
6296 #endif
6297 return success;
6298 }
6299
6300 /// Paste the clipboard content to the buffer
6301 bool wxRichTextBuffer::PasteFromClipboard(long position)
6302 {
6303 bool success = false;
6304 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
6305 if (CanPasteFromClipboard())
6306 {
6307 if (wxTheClipboard->Open())
6308 {
6309 if (wxTheClipboard->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())))
6310 {
6311 wxRichTextBufferDataObject data;
6312 wxTheClipboard->GetData(data);
6313 wxRichTextBuffer* richTextBuffer = data.GetRichTextBuffer();
6314 if (richTextBuffer)
6315 {
6316 InsertParagraphsWithUndo(position+1, *richTextBuffer, GetRichTextCtrl(), 0);
6317 if (GetRichTextCtrl())
6318 GetRichTextCtrl()->ShowPosition(position + richTextBuffer->GetRange().GetEnd());
6319 delete richTextBuffer;
6320 }
6321 }
6322 else if (wxTheClipboard->IsSupported(wxDF_TEXT) || wxTheClipboard->IsSupported(wxDF_UNICODETEXT))
6323 {
6324 wxTextDataObject data;
6325 wxTheClipboard->GetData(data);
6326 wxString text(data.GetText());
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
6340 InsertTextWithUndo(position+1, text2, GetRichTextCtrl(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE);
6341
6342 if (GetRichTextCtrl())
6343 GetRichTextCtrl()->ShowPosition(position + text2.Length());
6344
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);
6355
6356 action->GetNewParagraphs().AddImage(image);
6357
6358 if (action->GetNewParagraphs().GetChildCount() == 1)
6359 action->GetNewParagraphs().SetPartialParagraph(true);
6360
6361 action->SetPosition(position+1);
6362
6363 // Set the range we'll need to delete in Undo
6364 action->SetRange(wxRichTextRange(position+1, position+1));
6365
6366 SubmitAction(action);
6367
6368 success = true;
6369 }
6370 wxTheClipboard->Close();
6371 }
6372 }
6373 #else
6374 wxUnusedVar(position);
6375 #endif
6376 return success;
6377 }
6378
6379 /// Can we paste from the clipboard?
6380 bool wxRichTextBuffer::CanPasteFromClipboard() const
6381 {
6382 bool canPaste = false;
6383 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
6384 if (!wxTheClipboard->IsOpened() && wxTheClipboard->Open())
6385 {
6386 if (wxTheClipboard->IsSupported(wxDF_TEXT) || wxTheClipboard->IsSupported(wxDF_UNICODETEXT) ||
6387 wxTheClipboard->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())) ||
6388 wxTheClipboard->IsSupported(wxDF_BITMAP))
6389 {
6390 canPaste = true;
6391 }
6392 wxTheClipboard->Close();
6393 }
6394 #endif
6395 return canPaste;
6396 }
6397
6398 /// Dumps contents of buffer for debugging purposes
6399 void 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
6411 /// Add an event handler
6412 bool wxRichTextBuffer::AddEventHandler(wxEvtHandler* handler)
6413 {
6414 m_eventHandlers.Append(handler);
6415 return true;
6416 }
6417
6418 /// Remove an event handler
6419 bool 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;
6427
6428 return true;
6429 }
6430 else
6431 return false;
6432 }
6433
6434 /// Clear event handlers
6435 void 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.
6442 bool 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
6459 bool wxRichTextBuffer::SetStyleSheetAndNotify(wxRichTextStyleSheet* sheet)
6460 {
6461 wxRichTextStyleSheet* oldSheet = GetStyleSheet();
6462
6463 wxWindowID id = wxID_ANY;
6464 if (GetRichTextCtrl())
6465 id = GetRichTextCtrl()->GetId();
6466
6467 wxRichTextEvent event(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING, id);
6468 event.SetEventObject(GetRichTextCtrl());
6469 event.SetOldStyleSheet(oldSheet);
6470 event.SetNewStyleSheet(sheet);
6471 event.Allow();
6472
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
6494 void wxRichTextBuffer::SetRenderer(wxRichTextRenderer* renderer)
6495 {
6496 if (sm_renderer)
6497 delete sm_renderer;
6498 sm_renderer = renderer;
6499 }
6500
6501 bool wxRichTextStdRenderer::DrawStandardBullet(wxRichTextParagraph* paragraph, wxDC& dc, const wxRichTextAttr& bulletAttr, const wxRect& rect)
6502 {
6503 if (bulletAttr.GetTextColour().Ok())
6504 {
6505 wxCheckSetPen(dc, wxPen(bulletAttr.GetTextColour()));
6506 wxCheckSetBrush(dc, wxBrush(bulletAttr.GetTextColour()));
6507 }
6508 else
6509 {
6510 wxCheckSetPen(dc, *wxBLACK_PEN);
6511 wxCheckSetBrush(dc, *wxBLACK_BRUSH);
6512 }
6513
6514 wxFont font;
6515 if (bulletAttr.HasFont())
6516 {
6517 font = paragraph->GetBuffer()->GetFontTable().FindFont(bulletAttr);
6518 }
6519 else
6520 font = (*wxNORMAL_FONT);
6521
6522 wxCheckSetFont(dc, font);
6523
6524 int charHeight = dc.GetCharHeight();
6525
6526 int bulletWidth = (int) (((float) charHeight) * wxRichTextBuffer::GetBulletProportion());
6527 int bulletHeight = bulletWidth;
6528
6529 int x = rect.x;
6530
6531 // Calculate the top position of the character (as opposed to the whole line height)
6532 int y = rect.y + (rect.height - charHeight);
6533
6534 // Calculate where the bullet should be positioned
6535 y = y + (charHeight+1)/2 - (bulletHeight+1)/2;
6536
6537 // The margin between a bullet and text.
6538 int margin = paragraph->ConvertTenthsMMToPixels(dc, wxRichTextBuffer::GetBulletRightMargin());
6539
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;
6544
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;
6556
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;
6565
6566 dc.DrawPolygon(3, pts);
6567 }
6568 else // "standard/circle", and catch-all
6569 {
6570 dc.DrawEllipse(x, y, bulletWidth, bulletHeight);
6571 }
6572
6573 return true;
6574 }
6575
6576 bool wxRichTextStdRenderer::DrawTextBullet(wxRichTextParagraph* paragraph, wxDC& dc, const wxRichTextAttr& attr, const wxRect& rect, const wxString& text)
6577 {
6578 if (!text.empty())
6579 {
6580 wxFont font;
6581 if ((attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL) && !attr.GetBulletFont().IsEmpty() && attr.HasFont())
6582 {
6583 wxRichTextAttr fontAttr;
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);
6593 else
6594 font = (*wxNORMAL_FONT);
6595
6596 wxCheckSetFont(dc, font);
6597
6598 if (attr.GetTextColour().Ok())
6599 dc.SetTextForeground(attr.GetTextColour());
6600
6601 dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT);
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)
6610 int y = rect.y + (rect.height - charHeight);
6611
6612 // The margin between a bullet and text.
6613 int margin = paragraph->ConvertTenthsMMToPixels(dc, wxRichTextBuffer::GetBulletRightMargin());
6614
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);
6621
6622 return true;
6623 }
6624 else
6625 return false;
6626 }
6627
6628 bool wxRichTextStdRenderer::DrawBitmapBullet(wxRichTextParagraph* WXUNUSED(paragraph), wxDC& WXUNUSED(dc), const wxRichTextAttr& WXUNUSED(attr), const wxRect& WXUNUSED(rect))
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
6636 bool wxRichTextStdRenderer::EnumerateStandardBulletNames(wxArrayString& bulletNames)
6637 {
6638 bulletNames.Add(wxTRANSLATE("standard/circle"));
6639 bulletNames.Add(wxTRANSLATE("standard/square"));
6640 bulletNames.Add(wxTRANSLATE("standard/diamond"));
6641 bulletNames.Add(wxTRANSLATE("standard/triangle"));
6642
6643 return true;
6644 }
6645
6646 /*
6647 * Module to initialise and clean up handlers
6648 */
6649
6650 class wxRichTextModule: public wxModule
6651 {
6652 DECLARE_DYNAMIC_CLASS(wxRichTextModule)
6653 public:
6654 wxRichTextModule() {}
6655 bool OnInit()
6656 {
6657 wxRichTextBuffer::SetRenderer(new wxRichTextStdRenderer);
6658 wxRichTextBuffer::InitStandardHandlers();
6659 wxRichTextParagraph::InitDefaultTabs();
6660 return true;
6661 }
6662 void OnExit()
6663 {
6664 wxRichTextBuffer::CleanUpHandlers();
6665 wxRichTextDecimalToRoman(-1);
6666 wxRichTextParagraph::ClearDefaultTabs();
6667 wxRichTextCtrl::ClearAvailableFontNames();
6668 wxRichTextBuffer::SetRenderer(NULL);
6669 }
6670 };
6671
6672 IMPLEMENT_DYNAMIC_CLASS(wxRichTextModule, wxModule)
6673
6674
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.
6678 void wxRichTextModuleInit()
6679 {
6680 wxModule* module = new wxRichTextModule;
6681 module->Init();
6682 wxModule::RegisterModule(module);
6683 }
6684
6685
6686 /*!
6687 * Commands for undo/redo
6688 *
6689 */
6690
6691 wxRichTextCommand::wxRichTextCommand(const wxString& name, wxRichTextCommandId id, wxRichTextBuffer* buffer,
6692 wxRichTextCtrl* ctrl, bool ignoreFirstTime): wxCommand(true, name)
6693 {
6694 /* wxRichTextAction* action = */ new wxRichTextAction(this, name, id, buffer, ctrl, ignoreFirstTime);
6695 }
6696
6697 wxRichTextCommand::wxRichTextCommand(const wxString& name): wxCommand(true, name)
6698 {
6699 }
6700
6701 wxRichTextCommand::~wxRichTextCommand()
6702 {
6703 ClearActions();
6704 }
6705
6706 void wxRichTextCommand::AddAction(wxRichTextAction* action)
6707 {
6708 if (!m_actions.Member(action))
6709 m_actions.Append(action);
6710 }
6711
6712 bool wxRichTextCommand::Do()
6713 {
6714 for (wxList::compatibility_iterator node = m_actions.GetFirst(); node; node = node->GetNext())
6715 {
6716 wxRichTextAction* action = (wxRichTextAction*) node->GetData();
6717 action->Do();
6718 }
6719
6720 return true;
6721 }
6722
6723 bool wxRichTextCommand::Undo()
6724 {
6725 for (wxList::compatibility_iterator node = m_actions.GetLast(); node; node = node->GetPrevious())
6726 {
6727 wxRichTextAction* action = (wxRichTextAction*) node->GetData();
6728 action->Undo();
6729 }
6730
6731 return true;
6732 }
6733
6734 void wxRichTextCommand::ClearActions()
6735 {
6736 WX_CLEAR_LIST(wxList, m_actions);
6737 }
6738
6739 /*!
6740 * Individual action
6741 *
6742 */
6743
6744 wxRichTextAction::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
6759 wxRichTextAction::~wxRichTextAction()
6760 {
6761 }
6762
6763 void 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
6815 bool wxRichTextAction::Do()
6816 {
6817 m_buffer->Modify(true);
6818
6819 switch (m_cmdId)
6820 {
6821 case wxRICHTEXT_INSERT:
6822 {
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
6829 CalculateRefreshOptimizations(optimizationLineCharPositions, optimizationLineYPositions);
6830 #endif
6831
6832 m_buffer->InsertFragment(GetRange().GetStart(), m_newParagraphs);
6833 m_buffer->UpdateRanges();
6834 m_buffer->Invalidate(wxRichTextRange(wxMax(0, GetRange().GetStart()-1), GetRange().GetEnd()));
6835
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
6842 if (m_newParagraphs.GetPartialParagraph())
6843 newCaretPosition --;
6844 else
6845 if (m_newParagraphs.GetChildren().GetCount() > 1)
6846 {
6847 wxRichTextObject* p = (wxRichTextObject*) m_newParagraphs.GetChildren().GetLast()->GetData();
6848 if (p->GetRange().GetLength() == 1)
6849 newCaretPosition --;
6850 }
6851
6852 newCaretPosition = wxMin(newCaretPosition, (m_buffer->GetRange().GetEnd()-1));
6853
6854 UpdateAppearance(newCaretPosition, true /* send update event */, & optimizationLineCharPositions, & optimizationLineYPositions, true /* do */);
6855
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());
6862
6863 m_buffer->SendEvent(cmdEvent);
6864
6865 break;
6866 }
6867 case wxRICHTEXT_DELETE:
6868 {
6869 wxArrayInt optimizationLineCharPositions;
6870 wxArrayInt optimizationLineYPositions;
6871
6872 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6873 CalculateRefreshOptimizations(optimizationLineCharPositions, optimizationLineYPositions);
6874 #endif
6875
6876 m_buffer->DeleteRange(GetRange());
6877 m_buffer->UpdateRanges();
6878 m_buffer->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6879
6880 long caretPos = GetRange().GetStart()-1;
6881 if (caretPos >= m_buffer->GetRange().GetEnd())
6882 caretPos --;
6883
6884 UpdateAppearance(caretPos, true /* send update event */, & optimizationLineCharPositions, & optimizationLineYPositions, true /* do */);
6885
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());
6892
6893 m_buffer->SendEvent(cmdEvent);
6894
6895 break;
6896 }
6897 case wxRICHTEXT_CHANGE_STYLE:
6898 {
6899 ApplyParagraphs(GetNewParagraphs());
6900 m_buffer->Invalidate(GetRange());
6901
6902 UpdateAppearance(GetPosition());
6903
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());
6910
6911 m_buffer->SendEvent(cmdEvent);
6912
6913 break;
6914 }
6915 default:
6916 break;
6917 }
6918
6919 return true;
6920 }
6921
6922 bool wxRichTextAction::Undo()
6923 {
6924 m_buffer->Modify(true);
6925
6926 switch (m_cmdId)
6927 {
6928 case wxRICHTEXT_INSERT:
6929 {
6930 wxArrayInt optimizationLineCharPositions;
6931 wxArrayInt optimizationLineYPositions;
6932
6933 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6934 CalculateRefreshOptimizations(optimizationLineCharPositions, optimizationLineYPositions);
6935 #endif
6936
6937 m_buffer->DeleteRange(GetRange());
6938 m_buffer->UpdateRanges();
6939 m_buffer->Invalidate(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
6940
6941 long newCaretPosition = GetPosition() - 1;
6942
6943 UpdateAppearance(newCaretPosition, true, /* send update event */ & optimizationLineCharPositions, & optimizationLineYPositions, false /* undo */);
6944
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());
6951
6952 m_buffer->SendEvent(cmdEvent);
6953
6954 break;
6955 }
6956 case wxRICHTEXT_DELETE:
6957 {
6958 wxArrayInt optimizationLineCharPositions;
6959 wxArrayInt optimizationLineYPositions;
6960
6961 #if wxRICHTEXT_USE_OPTIMIZED_DRAWING
6962 CalculateRefreshOptimizations(optimizationLineCharPositions, optimizationLineYPositions);
6963 #endif
6964
6965 m_buffer->InsertFragment(GetRange().GetStart(), m_oldParagraphs);
6966 m_buffer->UpdateRanges();
6967 m_buffer->Invalidate(GetRange());
6968
6969 UpdateAppearance(GetPosition(), true, /* send update event */ & optimizationLineCharPositions, & optimizationLineYPositions, false /* undo */);
6970
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());
6977
6978 m_buffer->SendEvent(cmdEvent);
6979
6980 break;
6981 }
6982 case wxRICHTEXT_CHANGE_STYLE:
6983 {
6984 ApplyParagraphs(GetOldParagraphs());
6985 m_buffer->Invalidate(GetRange());
6986
6987 UpdateAppearance(GetPosition());
6988
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());
6995
6996 m_buffer->SendEvent(cmdEvent);
6997
6998 break;
6999 }
7000 default:
7001 break;
7002 }
7003
7004 return true;
7005 }
7006
7007 /// Update the control appearance
7008 void wxRichTextAction::UpdateAppearance(long caretPosition, bool sendUpdateEvent, wxArrayInt* WXUNUSED(optimizationLineCharPositions), wxArrayInt* WXUNUSED(optimizationLineYPositions), bool WXUNUSED(isDoCmd))
7009 {
7010 if (m_ctrl)
7011 {
7012 m_ctrl->SetCaretPosition(caretPosition);
7013 if (!m_ctrl->IsFrozen())
7014 {
7015 m_ctrl->LayoutContent();
7016 // TODO Refresh the whole client area now
7017 m_ctrl->Refresh(false);
7018
7019 #if wxRICHTEXT_USE_OWN_CARET
7020 m_ctrl->PositionCaret();
7021 #endif
7022 if (sendUpdateEvent)
7023 wxTextCtrl::SendTextUpdatedEvent(m_ctrl);
7024 }
7025 }
7026 }
7027
7028 /// Replace the buffer paragraphs with the new ones.
7029 void wxRichTextAction::ApplyParagraphs(const wxRichTextParagraphLayoutBox& fragment)
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'
7067 bool 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
7078 /*!
7079 * wxRichTextAnchoredObject implementation
7080 */
7081 IMPLEMENT_CLASS(wxRichTextAnchoredObject, wxRichTextObject)
7082
7083 wxRichTextAnchoredObject::wxRichTextAnchoredObject(wxRichTextObject* parent, const wxRichTextAttr& attr):
7084 wxRichTextObject(parent)
7085 {
7086 SetAttributes(attr);
7087 }
7088
7089 wxRichTextAnchoredObject::~wxRichTextAnchoredObject()
7090 {
7091 }
7092
7093 void wxRichTextAnchoredObject::Copy(const wxRichTextAnchoredObject& obj)
7094 {
7095 wxRichTextObject::Copy(obj);
7096 }
7097
7098 void wxRichTextAnchoredObject::SetParent(wxRichTextObject* parent)
7099 {
7100 wxRichTextObject::SetParent(parent);
7101 }
7102
7103 /*!
7104 * wxRichTextImage implementation
7105 * This object represents an image.
7106 */
7107
7108 IMPLEMENT_DYNAMIC_CLASS(wxRichTextImage, wxRichTextAnchoredObject)
7109
7110 wxRichTextImage::wxRichTextImage(const wxImage& image, wxRichTextObject* parent, wxRichTextAttr* charStyle):
7111 wxRichTextAnchoredObject(parent)
7112 {
7113 m_imageBlock.MakeImageBlockDefaultQuality(image, wxBITMAP_TYPE_PNG);
7114 if (charStyle)
7115 SetAttributes(*charStyle);
7116 }
7117
7118 wxRichTextImage::wxRichTextImage(const wxRichTextImageBlock& imageBlock, wxRichTextObject* parent, wxRichTextAttr* charStyle):
7119 wxRichTextAnchoredObject(parent)
7120 {
7121 m_imageBlock = imageBlock;
7122 if (charStyle)
7123 SetAttributes(*charStyle);
7124 }
7125
7126 /// Create a cached image at the required size
7127 bool wxRichTextImage::LoadImageCache(wxDC& dc, bool resetCache)
7128 {
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;
7133
7134 wxImage image;
7135 m_imageBlock.Load(image);
7136 if (!image.IsOk())
7137 return false;
7138
7139 int width = image.GetWidth();
7140 int height = image.GetHeight();
7141
7142 if (GetAttributes().GetTextBoxAttr().GetWidth().IsPresent() && GetAttributes().GetTextBoxAttr().GetWidth().GetValue() > 0)
7143 {
7144 if (GetAttributes().GetTextBoxAttr().GetWidth().GetUnits() == wxTEXT_ATTR_UNITS_TENTHS_MM)
7145 width = ConvertTenthsMMToPixels(dc, GetAttributes().GetTextBoxAttr().GetWidth().GetValue());
7146 else
7147 width = GetAttributes().GetTextBoxAttr().GetWidth().GetValue();
7148 }
7149 if (GetAttributes().GetTextBoxAttr().GetHeight().IsPresent() && GetAttributes().GetTextBoxAttr().GetHeight().GetValue() > 0)
7150 {
7151 if (GetAttributes().GetTextBoxAttr().GetHeight().GetUnits() == wxTEXT_ATTR_UNITS_TENTHS_MM)
7152 height = ConvertTenthsMMToPixels(dc, GetAttributes().GetTextBoxAttr().GetHeight().GetValue());
7153 else
7154 height = GetAttributes().GetTextBoxAttr().GetHeight().GetValue();
7155 }
7156
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 }
7176
7177 return m_imageCache.IsOk();
7178 }
7179
7180 /// Draw the item
7181 bool wxRichTextImage::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextRange& selectionRange, const wxRect& rect, int WXUNUSED(descent), int WXUNUSED(style))
7182 {
7183 // Don't need cached size AFAIK
7184 // wxSize size = GetCachedSize();
7185 if (!LoadImageCache(dc))
7186 return false;
7187
7188 int y = rect.y + (rect.height - m_imageCache.GetHeight());
7189
7190 dc.DrawBitmap(m_imageCache, rect.x, y, true);
7191
7192 if (selectionRange.Contains(range.GetStart()))
7193 {
7194 wxCheckSetBrush(dc, *wxBLACK_BRUSH);
7195 wxCheckSetPen(dc, *wxBLACK_PEN);
7196 dc.SetLogicalFunction(wxINVERT);
7197 dc.DrawRectangle(rect);
7198 dc.SetLogicalFunction(wxCOPY);
7199 }
7200
7201 return true;
7202 }
7203
7204 /// Lay the item out
7205 bool wxRichTextImage::Layout(wxDC& dc, const wxRect& rect, int WXUNUSED(style))
7206 {
7207 if (!LoadImageCache(dc))
7208 return false;
7209
7210 SetCachedSize(wxSize(m_imageCache.GetWidth(), m_imageCache.GetHeight()));
7211 SetPosition(rect.GetPosition());
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.
7218 bool wxRichTextImage::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& WXUNUSED(descent), wxDC& dc, int WXUNUSED(flags), wxPoint WXUNUSED(position), wxArrayInt* partialExtents) const
7219 {
7220 if (!range.IsWithin(GetRange()))
7221 return false;
7222
7223 if (!((wxRichTextImage*)this)->LoadImageCache(dc))
7224 {
7225 size.x = 0; size.y = 0;
7226 if (partialExtents)
7227 partialExtents->Add(0);
7228 return false;
7229 }
7230
7231 int width = m_imageCache.GetWidth();
7232 int height = m_imageCache.GetHeight();
7233
7234 if (partialExtents)
7235 partialExtents->Add(width);
7236
7237 size.x = width;
7238 size.y = height;
7239
7240 return true;
7241 }
7242
7243 /// Copy
7244 void wxRichTextImage::Copy(const wxRichTextImage& obj)
7245 {
7246 wxRichTextAnchoredObject::Copy(obj);
7247
7248 m_imageBlock = obj.m_imageBlock;
7249 }
7250
7251 /// Edit properties via a GUI
7252 bool 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
7266 /*!
7267 * Utilities
7268 *
7269 */
7270
7271 /// Compare two attribute objects
7272 bool wxTextAttrEq(const wxRichTextAttr& attr1, const wxRichTextAttr& attr2)
7273 {
7274 return (attr1 == attr2);
7275 }
7276
7277 // Partial equality test taking flags into account
7278 bool wxTextAttrEqPartial(const wxRichTextAttr& attr1, const wxRichTextAttr& attr2)
7279 {
7280 return attr1.EqPartial(attr2);
7281 }
7282
7283 /// Compare tabs
7284 bool wxRichTextTabsEq(const wxArrayInt& tabs1, const wxArrayInt& tabs2)
7285 {
7286 if (tabs1.GetCount() != tabs2.GetCount())
7287 return false;
7288
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 }
7297
7298 bool wxRichTextApplyStyle(wxRichTextAttr& destStyle, const wxRichTextAttr& style, wxRichTextAttr* compareWith)
7299 {
7300 return destStyle.Apply(style, compareWith);
7301 }
7302
7303 // Remove attributes
7304 bool wxRichTextRemoveStyle(wxRichTextAttr& destStyle, const wxRichTextAttr& style)
7305 {
7306 return destStyle.RemoveStyle(style);
7307 }
7308
7309 /// Combine two bitlists, specifying the bits of interest with separate flags.
7310 bool wxRichTextCombineBitlists(int& valueA, int valueB, int& flagsA, int flagsB)
7311 {
7312 return wxRichTextAttr::CombineBitlists(valueA, valueB, flagsA, flagsB);
7313 }
7314
7315 /// Compare two bitlists
7316 bool wxRichTextBitlistsEqPartial(int valueA, int valueB, int flags)
7317 {
7318 return wxRichTextAttr::BitlistsEqPartial(valueA, valueB, flags);
7319 }
7320
7321 /// Split into paragraph and character styles
7322 bool wxRichTextSplitParaCharStyles(const wxRichTextAttr& style, wxRichTextAttr& parStyle, wxRichTextAttr& charStyle)
7323 {
7324 return wxRichTextAttr::SplitParaCharStyles(style, parStyle, charStyle);
7325 }
7326
7327 /// Convert a decimal to Roman numerals
7328 wxString wxRichTextDecimalToRoman(long n)
7329 {
7330 static wxArrayInt decimalNumbers;
7331 static wxArrayString romanNumbers;
7332
7333 // Clean up arrays
7334 if (n == -1)
7335 {
7336 decimalNumbers.Clear();
7337 romanNumbers.Clear();
7338 return wxEmptyString;
7339 }
7340
7341 if (decimalNumbers.GetCount() == 0)
7342 {
7343 #define wxRichTextAddDecRom(n, r) decimalNumbers.Add(n); romanNumbers.Add(r);
7344
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 }
7359
7360 int i = 0;
7361 wxString roman;
7362
7363 while (n > 0 && i < 13)
7364 {
7365 if (n >= decimalNumbers[i])
7366 {
7367 n -= decimalNumbers[i];
7368 roman += romanNumbers[i];
7369 }
7370 else
7371 {
7372 i ++;
7373 }
7374 }
7375 if (roman.IsEmpty())
7376 roman = wxT("0");
7377 return roman;
7378 }
7379
7380 /*!
7381 * wxRichTextFileHandler
7382 * Base class for file handlers
7383 */
7384
7385 IMPLEMENT_CLASS(wxRichTextFileHandler, wxObject)
7386
7387 #if wxUSE_FFILE && wxUSE_STREAMS
7388 bool wxRichTextFileHandler::LoadFile(wxRichTextBuffer *buffer, const wxString& filename)
7389 {
7390 wxFFileInputStream stream(filename);
7391 if (stream.Ok())
7392 return LoadFile(buffer, stream);
7393
7394 return false;
7395 }
7396
7397 bool wxRichTextFileHandler::SaveFile(wxRichTextBuffer *buffer, const wxString& filename)
7398 {
7399 wxFFileOutputStream stream(filename);
7400 if (stream.Ok())
7401 return SaveFile(buffer, stream);
7402
7403 return false;
7404 }
7405 #endif // wxUSE_FFILE && wxUSE_STREAMS
7406
7407 /// Can we handle this filename (if using files)? By default, checks the extension.
7408 bool wxRichTextFileHandler::CanHandle(const wxString& filename) const
7409 {
7410 wxString path, file, ext;
7411 wxFileName::SplitPath(filename, & path, & file, & ext);
7412
7413 return (ext.Lower() == GetExtension());
7414 }
7415
7416 /*!
7417 * wxRichTextTextHandler
7418 * Plain text handler
7419 */
7420
7421 IMPLEMENT_CLASS(wxRichTextPlainTextHandler, wxRichTextFileHandler)
7422
7423 #if wxUSE_STREAMS
7424 bool wxRichTextPlainTextHandler::DoLoadFile(wxRichTextBuffer *buffer, wxInputStream& stream)
7425 {
7426 if (!stream.IsOk())
7427 return false;
7428
7429 wxString str;
7430 int lastCh = 0;
7431
7432 while (!stream.Eof())
7433 {
7434 int ch = stream.GetC();
7435
7436 if (!stream.Eof())
7437 {
7438 if (ch == 10 && lastCh != 13)
7439 str += wxT('\n');
7440
7441 if (ch > 0 && ch != 10)
7442 str += wxChar(ch);
7443
7444 lastCh = ch;
7445 }
7446 }
7447
7448 buffer->ResetAndClearCommands();
7449 buffer->Clear();
7450 buffer->AddParagraphs(str);
7451 buffer->UpdateRanges();
7452
7453 return true;
7454 }
7455
7456 bool wxRichTextPlainTextHandler::DoSaveFile(wxRichTextBuffer *buffer, wxOutputStream& stream)
7457 {
7458 if (!stream.IsOk())
7459 return false;
7460
7461 wxString text = buffer->GetText();
7462
7463 wxString newLine = wxRichTextLineBreakChar;
7464 text.Replace(newLine, wxT("\n"));
7465
7466 wxCharBuffer buf = text.ToAscii();
7467
7468 stream.Write((const char*) buf, text.length());
7469 return true;
7470 }
7471 #endif // wxUSE_STREAMS
7472
7473 /*
7474 * Stores information about an image, in binary in-memory form
7475 */
7476
7477 wxRichTextImageBlock::wxRichTextImageBlock()
7478 {
7479 Init();
7480 }
7481
7482 wxRichTextImageBlock::wxRichTextImageBlock(const wxRichTextImageBlock& block):wxObject()
7483 {
7484 Init();
7485 Copy(block);
7486 }
7487
7488 wxRichTextImageBlock::~wxRichTextImageBlock()
7489 {
7490 wxDELETEA(m_data);
7491 }
7492
7493 void wxRichTextImageBlock::Init()
7494 {
7495 m_data = NULL;
7496 m_dataSize = 0;
7497 m_imageType = wxBITMAP_TYPE_INVALID;
7498 }
7499
7500 void wxRichTextImageBlock::Clear()
7501 {
7502 wxDELETEA(m_data);
7503 m_dataSize = 0;
7504 m_imageType = wxBITMAP_TYPE_INVALID;
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
7514 bool wxRichTextImageBlock::MakeImageBlock(const wxString& filename, wxBitmapType imageType,
7515 wxImage& image, bool convertToJPEG)
7516 {
7517 m_imageType = imageType;
7518
7519 wxString filenameToRead(filename);
7520 bool removeFile = false;
7521
7522 if (imageType == wxBITMAP_TYPE_INVALID)
7523 return false; // Could not determine image type
7524
7525 if ((imageType != wxBITMAP_TYPE_JPEG) && convertToJPEG)
7526 {
7527 wxString tempFile =
7528 wxFileName::CreateTempFileName(_("image"));
7529
7530 wxASSERT(!tempFile.IsEmpty());
7531
7532 image.SaveFile(tempFile, wxBITMAP_TYPE_JPEG);
7533 filenameToRead = tempFile;
7534 removeFile = true;
7535
7536 m_imageType = wxBITMAP_TYPE_JPEG;
7537 }
7538 wxFile file;
7539 if (!file.Open(filenameToRead))
7540 return false;
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.
7557 bool wxRichTextImageBlock::MakeImageBlock(wxImage& image, wxBitmapType imageType, int quality)
7558 {
7559 image.SetOption(wxT("quality"), quality);
7560
7561 if (imageType == wxBITMAP_TYPE_INVALID)
7562 return false; // Could not determine image type
7563
7564 return DoMakeImageBlock(image, imageType);
7565 }
7566
7567 // Uses a const wxImage for efficiency, but can't set quality (only relevant for JPEG)
7568 bool wxRichTextImageBlock::MakeImageBlockDefaultQuality(const wxImage& image, wxBitmapType imageType)
7569 {
7570 if (imageType == wxBITMAP_TYPE_INVALID)
7571 return false; // Could not determine image type
7572
7573 return DoMakeImageBlock(image, imageType);
7574 }
7575
7576 // Makes the image block
7577 bool wxRichTextImageBlock::DoMakeImageBlock(const wxImage& image, wxBitmapType imageType)
7578 {
7579 wxMemoryOutputStream memStream;
7580 if (!image.SaveFile(memStream, imageType))
7581 {
7582 return false;
7583 }
7584
7585 unsigned char* block = new unsigned char[memStream.GetSize()];
7586 if (!block)
7587 return NULL;
7588
7589 if (m_data)
7590 delete[] m_data;
7591 m_data = block;
7592
7593 m_imageType = imageType;
7594 m_dataSize = memStream.GetSize();
7595
7596 memStream.CopyTo(m_data, m_dataSize);
7597
7598 return (m_data != NULL);
7599 }
7600
7601 // Write to a file
7602 bool wxRichTextImageBlock::Write(const wxString& filename)
7603 {
7604 return WriteBlock(filename, m_data, m_dataSize);
7605 }
7606
7607 void wxRichTextImageBlock::Copy(const wxRichTextImageBlock& block)
7608 {
7609 m_imageType = block.m_imageType;
7610 wxDELETEA(m_data);
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
7622 void wxRichTextImageBlock::operator=(const wxRichTextImageBlock& block)
7623 {
7624 Copy(block);
7625 }
7626
7627 // Load a wxImage from the block
7628 bool wxRichTextImageBlock::Load(wxImage& image)
7629 {
7630 if (!m_data)
7631 return false;
7632
7633 // Read in the image.
7634 #if wxUSE_STREAMS
7635 wxMemoryInputStream mstream(m_data, m_dataSize);
7636 bool success = image.LoadFile(mstream, GetImageType());
7637 #else
7638 wxString tempFile = wxFileName::CreateTempFileName(_("image"));
7639 wxASSERT(!tempFile.IsEmpty());
7640
7641 if (!WriteBlock(tempFile, m_data, m_dataSize))
7642 {
7643 return false;
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
7653 bool wxRichTextImageBlock::WriteHex(wxOutputStream& stream)
7654 {
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)
7662 {
7663 if (left*2 > bufSize)
7664 {
7665 n = bufSize; left -= (bufSize/2);
7666 }
7667 else
7668 {
7669 n = left*2; left = 0;
7670 }
7671
7672 char* b = buf;
7673 for (i = 0; i < (n/2); i++)
7674 {
7675 wxDecToHex(m_data[j], b, b+1);
7676 b += 2; j ++;
7677 }
7678
7679 buf[n] = 0;
7680 stream.Write((const char*) buf, n);
7681 }
7682 return true;
7683 }
7684
7685 // Read data in hex from a stream
7686 bool wxRichTextImageBlock::ReadHex(wxInputStream& stream, int length, wxBitmapType imageType)
7687 {
7688 int dataSize = length/2;
7689
7690 if (m_data)
7691 delete[] m_data;
7692
7693 // create a null terminated temporary string:
7694 char str[3];
7695 str[2] = '\0';
7696
7697 m_data = new unsigned char[dataSize];
7698 int i;
7699 for (i = 0; i < dataSize; i ++)
7700 {
7701 str[0] = (char)stream.GetC();
7702 str[1] = (char)stream.GetC();
7703
7704 m_data[i] = (unsigned char)wxHexToDec(str);
7705 }
7706
7707 m_dataSize = dataSize;
7708 m_imageType = imageType;
7709
7710 return true;
7711 }
7712
7713 // Allocate and read from stream as a block of memory
7714 unsigned 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
7725 unsigned 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
7735 bool 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
7743 bool wxRichTextImageBlock::WriteBlock(const wxString& filename, unsigned char* block, size_t size)
7744 {
7745 wxFileOutputStream outStream(filename);
7746 if (!outStream.Ok())
7747 return false;
7748
7749 return WriteBlock(outStream, block, size);
7750 }
7751
7752 // Gets the extension for the block's type
7753 wxString wxRichTextImageBlock::GetExtension() const
7754 {
7755 wxImageHandler* handler = wxImage::FindHandler(GetImageType());
7756 if (handler)
7757 return handler->GetExtension();
7758 else
7759 return wxEmptyString;
7760 }
7761
7762 #if wxUSE_DATAOBJ
7763
7764 /*!
7765 * The data object for a wxRichTextBuffer
7766 */
7767
7768 const wxChar *wxRichTextBufferDataObject::ms_richTextBufferFormatId = wxT("wxShape");
7769
7770 wxRichTextBufferDataObject::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
7781 wxRichTextBufferDataObject::~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!
7788 wxRichTextBuffer* wxRichTextBufferDataObject::GetRichTextBuffer()
7789 {
7790 wxRichTextBuffer* richTextBuffer = m_richTextBuffer;
7791 m_richTextBuffer = NULL;
7792
7793 return richTextBuffer;
7794 }
7795
7796 wxDataFormat wxRichTextBufferDataObject::GetPreferredFormat(Direction WXUNUSED(dir)) const
7797 {
7798 return m_formatRichTextBuffer;
7799 }
7800
7801 size_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
7825 bool 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
7855 bool wxRichTextBufferDataObject::SetData(size_t WXUNUSED(len), const void *buf)
7856 {
7857 wxDELETE(m_richTextBuffer);
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
7868 wxDELETE(m_richTextBuffer);
7869
7870 return false;
7871 }
7872 return true;
7873 }
7874
7875 #endif
7876 // wxUSE_DATAOBJ
7877
7878
7879 /*
7880 * wxRichTextFontTable
7881 * Manages quick access to a pool of fonts for rendering rich text
7882 */
7883
7884 WX_DECLARE_STRING_HASH_MAP_WITH_DECL(wxFont, wxRichTextFontTableHashMap, class WXDLLIMPEXP_RICHTEXT);
7885
7886 class wxRichTextFontTableData: public wxObjectRefData
7887 {
7888 public:
7889 wxRichTextFontTableData() {}
7890
7891 wxFont FindFont(const wxRichTextAttr& fontSpec);
7892
7893 wxRichTextFontTableHashMap m_hashMap;
7894 };
7895
7896 wxFont wxRichTextFontTableData::FindFont(const wxRichTextAttr& fontSpec)
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
7914 IMPLEMENT_DYNAMIC_CLASS(wxRichTextFontTable, wxObject)
7915
7916 wxRichTextFontTable::wxRichTextFontTable()
7917 {
7918 m_refData = new wxRichTextFontTableData;
7919 }
7920
7921 wxRichTextFontTable::wxRichTextFontTable(const wxRichTextFontTable& table)
7922 : wxObject()
7923 {
7924 (*this) = table;
7925 }
7926
7927 wxRichTextFontTable::~wxRichTextFontTable()
7928 {
7929 UnRef();
7930 }
7931
7932 bool wxRichTextFontTable::operator == (const wxRichTextFontTable& table) const
7933 {
7934 return (m_refData == table.m_refData);
7935 }
7936
7937 void wxRichTextFontTable::operator= (const wxRichTextFontTable& table)
7938 {
7939 Ref(table);
7940 }
7941
7942 wxFont wxRichTextFontTable::FindFont(const wxRichTextAttr& fontSpec)
7943 {
7944 wxRichTextFontTableData* data = (wxRichTextFontTableData*) m_refData;
7945 if (data)
7946 return data->FindFont(fontSpec);
7947 else
7948 return wxFont();
7949 }
7950
7951 void wxRichTextFontTable::Clear()
7952 {
7953 wxRichTextFontTableData* data = (wxRichTextFontTableData*) m_refData;
7954 if (data)
7955 data->m_hashMap.clear();
7956 }
7957
7958 // wxTextBoxAttr
7959
7960
7961 void 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
7980 bool 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
8001 bool 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.
8043 bool 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
8077 bool 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.
8105 void 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
8177 void wxRichTextAttr::Copy(const wxRichTextAttr& attr)
8178 {
8179 wxTextAttr::Copy(attr);
8180
8181 m_textBoxAttr = attr.m_textBoxAttr;
8182 }
8183
8184 bool 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
8193 bool 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.
8204 bool 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
8212 bool 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.
8221 void 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
8229 bool 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
8244 bool 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
8266 bool 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.
8280 void 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
8324 bool 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
8331 bool 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
8341 bool 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.
8352 void 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
8361 void 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
8370 void 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
8378 void 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
8387 void 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
8396 bool wxTextAttrDimension::EqPartial(const wxTextAttrDimension& dim) const
8397 {
8398 if (dim.IsPresent() && IsPresent() && !((*this) == dim))
8399 return false;
8400 else
8401 return true;
8402 }
8403
8404 bool 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.
8417 void 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
8440 bool 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
8458 bool 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
8469 bool 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.
8485 void 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.
8495 void 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
8916 #endif
8917 // wxUSE_RICHTEXT