+ node = node->GetNext();
+ }
+ }
+ else
+ {
+ wxRichTextObjectList::compatibility_iterator node = m_children.GetLast();
+ while (node)
+ {
+ wxRichTextObject* obj = node->GetData();
+ if (!obj->GetRange().IsOutside(range))
+ {
+ wxRichTextPlainText* textObj = wxDynamicCast(obj, wxRichTextPlainText);
+ if (textObj)
+ {
+ text = textObj->GetTextForRange(range) + text;
+ }
+ else
+ {
+ text = wxT(" ") + text;
+ }
+ }
+
+ node = node->GetPrevious();
+ }
+ }
+
+ return true;
+}
+
+/// Find a suitable wrap position.
+bool wxRichTextParagraph::FindWrapPosition(const wxRichTextRange& range, wxDC& dc, wxRichTextDrawingContext& context, int availableSpace, long& wrapPosition, wxArrayInt* partialExtents)
+{
+ if (range.GetLength() <= 0)
+ return false;
+
+ // Find the first position where the line exceeds the available space.
+ wxSize sz;
+ long breakPosition = range.GetEnd();
+
+#if wxRICHTEXT_USE_PARTIAL_TEXT_EXTENTS
+ if (partialExtents && partialExtents->GetCount() >= (size_t) (GetRange().GetLength()-1)) // the final position in a paragraph is the newline
+ {
+ int widthBefore;
+
+ if (range.GetStart() > GetRange().GetStart())
+ widthBefore = (*partialExtents)[range.GetStart() - GetRange().GetStart() - 1];
+ else
+ widthBefore = 0;
+
+ size_t i;
+ for (i = (size_t) range.GetStart(); i <= (size_t) range.GetEnd(); i++)
+ {
+ int widthFromStartOfThisRange = (*partialExtents)[i - GetRange().GetStart()] - widthBefore;
+
+ if (widthFromStartOfThisRange > availableSpace)
+ {
+ breakPosition = i-1;
+ break;
+ }
+ }
+ }
+ else
+#endif
+ {
+ // Binary chop for speed
+ long minPos = range.GetStart();
+ long maxPos = range.GetEnd();
+ while (true)
+ {
+ if (minPos == maxPos)
+ {
+ int descent = 0;
+ GetRangeSize(wxRichTextRange(range.GetStart(), minPos), sz, descent, dc, context, wxRICHTEXT_UNFORMATTED);
+
+ if (sz.x > availableSpace)
+ breakPosition = minPos - 1;
+ break;
+ }
+ else if ((maxPos - minPos) == 1)
+ {
+ int descent = 0;
+ GetRangeSize(wxRichTextRange(range.GetStart(), minPos), sz, descent, dc, context, wxRICHTEXT_UNFORMATTED);
+
+ if (sz.x > availableSpace)
+ breakPosition = minPos - 1;
+ else
+ {
+ GetRangeSize(wxRichTextRange(range.GetStart(), maxPos), sz, descent, dc, context, wxRICHTEXT_UNFORMATTED);
+ if (sz.x > availableSpace)
+ breakPosition = maxPos-1;
+ }
+ break;
+ }
+ else
+ {
+ long nextPos = minPos + ((maxPos - minPos) / 2);
+
+ int descent = 0;
+ GetRangeSize(wxRichTextRange(range.GetStart(), nextPos), sz, descent, dc, context, wxRICHTEXT_UNFORMATTED);
+
+ if (sz.x > availableSpace)
+ {
+ maxPos = nextPos;
+ }
+ else
+ {
+ minPos = nextPos;
+ }
+ }
+ }
+ }
+
+ // Now we know the last position on the line.
+ // Let's try to find a word break.
+
+ wxString plainText;
+ if (GetContiguousPlainText(plainText, wxRichTextRange(range.GetStart(), breakPosition), false))
+ {
+ int newLinePos = plainText.Find(wxRichTextLineBreakChar);
+ if (newLinePos != wxNOT_FOUND)
+ {
+ breakPosition = wxMax(0, range.GetStart() + newLinePos);
+ }
+ else
+ {
+ int spacePos = plainText.Find(wxT(' '), true);
+ int tabPos = plainText.Find(wxT('\t'), true);
+ int pos = wxMax(spacePos, tabPos);
+ if (pos != wxNOT_FOUND)
+ {
+ int positionsFromEndOfString = plainText.length() - pos - 1;
+ breakPosition = breakPosition - positionsFromEndOfString;
+ }
+ }
+ }
+
+ wrapPosition = breakPosition;
+
+ return true;
+}
+
+/// Get the bullet text for this paragraph.
+wxString wxRichTextParagraph::GetBulletText()
+{
+ if (GetAttributes().GetBulletStyle() == wxTEXT_ATTR_BULLET_STYLE_NONE ||
+ (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP))
+ return wxEmptyString;
+
+ int number = GetAttributes().GetBulletNumber();
+
+ wxString text;
+ if ((GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ARABIC) || (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE))
+ {
+ text.Printf(wxT("%d"), number);
+ }
+ else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER)
+ {
+ // TODO: Unicode, and also check if number > 26
+ text.Printf(wxT("%c"), (wxChar) (number+64));
+ }
+ else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER)
+ {
+ // TODO: Unicode, and also check if number > 26
+ text.Printf(wxT("%c"), (wxChar) (number+96));
+ }
+ else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER)
+ {
+ text = wxRichTextDecimalToRoman(number);
+ }
+ else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER)
+ {
+ text = wxRichTextDecimalToRoman(number);
+ text.MakeLower();
+ }
+ else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL)
+ {
+ text = GetAttributes().GetBulletText();
+ }
+
+ if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE)
+ {
+ // The outline style relies on the text being computed statically,
+ // since it depends on other levels points (e.g. 1.2.1.1). So normally the bullet text
+ // should be stored in the attributes; if not, just use the number for this
+ // level, as previously computed.
+ if (!GetAttributes().GetBulletText().IsEmpty())
+ text = GetAttributes().GetBulletText();
+ }
+
+ if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PARENTHESES)
+ {
+ text = wxT("(") + text + wxT(")");
+ }
+ else if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS)
+ {
+ text = text + wxT(")");
+ }
+
+ if (GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PERIOD)
+ {
+ text += wxT(".");
+ }
+
+ return text;
+}
+
+/// Allocate or reuse a line object
+wxRichTextLine* wxRichTextParagraph::AllocateLine(int pos)
+{
+ if (pos < (int) m_cachedLines.GetCount())
+ {
+ wxRichTextLine* line = m_cachedLines.Item(pos)->GetData();
+ line->Init(this);
+ return line;
+ }
+ else
+ {
+ wxRichTextLine* line = new wxRichTextLine(this);
+ m_cachedLines.Append(line);
+ return line;
+ }
+}
+
+/// Clear remaining unused line objects, if any
+bool wxRichTextParagraph::ClearUnusedLines(int lineCount)
+{
+ int cachedLineCount = m_cachedLines.GetCount();
+ if ((int) cachedLineCount > lineCount)
+ {
+ for (int i = 0; i < (int) (cachedLineCount - lineCount); i ++)
+ {
+ wxRichTextLineList::compatibility_iterator node = m_cachedLines.GetLast();
+ wxRichTextLine* line = node->GetData();
+ m_cachedLines.Erase(node);
+ delete line;
+ }
+ }
+ return true;
+}
+
+/// Get combined attributes of the base style, paragraph style and character style. We use this to dynamically
+/// retrieve the actual style.
+wxRichTextAttr wxRichTextParagraph::GetCombinedAttributes(const wxRichTextAttr& contentStyle, bool includingBoxAttr) const
+{
+ wxRichTextAttr attr;
+ wxRichTextParagraphLayoutBox* buf = wxDynamicCast(GetParent(), wxRichTextParagraphLayoutBox);
+ if (buf)
+ {
+ attr = buf->GetBasicStyle();
+ if (!includingBoxAttr)
+ {
+ attr.GetTextBoxAttr().Reset();
+ // The background colour will be painted by the container, and we don't
+ // want to unnecessarily overwrite the background when we're drawing text
+ // because this may erase the guideline (which appears just under the text
+ // if there's no padding).
+ attr.SetFlags(attr.GetFlags() & ~wxTEXT_ATTR_BACKGROUND_COLOUR);
+ }
+ wxRichTextApplyStyle(attr, GetAttributes());
+ }
+ else
+ attr = GetAttributes();
+
+ wxRichTextApplyStyle(attr, contentStyle);
+ return attr;
+}
+
+/// Get combined attributes of the base style and paragraph style.
+wxRichTextAttr wxRichTextParagraph::GetCombinedAttributes(bool includingBoxAttr) const
+{
+ wxRichTextAttr attr;
+ wxRichTextParagraphLayoutBox* buf = wxDynamicCast(GetParent(), wxRichTextParagraphLayoutBox);
+ if (buf)
+ {
+ attr = buf->GetBasicStyle();
+ if (!includingBoxAttr)
+ attr.GetTextBoxAttr().Reset();
+ wxRichTextApplyStyle(attr, GetAttributes());
+ }
+ else
+ attr = GetAttributes();
+
+ return attr;
+}
+
+// Create default tabstop array
+void wxRichTextParagraph::InitDefaultTabs()
+{
+ // create a default tab list at 10 mm each.
+ for (int i = 0; i < 20; ++i)
+ {
+ sm_defaultTabs.Add(i*100);
+ }
+}
+
+// Clear default tabstop array
+void wxRichTextParagraph::ClearDefaultTabs()
+{
+ sm_defaultTabs.Clear();
+}
+
+void wxRichTextParagraph::LayoutFloat(wxDC& dc, wxRichTextDrawingContext& context, const wxRect& rect, const wxRect& parentRect, int style, wxRichTextFloatCollector* floatCollector)
+{
+ wxRichTextObjectList::compatibility_iterator node = GetChildren().GetFirst();
+ while (node)
+ {
+ wxRichTextObject* anchored = node->GetData();
+ if (anchored && anchored->IsFloating() && !floatCollector->HasFloat(anchored))
+ {
+ int x = 0;
+ wxRichTextAttr parentAttr(GetAttributes());
+ context.ApplyVirtualAttributes(parentAttr, this);
+#if 1
+ // 27-09-2012
+ wxRect availableSpace = GetParent()->GetAvailableContentArea(dc, context, rect);
+
+ anchored->LayoutToBestSize(dc, context, GetBuffer(),
+ parentAttr, anchored->GetAttributes(),
+ parentRect, availableSpace,
+ style);
+ wxSize size = anchored->GetCachedSize();
+#else
+ wxSize size;
+ int descent = 0;
+ anchored->GetRangeSize(anchored->GetRange(), size, descent, dc, context, style);
+#endif
+
+ int offsetY = 0;
+ if (anchored->GetAttributes().GetTextBoxAttr().GetTop().IsValid())
+ {
+ offsetY = anchored->GetAttributes().GetTextBoxAttr().GetTop().GetValue();
+ if (anchored->GetAttributes().GetTextBoxAttr().GetTop().GetUnits() == wxTEXT_ATTR_UNITS_TENTHS_MM)
+ {
+ offsetY = ConvertTenthsMMToPixels(dc, offsetY);
+ }
+ }
+
+ int pos = floatCollector->GetFitPosition(anchored->GetAttributes().GetTextBoxAttr().GetFloatMode(), rect.y + offsetY, size.y);
+
+ /* Update the offset */
+ int newOffsetY = pos - rect.y;
+ if (newOffsetY != offsetY)
+ {
+ if (anchored->GetAttributes().GetTextBoxAttr().GetTop().GetUnits() == wxTEXT_ATTR_UNITS_TENTHS_MM)
+ newOffsetY = ConvertPixelsToTenthsMM(dc, newOffsetY);
+ anchored->GetAttributes().GetTextBoxAttr().GetTop().SetValue(newOffsetY);
+ }
+
+ if (anchored->GetAttributes().GetTextBoxAttr().GetFloatMode() == wxTEXT_BOX_ATTR_FLOAT_LEFT)
+ x = rect.x;
+ else if (anchored->GetAttributes().GetTextBoxAttr().GetFloatMode() == wxTEXT_BOX_ATTR_FLOAT_RIGHT)
+ x = rect.x + rect.width - size.x;
+
+ //anchored->SetPosition(wxPoint(x, pos));
+ anchored->Move(wxPoint(x, pos)); // should move children
+ anchored->SetCachedSize(size);
+ floatCollector->CollectFloat(this, anchored);
+ }
+
+ node = node->GetNext();
+ }
+}
+
+// Get the first position from pos that has a line break character.
+long wxRichTextParagraph::GetFirstLineBreakPosition(long pos)
+{
+ wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
+ while (node)
+ {
+ wxRichTextObject* obj = node->GetData();
+ if (pos >= obj->GetRange().GetStart() && pos <= obj->GetRange().GetEnd())
+ {
+ wxRichTextPlainText* textObj = wxDynamicCast(obj, wxRichTextPlainText);
+ if (textObj)
+ {
+ long breakPos = textObj->GetFirstLineBreakPosition(pos);
+ if (breakPos > -1)
+ return breakPos;
+ }
+ }
+ node = node->GetNext();
+ }
+ return -1;
+}
+
+/*!
+ * wxRichTextLine
+ * This object represents a line in a paragraph, and stores
+ * offsets from the start of the paragraph representing the
+ * start and end positions of the line.
+ */
+
+wxRichTextLine::wxRichTextLine(wxRichTextParagraph* parent)
+{
+ Init(parent);
+}
+
+/// Initialisation
+void wxRichTextLine::Init(wxRichTextParagraph* parent)
+{
+ m_parent = parent;
+ m_range.SetRange(-1, -1);
+ m_pos = wxPoint(0, 0);
+ m_size = wxSize(0, 0);
+ m_descent = 0;
+#if wxRICHTEXT_USE_OPTIMIZED_LINE_DRAWING
+ m_objectSizes.Clear();
+#endif
+}
+
+/// Copy
+void wxRichTextLine::Copy(const wxRichTextLine& obj)
+{
+ m_range = obj.m_range;
+#if wxRICHTEXT_USE_OPTIMIZED_LINE_DRAWING
+ m_objectSizes = obj.m_objectSizes;
+#endif
+}
+
+/// Get the absolute object position
+wxPoint wxRichTextLine::GetAbsolutePosition() const
+{
+ return m_parent->GetPosition() + m_pos;
+}
+
+/// Get the absolute range
+wxRichTextRange wxRichTextLine::GetAbsoluteRange() const
+{
+ wxRichTextRange range(m_range.GetStart() + m_parent->GetRange().GetStart(), 0);
+ range.SetEnd(range.GetStart() + m_range.GetLength()-1);
+ return range;
+}
+
+/*!
+ * wxRichTextPlainText
+ * This object represents a single piece of text.
+ */
+
+IMPLEMENT_DYNAMIC_CLASS(wxRichTextPlainText, wxRichTextObject)
+
+wxRichTextPlainText::wxRichTextPlainText(const wxString& text, wxRichTextObject* parent, wxRichTextAttr* style):
+ wxRichTextObject(parent)
+{
+ if (style)
+ SetAttributes(*style);
+
+ m_text = text;
+}
+
+#define USE_KERNING_FIX 1
+
+// If insufficient tabs are defined, this is the tab width used
+#define WIDTH_FOR_DEFAULT_TABS 50
+
+/// Draw the item
+bool wxRichTextPlainText::Draw(wxDC& dc, wxRichTextDrawingContext& context, const wxRichTextRange& range, const wxRichTextSelection& selection, const wxRect& rect, int descent, int WXUNUSED(style))
+{
+ wxRichTextParagraph* para = wxDynamicCast(GetParent(), wxRichTextParagraph);
+ wxASSERT (para != NULL);
+
+ wxRichTextAttr textAttr(para ? para->GetCombinedAttributes(GetAttributes(), false /* no box attributes */) : GetAttributes());
+ context.ApplyVirtualAttributes(textAttr, this);
+
+ // Let's make the assumption for now that for content in a paragraph, including
+ // text, we never have a discontinuous selection. So we only deal with a
+ // single range.
+ wxRichTextRange selectionRange;
+ if (selection.IsValid())
+ {
+ wxRichTextRangeArray selectionRanges = selection.GetSelectionForObject(this);
+ if (selectionRanges.GetCount() > 0)
+ selectionRange = selectionRanges[0];
+ else
+ selectionRange = wxRICHTEXT_NO_SELECTION;
+ }
+ else
+ selectionRange = wxRICHTEXT_NO_SELECTION;
+
+ int offset = GetRange().GetStart();
+
+ wxString str = m_text;
+ if (context.HasVirtualText(this))
+ {
+ if (!context.GetVirtualText(this, str) || str.Length() != m_text.Length())
+ str = m_text;
+ }
+
+ // Replace line break characters with spaces
+ wxString toRemove = wxRichTextLineBreakChar;
+ str.Replace(toRemove, wxT(" "));
+ if (textAttr.HasTextEffects() && (textAttr.GetTextEffects() & (wxTEXT_ATTR_EFFECT_CAPITALS|wxTEXT_ATTR_EFFECT_SMALL_CAPITALS)))
+ str.MakeUpper();
+
+ long len = range.GetLength();
+ wxString stringChunk = str.Mid(range.GetStart() - offset, (size_t) len);
+
+ // Test for the optimized situations where all is selected, or none
+ // is selected.
+
+ wxFont textFont(GetBuffer()->GetFontTable().FindFont(textAttr));
+ wxCheckSetFont(dc, textFont);
+ int charHeight = dc.GetCharHeight();
+
+ int x, y;
+ if ( textFont.IsOk() )
+ {
+ if (textAttr.HasTextEffects() && (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_SMALL_CAPITALS))
+ {
+ textFont.SetPointSize((int) (textFont.GetPointSize()*0.75));
+ wxCheckSetFont(dc, textFont);
+ charHeight = dc.GetCharHeight();
+ }
+
+ if ( textAttr.HasTextEffects() && (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUPERSCRIPT) )
+ {
+ if (textFont.IsUsingSizeInPixels())
+ {
+ double size = static_cast<double>(textFont.GetPixelSize().y) / wxSCRIPT_MUL_FACTOR;
+ textFont.SetPixelSize(wxSize(0, static_cast<int>(size)));
+ x = rect.x;
+ y = rect.y;
+ }
+ else
+ {
+ double size = static_cast<double>(textFont.GetPointSize()) / wxSCRIPT_MUL_FACTOR;
+ textFont.SetPointSize(static_cast<int>(size));
+ x = rect.x;
+ y = rect.y;
+ }
+ wxCheckSetFont(dc, textFont);
+ }
+ else if ( textAttr.HasTextEffects() && (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUBSCRIPT) )
+ {
+ if (textFont.IsUsingSizeInPixels())
+ {
+ double size = static_cast<double>(textFont.GetPixelSize().y) / wxSCRIPT_MUL_FACTOR;
+ textFont.SetPixelSize(wxSize(0, static_cast<int>(size)));
+ x = rect.x;
+ int sub_height = static_cast<int>(static_cast<double>(charHeight) / wxSCRIPT_MUL_FACTOR);
+ y = rect.y + (rect.height - sub_height + (descent - m_descent));
+ }
+ else
+ {
+ double size = static_cast<double>(textFont.GetPointSize()) / wxSCRIPT_MUL_FACTOR;
+ textFont.SetPointSize(static_cast<int>(size));
+ x = rect.x;
+ int sub_height = static_cast<int>(static_cast<double>(charHeight) / wxSCRIPT_MUL_FACTOR);
+ y = rect.y + (rect.height - sub_height + (descent - m_descent));
+ }
+ wxCheckSetFont(dc, textFont);
+ }
+ else
+ {
+ x = rect.x;
+ y = rect.y + (rect.height - charHeight - (descent - m_descent));
+ }
+ }
+ else
+ {
+ x = rect.x;
+ y = rect.y + (rect.height - charHeight - (descent - m_descent));
+ }
+
+ // TODO: new selection code
+
+ // (a) All selected.
+ if (selectionRange.GetStart() <= range.GetStart() && selectionRange.GetEnd() >= range.GetEnd())
+ {
+ DrawTabbedString(dc, textAttr, rect, stringChunk, x, y, true);
+ }
+ // (b) None selected.
+ else if (selectionRange.GetEnd() < range.GetStart() || selectionRange.GetStart() > range.GetEnd())
+ {
+ // Draw all unselected
+ DrawTabbedString(dc, textAttr, rect, stringChunk, x, y, false);
+ }
+ else
+ {
+ // (c) Part selected, part not
+ // Let's draw unselected chunk, selected chunk, then unselected chunk.
+
+ dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT);
+
+ // 1. Initial unselected chunk, if any, up until start of selection.
+ if (selectionRange.GetStart() > range.GetStart() && selectionRange.GetStart() <= range.GetEnd())
+ {
+ int r1 = range.GetStart();
+ int s1 = selectionRange.GetStart()-1;
+ int fragmentLen = s1 - r1 + 1;
+ if (fragmentLen < 0)
+ {
+ wxLogDebug(wxT("Mid(%d, %d"), (int)(r1 - offset), (int)fragmentLen);
+ }
+ wxString stringFragment = str.Mid(r1 - offset, fragmentLen);
+
+ DrawTabbedString(dc, textAttr, rect, stringFragment, x, y, false);
+
+#if USE_KERNING_FIX
+ if (stringChunk.Find(wxT("\t")) == wxNOT_FOUND)
+ {
+ // Compensate for kerning difference
+ wxString stringFragment2(str.Mid(r1 - offset, fragmentLen+1));
+ wxString stringFragment3(str.Mid(r1 - offset + fragmentLen, 1));
+
+ wxCoord w1, h1, w2, h2, w3, h3;
+ dc.GetTextExtent(stringFragment, & w1, & h1);
+ dc.GetTextExtent(stringFragment2, & w2, & h2);
+ dc.GetTextExtent(stringFragment3, & w3, & h3);
+
+ int kerningDiff = (w1 + w3) - w2;
+ x = x - kerningDiff;
+ }
+#endif
+ }
+
+ // 2. Selected chunk, if any.
+ if (selectionRange.GetEnd() >= range.GetStart())
+ {
+ int s1 = wxMax(selectionRange.GetStart(), range.GetStart());
+ int s2 = wxMin(selectionRange.GetEnd(), range.GetEnd());
+
+ int fragmentLen = s2 - s1 + 1;
+ if (fragmentLen < 0)
+ {
+ wxLogDebug(wxT("Mid(%d, %d"), (int)(s1 - offset), (int)fragmentLen);
+ }
+ wxString stringFragment = str.Mid(s1 - offset, fragmentLen);
+
+ DrawTabbedString(dc, textAttr, rect, stringFragment, x, y, true);
+
+#if USE_KERNING_FIX
+ if (stringChunk.Find(wxT("\t")) == wxNOT_FOUND)
+ {
+ // Compensate for kerning difference
+ wxString stringFragment2(str.Mid(s1 - offset, fragmentLen+1));
+ wxString stringFragment3(str.Mid(s1 - offset + fragmentLen, 1));
+
+ wxCoord w1, h1, w2, h2, w3, h3;
+ dc.GetTextExtent(stringFragment, & w1, & h1);
+ dc.GetTextExtent(stringFragment2, & w2, & h2);
+ dc.GetTextExtent(stringFragment3, & w3, & h3);
+
+ int kerningDiff = (w1 + w3) - w2;
+ x = x - kerningDiff;
+ }
+#endif
+ }
+
+ // 3. Remaining unselected chunk, if any
+ if (selectionRange.GetEnd() < range.GetEnd())
+ {
+ int s2 = wxMin(selectionRange.GetEnd()+1, range.GetEnd());
+ int r2 = range.GetEnd();
+
+ int fragmentLen = r2 - s2 + 1;
+ if (fragmentLen < 0)
+ {
+ wxLogDebug(wxT("Mid(%d, %d"), (int)(s2 - offset), (int)fragmentLen);
+ }
+ wxString stringFragment = str.Mid(s2 - offset, fragmentLen);
+
+ DrawTabbedString(dc, textAttr, rect, stringFragment, x, y, false);
+ }
+ }
+
+ return true;
+}
+
+bool wxRichTextPlainText::DrawTabbedString(wxDC& dc, const wxRichTextAttr& attr, const wxRect& rect,wxString& str, wxCoord& x, wxCoord& y, bool selected)
+{
+ bool hasTabs = (str.Find(wxT('\t')) != wxNOT_FOUND);
+
+ wxArrayInt tabArray;
+ int tabCount;
+ if (hasTabs)
+ {
+ if (attr.GetTabs().IsEmpty())
+ tabArray = wxRichTextParagraph::GetDefaultTabs();
+ else
+ tabArray = attr.GetTabs();
+ tabCount = tabArray.GetCount();
+
+ for (int i = 0; i < tabCount; ++i)
+ {
+ int pos = tabArray[i];
+ pos = ConvertTenthsMMToPixels(dc, pos);
+ tabArray[i] = pos;
+ }
+ }
+ else
+ tabCount = 0;
+
+ int nextTabPos = -1;
+ int tabPos = -1;
+ wxCoord w, h;
+
+ if (selected)
+ {
+ wxColour highlightColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT));
+ wxColour highlightTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT));
+
+ wxCheckSetBrush(dc, wxBrush(highlightColour));
+ wxCheckSetPen(dc, wxPen(highlightColour));
+ dc.SetTextForeground(highlightTextColour);
+ dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT);
+ }
+ else
+ {
+ dc.SetTextForeground(attr.GetTextColour());
+
+ if (attr.HasFlag(wxTEXT_ATTR_BACKGROUND_COLOUR) && attr.GetBackgroundColour().IsOk())
+ {
+ dc.SetBackgroundMode(wxBRUSHSTYLE_SOLID);
+ dc.SetTextBackground(attr.GetBackgroundColour());
+ }
+ else
+ dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT);
+ }
+
+ wxCoord x_orig = GetParent()->GetPosition().x;
+ while (hasTabs)
+ {
+ // the string has a tab
+ // break up the string at the Tab
+ wxString stringChunk = str.BeforeFirst(wxT('\t'));
+ str = str.AfterFirst(wxT('\t'));
+ dc.GetTextExtent(stringChunk, & w, & h);
+ tabPos = x + w;
+ bool not_found = true;
+ for (int i = 0; i < tabCount && not_found; ++i)
+ {
+ nextTabPos = tabArray.Item(i) + x_orig;
+
+ // Find the next tab position.
+ // Even if we're at the end of the tab array, we must still draw the chunk.
+
+ if (nextTabPos > tabPos || (i == (tabCount - 1)))
+ {
+ if (nextTabPos <= tabPos)
+ {
+ int defaultTabWidth = ConvertTenthsMMToPixels(dc, WIDTH_FOR_DEFAULT_TABS);
+ nextTabPos = tabPos + defaultTabWidth;
+ }
+
+ not_found = false;
+ if (selected)
+ {
+ w = nextTabPos - x;
+ wxRect selRect(x, rect.y, w, rect.GetHeight());
+ dc.DrawRectangle(selRect);
+ }
+ dc.DrawText(stringChunk, x, y);
+
+ if (attr.HasTextEffects() && (attr.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH))
+ {
+ wxPen oldPen = dc.GetPen();
+ wxCheckSetPen(dc, wxPen(attr.GetTextColour(), 1));
+ dc.DrawLine(x, (int) (y+(h/2)+0.5), x+w, (int) (y+(h/2)+0.5));
+ wxCheckSetPen(dc, oldPen);
+ }
+
+ x = nextTabPos;
+ }
+ }
+ hasTabs = (str.Find(wxT('\t')) != wxNOT_FOUND);
+ }
+
+ if (!str.IsEmpty())
+ {
+ dc.GetTextExtent(str, & w, & h);
+ if (selected)
+ {
+ wxRect selRect(x, rect.y, w, rect.GetHeight());
+ dc.DrawRectangle(selRect);
+ }
+ dc.DrawText(str, x, y);
+
+ if (attr.HasTextEffects() && (attr.GetTextEffects() & wxTEXT_ATTR_EFFECT_STRIKETHROUGH))
+ {
+ wxPen oldPen = dc.GetPen();
+ wxCheckSetPen(dc, wxPen(attr.GetTextColour(), 1));
+ dc.DrawLine(x, (int) (y+(h/2)+0.5), x+w, (int) (y+(h/2)+0.5));
+ wxCheckSetPen(dc, oldPen);
+ }
+
+ x += w;
+ }
+
+ return true;
+}
+
+/// Lay the item out
+bool wxRichTextPlainText::Layout(wxDC& dc, wxRichTextDrawingContext& context, const wxRect& WXUNUSED(rect), const wxRect& WXUNUSED(parentRect), int WXUNUSED(style))
+{
+ // Only lay out if we haven't already cached the size
+ if (m_size.x == -1)
+ GetRangeSize(GetRange(), m_size, m_descent, dc, context, 0, wxPoint(0, 0));
+ m_maxSize = m_size;
+ // Eventually we want to have a reasonable estimate of minimum size.
+ m_minSize = wxSize(0, 0);
+ return true;
+}
+
+/// Copy
+void wxRichTextPlainText::Copy(const wxRichTextPlainText& obj)
+{
+ wxRichTextObject::Copy(obj);
+
+ m_text = obj.m_text;
+}
+
+/// Get/set the object size for the given range. Returns false if the range
+/// is invalid for this object.
+bool wxRichTextPlainText::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, wxRichTextDrawingContext& context, int WXUNUSED(flags), const wxPoint& position, const wxSize& WXUNUSED(parentSize), wxArrayInt* partialExtents) const
+{
+ if (!range.IsWithin(GetRange()))
+ return false;
+
+ wxRichTextParagraph* para = wxDynamicCast(GetParent(), wxRichTextParagraph);
+ wxASSERT (para != NULL);
+
+ int relativeX = position.x - GetParent()->GetPosition().x;
+
+ wxRichTextAttr textAttr(para ? para->GetCombinedAttributes(GetAttributes()) : GetAttributes());
+ context.ApplyVirtualAttributes(textAttr, (wxRichTextObject*) this);
+
+ // Always assume unformatted text, since at this level we have no knowledge
+ // of line breaks - and we don't need it, since we'll calculate size within
+ // formatted text by doing it in chunks according to the line ranges
+
+ bool bScript(false);
+ wxFont font(GetBuffer()->GetFontTable().FindFont(textAttr));
+ if (font.IsOk())
+ {
+ if ( textAttr.HasTextEffects() && ( (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUPERSCRIPT)
+ || (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUBSCRIPT) ) )
+ {
+ wxFont textFont = font;
+ if (textFont.IsUsingSizeInPixels())
+ {
+ double size = static_cast<double>(textFont.GetPixelSize().y) / wxSCRIPT_MUL_FACTOR;
+ textFont.SetPixelSize(wxSize(0, static_cast<int>(size)));
+ }
+ else
+ {
+ double size = static_cast<double>(textFont.GetPointSize()) / wxSCRIPT_MUL_FACTOR;
+ textFont.SetPointSize(static_cast<int>(size));
+ }
+ wxCheckSetFont(dc, textFont);
+ bScript = true;
+ }
+ else if (textAttr.HasTextEffects() && (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_SMALL_CAPITALS))
+ {
+ wxFont textFont = font;
+ textFont.SetPointSize((int) (textFont.GetPointSize()*0.75));
+ wxCheckSetFont(dc, textFont);
+ bScript = true;
+ }
+ else
+ {
+ wxCheckSetFont(dc, font);
+ }
+ }
+
+ bool haveDescent = false;
+ int startPos = range.GetStart() - GetRange().GetStart();
+ long len = range.GetLength();
+
+ wxString str(m_text);
+ if (context.HasVirtualText(this))
+ {
+ if (!context.GetVirtualText(this, str) || str.Length() != m_text.Length())
+ str = m_text;
+ }
+
+ wxString toReplace = wxRichTextLineBreakChar;
+ str.Replace(toReplace, wxT(" "));
+
+ wxString stringChunk = str.Mid(startPos, (size_t) len);
+
+ if (textAttr.HasTextEffects() && (textAttr.GetTextEffects() & (wxTEXT_ATTR_EFFECT_CAPITALS|wxTEXT_ATTR_EFFECT_SMALL_CAPITALS)))
+ stringChunk.MakeUpper();
+
+ wxCoord w, h;
+ int width = 0;
+ if (stringChunk.Find(wxT('\t')) != wxNOT_FOUND)
+ {
+ // the string has a tab
+ wxArrayInt tabArray;
+ if (textAttr.GetTabs().IsEmpty())
+ tabArray = wxRichTextParagraph::GetDefaultTabs();
+ else
+ tabArray = textAttr.GetTabs();
+
+ int tabCount = tabArray.GetCount();
+
+ for (int i = 0; i < tabCount; ++i)
+ {
+ int pos = tabArray[i];
+ pos = ((wxRichTextPlainText*) this)->ConvertTenthsMMToPixels(dc, pos);
+ tabArray[i] = pos;
+ }
+
+ int nextTabPos = -1;
+
+ while (stringChunk.Find(wxT('\t')) >= 0)
+ {
+ int absoluteWidth = 0;
+
+ // the string has a tab
+ // break up the string at the Tab
+ wxString stringFragment = stringChunk.BeforeFirst(wxT('\t'));
+ stringChunk = stringChunk.AfterFirst(wxT('\t'));
+
+ if (partialExtents)
+ {
+ int oldWidth;
+ if (partialExtents->GetCount() > 0)
+ oldWidth = (*partialExtents)[partialExtents->GetCount()-1];
+ else
+ oldWidth = 0;
+
+ // Add these partial extents
+ wxArrayInt p;
+ dc.GetPartialTextExtents(stringFragment, p);
+ size_t j;
+ for (j = 0; j < p.GetCount(); j++)
+ partialExtents->Add(oldWidth + p[j]);
+
+ if (partialExtents->GetCount() > 0)
+ absoluteWidth = (*partialExtents)[(*partialExtents).GetCount()-1] + relativeX;
+ else
+ absoluteWidth = relativeX;
+ }
+ else
+ {
+ dc.GetTextExtent(stringFragment, & w, & h);
+ width += w;
+ absoluteWidth = width + relativeX;
+ haveDescent = true;
+ }
+
+ bool notFound = true;
+ for (int i = 0; i < tabCount && notFound; ++i)
+ {
+ nextTabPos = tabArray.Item(i);
+
+ // Find the next tab position.
+ // Even if we're at the end of the tab array, we must still process the chunk.
+
+ if (nextTabPos > absoluteWidth || (i == (tabCount - 1)))
+ {
+ if (nextTabPos <= absoluteWidth)
+ {
+ int defaultTabWidth = ((wxRichTextPlainText*) this)->ConvertTenthsMMToPixels(dc, WIDTH_FOR_DEFAULT_TABS);
+ nextTabPos = absoluteWidth + defaultTabWidth;
+ }
+
+ notFound = false;
+ width = nextTabPos - relativeX;
+
+ if (partialExtents)
+ partialExtents->Add(width);
+ }
+ }
+ }
+ }
+
+ if (!stringChunk.IsEmpty())
+ {
+ if (partialExtents)
+ {
+ int oldWidth;
+ if (partialExtents->GetCount() > 0)
+ oldWidth = (*partialExtents)[partialExtents->GetCount()-1];
+ else
+ oldWidth = 0;
+
+ // Add these partial extents
+ wxArrayInt p;
+ dc.GetPartialTextExtents(stringChunk, p);
+ size_t j;
+ for (j = 0; j < p.GetCount(); j++)
+ partialExtents->Add(oldWidth + p[j]);
+ }
+ else
+ {
+ dc.GetTextExtent(stringChunk, & w, & h, & descent);
+ width += w;
+ haveDescent = true;
+ }
+ }
+
+ if (partialExtents)
+ {
+ int charHeight = dc.GetCharHeight();
+ if ((*partialExtents).GetCount() > 0)
+ w = (*partialExtents)[partialExtents->GetCount()-1];
+ else
+ w = 0;
+ size = wxSize(w, charHeight);
+ }
+ else
+ {
+ size = wxSize(width, dc.GetCharHeight());
+ }
+
+ if (!haveDescent)
+ dc.GetTextExtent(wxT("X"), & w, & h, & descent);
+
+ if ( bScript )
+ dc.SetFont(font);
+
+ return true;
+}
+
+/// Do a split, returning an object containing the second part, and setting
+/// the first part in 'this'.
+wxRichTextObject* wxRichTextPlainText::DoSplit(long pos)
+{
+ long index = pos - GetRange().GetStart();
+
+ if (index < 0 || index >= (int) m_text.length())
+ return NULL;
+
+ wxString firstPart = m_text.Mid(0, index);
+ wxString secondPart = m_text.Mid(index);
+
+ m_text = firstPart;
+
+ wxRichTextPlainText* newObject = new wxRichTextPlainText(secondPart);
+ newObject->SetAttributes(GetAttributes());
+ newObject->SetProperties(GetProperties());
+
+ newObject->SetRange(wxRichTextRange(pos, GetRange().GetEnd()));
+ GetRange().SetEnd(pos-1);
+
+ return newObject;
+}
+
+/// Calculate range
+void wxRichTextPlainText::CalculateRange(long start, long& end)
+{
+ end = start + m_text.length() - 1;
+ m_range.SetRange(start, end);
+}
+
+/// Delete range
+bool wxRichTextPlainText::DeleteRange(const wxRichTextRange& range)
+{
+ wxRichTextRange r = range;
+
+ r.LimitTo(GetRange());
+
+ if (r.GetStart() == GetRange().GetStart() && r.GetEnd() == GetRange().GetEnd())
+ {
+ m_text.Empty();
+ return true;
+ }
+
+ long startIndex = r.GetStart() - GetRange().GetStart();
+ long len = r.GetLength();
+
+ m_text = m_text.Mid(0, startIndex) + m_text.Mid(startIndex+len);
+ return true;
+}
+
+/// Get text for the given range.
+wxString wxRichTextPlainText::GetTextForRange(const wxRichTextRange& range) const
+{
+ wxRichTextRange r = range;
+
+ r.LimitTo(GetRange());
+
+ long startIndex = r.GetStart() - GetRange().GetStart();
+ long len = r.GetLength();
+
+ return m_text.Mid(startIndex, len);
+}
+
+/// Returns true if this object can merge itself with the given one.
+bool wxRichTextPlainText::CanMerge(wxRichTextObject* object, wxRichTextDrawingContext& context) const
+{
+ // JACS 2013-01-27
+ if (!context.GetVirtualAttributesEnabled())
+ {
+ return object->GetClassInfo() == wxCLASSINFO(wxRichTextPlainText) &&
+ (m_text.empty() || (wxTextAttrEq(GetAttributes(), object->GetAttributes()) && m_properties == object->GetProperties()));
+ }
+ else
+ {
+ wxRichTextPlainText* otherObj = wxDynamicCast(object, wxRichTextPlainText);
+ if (!otherObj || m_text.empty())
+ return false;
+
+ if (!wxTextAttrEq(GetAttributes(), object->GetAttributes()) || !(m_properties == object->GetProperties()))
+ return false;
+
+ // Check if differing virtual attributes makes it impossible to merge
+ // these strings.
+
+ bool hasVirtualAttr1 = context.HasVirtualAttributes((wxRichTextObject*) this);
+ bool hasVirtualAttr2 = context.HasVirtualAttributes((wxRichTextObject*) object);
+ if (!hasVirtualAttr1 && !hasVirtualAttr2)
+ return true;
+ else if (hasVirtualAttr1 != hasVirtualAttr2)
+ return false;
+ else
+ {
+ wxRichTextAttr virtualAttr1 = context.GetVirtualAttributes((wxRichTextObject*) this);
+ wxRichTextAttr virtualAttr2 = context.GetVirtualAttributes((wxRichTextObject*) object);
+ return virtualAttr1 == virtualAttr2;
+ }
+ }
+}
+
+/// Returns true if this object merged itself with the given one.
+/// The calling code will then delete the given object.
+bool wxRichTextPlainText::Merge(wxRichTextObject* object, wxRichTextDrawingContext& WXUNUSED(context))
+{
+ wxRichTextPlainText* textObject = wxDynamicCast(object, wxRichTextPlainText);
+ wxASSERT( textObject != NULL );
+
+ if (textObject)
+ {
+ m_text += textObject->GetText();
+ wxRichTextApplyStyle(m_attributes, textObject->GetAttributes());
+ return true;
+ }
+ else
+ return false;
+}
+
+bool wxRichTextPlainText::CanSplit(wxRichTextDrawingContext& context) const
+{
+ // If this object has any virtual attributes at all, whether for the whole object
+ // or individual ones, we should try splitting it by calling Split.
+ // Must be more than one character in order to be able to split.
+ return m_text.Length() > 1 && context.HasVirtualAttributes((wxRichTextObject*) this);
+}
+
+wxRichTextObject* wxRichTextPlainText::Split(wxRichTextDrawingContext& context)
+{
+ int count = context.GetVirtualSubobjectAttributesCount(this);
+ if (count > 0 && GetParent())
+ {
+ wxRichTextCompositeObject* parent = wxDynamicCast(GetParent(), wxRichTextCompositeObject);
+ wxRichTextObjectList::compatibility_iterator node = parent->GetChildren().Find(this);
+ if (node)
+ {
+ const wxRichTextAttr emptyAttr;
+ wxRichTextObjectList::compatibility_iterator next = node->GetNext();
+
+ wxArrayInt positions;
+ wxRichTextAttrArray attributes;
+ if (context.GetVirtualSubobjectAttributes(this, positions, attributes) && positions.GetCount() > 0)
+ {
+ wxASSERT(positions.GetCount() == attributes.GetCount());
+
+ // We will gather up runs of text with the same virtual attributes
+
+ int len = m_text.Length();
+ int i = 0;
+
+ // runStart and runEnd represent the accumulated run with a consistent attribute
+ // that hasn't yet been appended
+ int runStart = -1;
+ int runEnd = -1;
+ wxRichTextAttr currentAttr;
+ wxString text = m_text;
+ wxRichTextPlainText* lastPlainText = this;
+
+ for (i = 0; i < (int) positions.GetCount(); i++)
+ {
+ int pos = positions[i];
+ wxASSERT(pos >= 0 && pos < len);
+ if (pos >= 0 && pos < len)
+ {
+ const wxRichTextAttr& attr = attributes[i];
+
+ if (pos == 0)
+ {
+ runStart = 0;
+ currentAttr = attr;
+ }
+ // Check if there was a gap from the last known attribute and this.
+ // In that case, we need to do something with the span of non-attributed text.
+ else if ((pos-1) > runEnd)
+ {
+ if (runEnd == -1)
+ {
+ // We hadn't processed anything previously, so the previous run is from the text start
+ // to just before this position. The current attribute remains empty.
+ runStart = 0;
+ runEnd = pos-1;
+ }
+ else
+ {
+ // If the previous attribute matches the gap's attribute (i.e., no attributes)
+ // then just extend the run.
+ if (currentAttr.IsDefault())
+ {
+ runEnd = pos-1;
+ }
+ else
+ {
+ // We need to add an object, or reuse the existing one.
+ if (runStart == 0)
+ {
+ lastPlainText = this;
+ SetText(text.Mid(runStart, runEnd - runStart + 1));
+ }
+ else
+ {
+ wxRichTextPlainText* obj = new wxRichTextPlainText;
+ lastPlainText = obj;
+ obj->SetAttributes(GetAttributes());
+ obj->SetProperties(GetProperties());
+ obj->SetParent(parent);
+
+ obj->SetText(text.Mid(runStart, runEnd - runStart + 1));
+ if (next)
+ parent->GetChildren().Insert(next, obj);
+ else
+ parent->GetChildren().Append(obj);
+ }
+
+ runStart = runEnd+1;
+ runEnd = pos-1;
+
+ currentAttr = emptyAttr;
+ }
+ }
+ }
+
+ wxASSERT(runEnd == pos-1);
+
+ // Now we only have to deal with the previous run
+ if (currentAttr == attr)
+ {
+ // If we still have the same attributes, then we
+ // simply increase the run size.
+ runEnd = pos;
+ }
+ else
+ {
+ if (runEnd >= 0)
+ {
+ // We need to add an object, or reuse the existing one.
+ if (runStart == 0)
+ {
+ lastPlainText = this;
+ SetText(text.Mid(runStart, runEnd - runStart + 1));
+ }
+ else
+ {
+ wxRichTextPlainText* obj = new wxRichTextPlainText;
+ lastPlainText = obj;
+ obj->SetAttributes(GetAttributes());
+ obj->SetProperties(GetProperties());
+ obj->SetParent(parent);
+
+ obj->SetText(text.Mid(runStart, runEnd - runStart + 1));
+ if (next)
+ parent->GetChildren().Insert(next, obj);
+ else
+ parent->GetChildren().Append(obj);
+ }
+ }
+
+ runStart = pos;
+ runEnd = pos;
+
+ currentAttr = attr;
+ }
+ }
+ }
+
+ // We may still have a run to add, and possibly a no-attribute text fragment after that.
+ // If the whole string was already a single attribute (the run covers the whole string), don't split.
+ if ((runStart != -1) && !(runStart == 0 && runEnd == (len-1)))
+ {
+ // If the current attribute is empty, merge the run with the next fragment
+ // which by definition (because it's not specified) has empty attributes.
+ if (currentAttr.IsDefault())
+ runEnd = (len-1);
+
+ if (runEnd < (len-1))
+ {
+ // We need to add an object, or reuse the existing one.
+ if (runStart == 0)
+ {
+ lastPlainText = this;
+ SetText(text.Mid(runStart, runEnd - runStart + 1));
+ }
+ else
+ {
+ wxRichTextPlainText* obj = new wxRichTextPlainText;
+ lastPlainText = obj;
+ obj->SetAttributes(GetAttributes());
+ obj->SetProperties(GetProperties());
+ obj->SetParent(parent);
+
+ obj->SetText(text.Mid(runStart, runEnd - runStart + 1));
+ if (next)
+ parent->GetChildren().Insert(next, obj);
+ else
+ parent->GetChildren().Append(obj);
+ }
+
+ runStart = runEnd+1;
+ runEnd = (len-1);
+ }
+
+ // Now the last, non-attributed fragment at the end, if any
+ if ((runStart < len) && !(runStart == 0 && runEnd == (len-1)))
+ {
+ wxASSERT(runStart != 0);
+
+ wxRichTextPlainText* obj = new wxRichTextPlainText;
+ obj->SetAttributes(GetAttributes());
+ obj->SetProperties(GetProperties());
+ obj->SetParent(parent);
+
+ obj->SetText(text.Mid(runStart, runEnd - runStart + 1));
+ if (next)
+ parent->GetChildren().Insert(next, obj);
+ else
+ parent->GetChildren().Append(obj);
+
+ lastPlainText = obj;
+ }
+ }
+
+ return lastPlainText;
+ }
+ }
+ }
+ return this;
+}
+
+/// Dump to output stream for debugging
+void wxRichTextPlainText::Dump(wxTextOutputStream& stream)
+{
+ wxRichTextObject::Dump(stream);
+ stream << m_text << wxT("\n");
+}
+
+/// Get the first position from pos that has a line break character.
+long wxRichTextPlainText::GetFirstLineBreakPosition(long pos)
+{
+ int i;
+ int len = m_text.length();
+ int startPos = pos - m_range.GetStart();
+ for (i = startPos; i < len; i++)
+ {
+ wxChar ch = m_text[i];
+ if (ch == wxRichTextLineBreakChar)
+ {
+ return i + m_range.GetStart();
+ }
+ }
+ return -1;
+}
+
+/*!
+ * wxRichTextBuffer
+ * This is a kind of box, used to represent the whole buffer
+ */
+
+IMPLEMENT_DYNAMIC_CLASS(wxRichTextBuffer, wxRichTextParagraphLayoutBox)
+
+wxList wxRichTextBuffer::sm_handlers;
+wxList wxRichTextBuffer::sm_drawingHandlers;
+wxRichTextFieldTypeHashMap wxRichTextBuffer::sm_fieldTypes;
+wxRichTextRenderer* wxRichTextBuffer::sm_renderer = NULL;
+int wxRichTextBuffer::sm_bulletRightMargin = 20;
+float wxRichTextBuffer::sm_bulletProportion = (float) 0.3;
+bool wxRichTextBuffer::sm_floatingLayoutMode = true;
+
+/// Initialisation
+void wxRichTextBuffer::Init()
+{
+ m_commandProcessor = new wxCommandProcessor;
+ m_styleSheet = NULL;
+ m_modified = false;
+ m_batchedCommandDepth = 0;
+ m_batchedCommand = NULL;
+ m_suppressUndo = 0;
+ m_handlerFlags = 0;
+ m_scale = 1.0;
+ m_dimensionScale = 1.0;
+ m_fontScale = 1.0;
+ SetMargins(4);
+}
+
+/// Initialisation
+wxRichTextBuffer::~wxRichTextBuffer()
+{
+ delete m_commandProcessor;
+ delete m_batchedCommand;
+
+ ClearStyleStack();
+ ClearEventHandlers();
+}
+
+void wxRichTextBuffer::ResetAndClearCommands()
+{
+ Reset();
+
+ GetCommandProcessor()->ClearCommands();
+
+ Modify(false);
+ Invalidate(wxRICHTEXT_ALL);
+}
+
+void wxRichTextBuffer::Copy(const wxRichTextBuffer& obj)
+{
+ wxRichTextParagraphLayoutBox::Copy(obj);
+
+ m_styleSheet = obj.m_styleSheet;
+ m_modified = obj.m_modified;
+ m_batchedCommandDepth = 0;
+ if (m_batchedCommand)
+ delete m_batchedCommand;
+ m_batchedCommand = NULL;
+ m_suppressUndo = obj.m_suppressUndo;
+ m_invalidRange = obj.m_invalidRange;
+ m_dimensionScale = obj.m_dimensionScale;
+ m_fontScale = obj.m_fontScale;
+}
+
+/// Push style sheet to top of stack
+bool wxRichTextBuffer::PushStyleSheet(wxRichTextStyleSheet* styleSheet)
+{
+ if (m_styleSheet)
+ styleSheet->InsertSheet(m_styleSheet);
+
+ SetStyleSheet(styleSheet);
+
+ return true;
+}
+
+/// Pop style sheet from top of stack
+wxRichTextStyleSheet* wxRichTextBuffer::PopStyleSheet()
+{
+ if (m_styleSheet)
+ {
+ wxRichTextStyleSheet* oldSheet = m_styleSheet;
+ m_styleSheet = oldSheet->GetNextSheet();
+ oldSheet->Unlink();
+
+ return oldSheet;
+ }
+ else
+ return NULL;
+}
+
+/// Submit command to insert paragraphs
+bool wxRichTextBuffer::InsertParagraphsWithUndo(long pos, const wxRichTextParagraphLayoutBox& paragraphs, wxRichTextCtrl* ctrl, int flags)
+{
+ return ctrl->GetFocusObject()->InsertParagraphsWithUndo(this, pos, paragraphs, ctrl, flags);
+}
+
+/// Submit command to insert paragraphs
+bool wxRichTextParagraphLayoutBox::InsertParagraphsWithUndo(wxRichTextBuffer* buffer, long pos, const wxRichTextParagraphLayoutBox& paragraphs, wxRichTextCtrl* ctrl, int WXUNUSED(flags))
+{
+ wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Text"), wxRICHTEXT_INSERT, buffer, this, ctrl, false);
+
+ action->GetNewParagraphs() = paragraphs;
+
+ action->SetPosition(pos);
+
+ wxRichTextRange range = wxRichTextRange(pos, pos + paragraphs.GetOwnRange().GetEnd() - 1);
+ if (!paragraphs.GetPartialParagraph())
+ range.SetEnd(range.GetEnd()+1);
+
+ // Set the range we'll need to delete in Undo
+ action->SetRange(range);
+
+ buffer->SubmitAction(action);
+
+ return true;
+}
+
+/// Submit command to insert the given text
+bool wxRichTextBuffer::InsertTextWithUndo(long pos, const wxString& text, wxRichTextCtrl* ctrl, int flags)
+{
+ if (ctrl)
+ return ctrl->GetFocusObject()->InsertTextWithUndo(this, pos, text, ctrl, flags);
+ else
+ return wxRichTextParagraphLayoutBox::InsertTextWithUndo(this, pos, text, ctrl, flags);
+}
+
+/// Submit command to insert the given text
+bool wxRichTextParagraphLayoutBox::InsertTextWithUndo(wxRichTextBuffer* buffer, long pos, const wxString& text, wxRichTextCtrl* ctrl, int flags)
+{
+ wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Text"), wxRICHTEXT_INSERT, buffer, this, ctrl, false);
+
+ wxRichTextAttr* p = NULL;
+ wxRichTextAttr paraAttr;
+ if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
+ {
+ // Get appropriate paragraph style
+ paraAttr = GetStyleForNewParagraph(buffer, pos, false, false);
+ if (!paraAttr.IsDefault())
+ p = & paraAttr;
+ }
+
+ action->GetNewParagraphs().AddParagraphs(text, p);
+
+ int length = action->GetNewParagraphs().GetOwnRange().GetLength();
+
+ if (!text.empty() && text.Last() != wxT('\n'))
+ {
+ // Don't count the newline when undoing
+ length --;
+ action->GetNewParagraphs().SetPartialParagraph(true);
+ }
+ else if (!text.empty() && text.Last() == wxT('\n'))
+ length --;
+
+ action->SetPosition(pos);
+
+ // Set the range we'll need to delete in Undo
+ action->SetRange(wxRichTextRange(pos, pos + length - 1));
+
+ buffer->SubmitAction(action);
+
+ return true;
+}
+
+/// Submit command to insert the given text
+bool wxRichTextBuffer::InsertNewlineWithUndo(long pos, wxRichTextCtrl* ctrl, int flags)
+{
+ return ctrl->GetFocusObject()->InsertNewlineWithUndo(this, pos, ctrl, flags);
+}
+
+/// Submit command to insert the given text
+bool wxRichTextParagraphLayoutBox::InsertNewlineWithUndo(wxRichTextBuffer* buffer, long pos, wxRichTextCtrl* ctrl, int flags)
+{
+ wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Text"), wxRICHTEXT_INSERT, buffer, this, ctrl, false);
+
+ wxRichTextAttr* p = NULL;
+ wxRichTextAttr paraAttr;
+ if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
+ {
+ paraAttr = GetStyleForNewParagraph(buffer, pos, false, true /* look for next paragraph style */);
+ if (!paraAttr.IsDefault())
+ p = & paraAttr;
+ }
+
+ wxRichTextAttr attr(buffer->GetDefaultStyle());
+ // Don't include box attributes such as margins
+ attr.GetTextBoxAttr().Reset();
+
+ wxRichTextParagraph* newPara = new wxRichTextParagraph(wxEmptyString, this, & attr);
+ action->GetNewParagraphs().AppendChild(newPara);
+ action->GetNewParagraphs().UpdateRanges();
+ action->GetNewParagraphs().SetPartialParagraph(false);
+ wxRichTextParagraph* para = GetParagraphAtPosition(pos, false);
+ long pos1 = pos;
+
+ if (p)
+ newPara->SetAttributes(*p);
+
+ if (flags & wxRICHTEXT_INSERT_INTERACTIVE)
+ {
+ if (para && para->GetRange().GetEnd() == pos)
+ pos1 ++;
+
+ // Now see if we need to number the paragraph.
+ if (newPara->GetAttributes().HasBulletNumber())
+ {
+ wxRichTextAttr numberingAttr;
+ if (FindNextParagraphNumber(para, numberingAttr))
+ wxRichTextApplyStyle(newPara->GetAttributes(), (const wxRichTextAttr&) numberingAttr);
+ }
+ }
+
+ action->SetPosition(pos);
+
+ // Use the default character style
+ if (!buffer->GetDefaultStyle().IsDefault() && newPara->GetChildren().GetFirst())
+ {
+ // Check whether the default style merely reflects the paragraph/basic style,
+ // in which case don't apply it.
+ wxRichTextAttr defaultStyle(buffer->GetDefaultStyle());
+ defaultStyle.GetTextBoxAttr().Reset();
+ wxRichTextAttr toApply;
+ if (para)
+ {
+ wxRichTextAttr combinedAttr = para->GetCombinedAttributes(true /* include box attributes */);
+ wxRichTextAttr newAttr;
+ // This filters out attributes that are accounted for by the current
+ // paragraph/basic style
+ wxRichTextApplyStyle(toApply, defaultStyle, & combinedAttr);
+ }
+ else
+ toApply = defaultStyle;
+
+ if (!toApply.IsDefault())
+ newPara->GetChildren().GetFirst()->GetData()->SetAttributes(toApply);
+ }
+
+ // Set the range we'll need to delete in Undo
+ action->SetRange(wxRichTextRange(pos1, pos1));
+
+ buffer->SubmitAction(action);
+
+ return true;
+}
+
+/// Submit command to insert the given image
+bool wxRichTextBuffer::InsertImageWithUndo(long pos, const wxRichTextImageBlock& imageBlock, wxRichTextCtrl* ctrl, int flags,
+ const wxRichTextAttr& textAttr)
+{
+ return ctrl->GetFocusObject()->InsertImageWithUndo(this, pos, imageBlock, ctrl, flags, textAttr);
+}
+
+/// Submit command to insert the given image
+bool wxRichTextParagraphLayoutBox::InsertImageWithUndo(wxRichTextBuffer* buffer, long pos, const wxRichTextImageBlock& imageBlock,
+ wxRichTextCtrl* ctrl, int flags,
+ const wxRichTextAttr& textAttr)
+{
+ wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Image"), wxRICHTEXT_INSERT, buffer, this, ctrl, false);
+
+ wxRichTextAttr* p = NULL;
+ wxRichTextAttr paraAttr;
+ if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
+ {
+ paraAttr = GetStyleForNewParagraph(buffer, pos);
+ if (!paraAttr.IsDefault())
+ p = & paraAttr;
+ }
+
+ wxRichTextAttr attr(buffer->GetDefaultStyle());
+
+ // Don't include box attributes such as margins
+ attr.GetTextBoxAttr().Reset();
+
+ wxRichTextParagraph* newPara = new wxRichTextParagraph(this, & attr);
+ if (p)
+ newPara->SetAttributes(*p);
+
+ wxRichTextImage* imageObject = new wxRichTextImage(imageBlock, newPara);
+ newPara->AppendChild(imageObject);
+ imageObject->SetAttributes(textAttr);
+ action->GetNewParagraphs().AppendChild(newPara);
+ action->GetNewParagraphs().UpdateRanges();
+
+ action->GetNewParagraphs().SetPartialParagraph(true);
+
+ action->SetPosition(pos);
+
+ // Set the range we'll need to delete in Undo
+ action->SetRange(wxRichTextRange(pos, pos));
+
+ buffer->SubmitAction(action);
+
+ return true;
+}
+
+// Insert an object with no change of it
+wxRichTextObject* wxRichTextBuffer::InsertObjectWithUndo(long pos, wxRichTextObject *object, wxRichTextCtrl* ctrl, int flags)
+{
+ return ctrl->GetFocusObject()->InsertObjectWithUndo(this, pos, object, ctrl, flags);
+}
+
+// Insert an object with no change of it
+wxRichTextObject* wxRichTextParagraphLayoutBox::InsertObjectWithUndo(wxRichTextBuffer* buffer, long pos, wxRichTextObject *object, wxRichTextCtrl* ctrl, int flags)
+{
+ wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Object"), wxRICHTEXT_INSERT, buffer, this, ctrl, false);
+
+ wxRichTextAttr* p = NULL;
+ wxRichTextAttr paraAttr;
+ if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
+ {
+ paraAttr = GetStyleForNewParagraph(buffer, pos);
+ if (!paraAttr.IsDefault())
+ p = & paraAttr;
+ }
+
+ wxRichTextAttr attr(buffer->GetDefaultStyle());
+
+ // Don't include box attributes such as margins
+ attr.GetTextBoxAttr().Reset();
+
+ wxRichTextParagraph* newPara = new wxRichTextParagraph(this, & attr);
+ if (p)
+ newPara->SetAttributes(*p);
+
+ newPara->AppendChild(object);
+ action->GetNewParagraphs().AppendChild(newPara);
+ action->GetNewParagraphs().UpdateRanges();
+
+ action->GetNewParagraphs().SetPartialParagraph(true);
+
+ action->SetPosition(pos);
+
+ // Set the range we'll need to delete in Undo
+ action->SetRange(wxRichTextRange(pos, pos));
+
+ buffer->SubmitAction(action);
+
+ wxRichTextObject* obj = GetLeafObjectAtPosition(pos);
+ return obj;
+}
+
+wxRichTextField* wxRichTextParagraphLayoutBox::InsertFieldWithUndo(wxRichTextBuffer* buffer, long pos, const wxString& fieldType,
+ const wxRichTextProperties& properties,
+ wxRichTextCtrl* ctrl, int flags,
+ const wxRichTextAttr& textAttr)
+{
+ wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Field"), wxRICHTEXT_INSERT, buffer, this, ctrl, false);
+
+ wxRichTextAttr* p = NULL;
+ wxRichTextAttr paraAttr;
+ if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
+ {
+ paraAttr = GetStyleForNewParagraph(buffer, pos);
+ if (!paraAttr.IsDefault())
+ p = & paraAttr;
+ }
+
+ wxRichTextAttr attr(buffer->GetDefaultStyle());
+
+ // Don't include box attributes such as margins
+ attr.GetTextBoxAttr().Reset();
+
+ wxRichTextParagraph* newPara = new wxRichTextParagraph(this, & attr);
+ if (p)
+ newPara->SetAttributes(*p);
+
+ wxRichTextField* fieldObject = new wxRichTextField();
+ fieldObject->wxRichTextObject::SetProperties(properties);
+ fieldObject->SetFieldType(fieldType);
+ fieldObject->SetAttributes(textAttr);
+ newPara->AppendChild(fieldObject);
+ action->GetNewParagraphs().AppendChild(newPara);
+ action->GetNewParagraphs().UpdateRanges();
+ action->GetNewParagraphs().SetPartialParagraph(true);
+ action->SetPosition(pos);
+
+ // Set the range we'll need to delete in Undo
+ action->SetRange(wxRichTextRange(pos, pos));
+
+ buffer->SubmitAction(action);
+
+ wxRichTextField* obj = wxDynamicCast(GetLeafObjectAtPosition(pos), wxRichTextField);
+ return obj;
+}
+
+bool wxRichTextParagraphLayoutBox::SetObjectPropertiesWithUndo(wxRichTextObject& obj, const wxRichTextProperties& properties, wxRichTextObject* objToSet)
+{
+ wxRichTextBuffer* buffer = GetBuffer();
+ wxCHECK_MSG(buffer, false, wxT("Invalid buffer"));
+ wxRichTextCtrl* rtc = buffer->GetRichTextCtrl();
+ wxCHECK_MSG(rtc, false, wxT("Invalid rtc"));
+
+ wxRichTextAction* action = NULL;
+ wxRichTextObject* clone = NULL;
+
+ // The object on which to set properties will usually be 'obj', but use objToSet if it's valid.
+ // This is necessary e.g. on setting a wxRichTextCell's properties, when obj will be the parent table
+ if (objToSet == NULL)
+ objToSet = &obj;
+
+ if (rtc->SuppressingUndo())
+ objToSet->SetProperties(properties);
+ else
+ {
+ clone = obj.Clone();
+ objToSet->SetProperties(properties);
+
+ // The 'true' parameter in the next line says "Ignore first time"; otherwise the objects are prematurely switched
+ action = new wxRichTextAction(NULL, _("Change Properties"), wxRICHTEXT_CHANGE_OBJECT, buffer, obj.GetParentContainer(), rtc, true);
+ action->SetOldAndNewObjects(& obj, clone);
+ action->SetPosition(obj.GetRange().GetStart());
+ action->SetRange(obj.GetRange());
+ buffer->SubmitAction(action);
+ }
+
+ return true;
+}
+
+/// Get the style that is appropriate for a new paragraph at this position.
+/// If the previous paragraph has a paragraph style name, look up the next-paragraph
+/// style.
+wxRichTextAttr wxRichTextParagraphLayoutBox::GetStyleForNewParagraph(wxRichTextBuffer* buffer, long pos, bool caretPosition, bool lookUpNewParaStyle) const
+{
+ wxRichTextParagraph* para = GetParagraphAtPosition(pos, caretPosition);
+ if (para)
+ {
+ wxRichTextAttr attr;
+ bool foundAttributes = false;
+
+ // Look for a matching paragraph style
+ if (lookUpNewParaStyle && !para->GetAttributes().GetParagraphStyleName().IsEmpty() && buffer->GetStyleSheet())
+ {
+ wxRichTextParagraphStyleDefinition* paraDef = buffer->GetStyleSheet()->FindParagraphStyle(para->GetAttributes().GetParagraphStyleName());
+ if (paraDef)
+ {
+ // If we're not at the end of the paragraph, then we apply THIS style, and not the designated next style.
+ if (para->GetRange().GetEnd() == pos && !paraDef->GetNextStyle().IsEmpty())
+ {
+ wxRichTextParagraphStyleDefinition* nextParaDef = buffer->GetStyleSheet()->FindParagraphStyle(paraDef->GetNextStyle());
+ if (nextParaDef)
+ {
+ foundAttributes = true;
+ attr = nextParaDef->GetStyleMergedWithBase(buffer->GetStyleSheet());
+ }
+ }
+
+ // If we didn't find the 'next style', use this style instead.
+ if (!foundAttributes)
+ {
+ foundAttributes = true;
+ attr = paraDef->GetStyleMergedWithBase(buffer->GetStyleSheet());
+ }
+ }
+ }
+
+ // Also apply list style if present
+ if (lookUpNewParaStyle && !para->GetAttributes().GetListStyleName().IsEmpty() && buffer->GetStyleSheet())
+ {
+ wxRichTextListStyleDefinition* listDef = buffer->GetStyleSheet()->FindListStyle(para->GetAttributes().GetListStyleName());
+ if (listDef)
+ {
+ int thisIndent = para->GetAttributes().GetLeftIndent();
+ int thisLevel = para->GetAttributes().HasOutlineLevel() ? para->GetAttributes().GetOutlineLevel() : listDef->FindLevelForIndent(thisIndent);
+
+ // Apply the overall list style, and item style for this level
+ wxRichTextAttr listStyle(listDef->GetCombinedStyleForLevel(thisLevel, buffer->GetStyleSheet()));
+ wxRichTextApplyStyle(attr, listStyle);
+ attr.SetOutlineLevel(thisLevel);
+ if (para->GetAttributes().HasBulletNumber())
+ attr.SetBulletNumber(para->GetAttributes().GetBulletNumber());
+ }
+ }
+
+ if (!foundAttributes)
+ {
+ attr = para->GetAttributes();
+ int flags = attr.GetFlags();
+
+ // Eliminate character styles
+ flags &= ( (~ wxTEXT_ATTR_FONT) |
+ (~ wxTEXT_ATTR_TEXT_COLOUR) |
+ (~ wxTEXT_ATTR_BACKGROUND_COLOUR) );
+ attr.SetFlags(flags);
+ }
+
+ return attr;
+ }
+ else
+ return wxRichTextAttr();
+}
+
+/// Submit command to delete this range
+bool wxRichTextBuffer::DeleteRangeWithUndo(const wxRichTextRange& range, wxRichTextCtrl* ctrl)
+{
+ return ctrl->GetFocusObject()->DeleteRangeWithUndo(range, ctrl, this);
+}
+
+/// Submit command to delete this range
+bool wxRichTextParagraphLayoutBox::DeleteRangeWithUndo(const wxRichTextRange& range, wxRichTextCtrl* ctrl, wxRichTextBuffer* buffer)
+{
+ wxRichTextAction* action = new wxRichTextAction(NULL, _("Delete"), wxRICHTEXT_DELETE, buffer, this, ctrl);
+
+ action->SetPosition(ctrl->GetCaretPosition());
+
+ // Set the range to delete
+ action->SetRange(range);
+
+ // Copy the fragment that we'll need to restore in Undo
+ CopyFragment(range, action->GetOldParagraphs());
+
+ // See if we're deleting a paragraph marker, in which case we need to
+ // make a note not to copy the attributes from the 2nd paragraph to the 1st.
+ if (range.GetStart() == range.GetEnd())
+ {
+ wxRichTextParagraph* para = GetParagraphAtPosition(range.GetStart());
+ if (para && para->GetRange().GetEnd() == range.GetEnd())
+ {
+ wxRichTextParagraph* nextPara = GetParagraphAtPosition(range.GetStart()+1);
+ if (nextPara && nextPara != para)
+ {
+ action->GetOldParagraphs().GetChildren().GetFirst()->GetData()->SetAttributes(nextPara->GetAttributes());
+ action->GetOldParagraphs().GetAttributes().SetFlags(action->GetOldParagraphs().GetAttributes().GetFlags() | wxTEXT_ATTR_KEEP_FIRST_PARA_STYLE);
+ }
+ }
+ }
+
+ buffer->SubmitAction(action);
+
+ return true;
+}
+
+/// Collapse undo/redo commands
+bool wxRichTextBuffer::BeginBatchUndo(const wxString& cmdName)
+{
+ if (m_batchedCommandDepth == 0)
+ {
+ wxASSERT(m_batchedCommand == NULL);
+ if (m_batchedCommand)
+ {
+ GetCommandProcessor()->Store(m_batchedCommand);
+ }
+ m_batchedCommand = new wxRichTextCommand(cmdName);
+ }
+
+ m_batchedCommandDepth ++;
+
+ return true;
+}
+
+/// Collapse undo/redo commands
+bool wxRichTextBuffer::EndBatchUndo()
+{
+ m_batchedCommandDepth --;
+
+ wxASSERT(m_batchedCommandDepth >= 0);
+ wxASSERT(m_batchedCommand != NULL);
+
+ if (m_batchedCommandDepth == 0)
+ {
+ GetCommandProcessor()->Store(m_batchedCommand);
+ m_batchedCommand = NULL;
+ }
+
+ return true;
+}
+
+/// Submit immediately, or delay according to whether collapsing is on
+bool wxRichTextBuffer::SubmitAction(wxRichTextAction* action)
+{
+ if (action && !action->GetNewParagraphs().IsEmpty())
+ PrepareContent(action->GetNewParagraphs());
+
+ if (BatchingUndo() && m_batchedCommand && !SuppressingUndo())
+ {
+ if (!action->GetIgnoreFirstTime())
+ {
+ wxRichTextCommand* cmd = new wxRichTextCommand(action->GetName());
+ cmd->AddAction(action);
+ cmd->Do();
+ cmd->GetActions().Clear();
+ delete cmd;
+ }
+
+ m_batchedCommand->AddAction(action);
+ }
+ else
+ {
+ wxRichTextCommand* cmd = new wxRichTextCommand(action->GetName());
+ cmd->AddAction(action);
+
+ // Only store it if we're not suppressing undo.
+ if (!action->GetIgnoreFirstTime())
+ {
+ return GetCommandProcessor()->Submit(cmd, !SuppressingUndo());
+ }
+ else if (!SuppressingUndo())
+ {
+ GetCommandProcessor()->Store(cmd); // Just store it, without Do()ing anything
+ }
+ }
+
+ return true;
+}
+
+/// Begin suppressing undo/redo commands.
+bool wxRichTextBuffer::BeginSuppressUndo()
+{
+ m_suppressUndo ++;
+
+ return true;
+}
+
+/// End suppressing undo/redo commands.
+bool wxRichTextBuffer::EndSuppressUndo()
+{
+ m_suppressUndo --;
+
+ return true;
+}
+
+/// Begin using a style
+bool wxRichTextBuffer::BeginStyle(const wxRichTextAttr& style)
+{
+ wxRichTextAttr newStyle(GetDefaultStyle());
+ newStyle.GetTextBoxAttr().Reset();
+
+ // Save the old default style
+ m_attributeStack.Append((wxObject*) new wxRichTextAttr(newStyle));
+
+ wxRichTextApplyStyle(newStyle, style);
+ newStyle.SetFlags(style.GetFlags()|newStyle.GetFlags());
+
+ SetDefaultStyle(newStyle);
+
+ return true;
+}
+
+/// End the style
+bool wxRichTextBuffer::EndStyle()
+{
+ if (!m_attributeStack.GetFirst())
+ {
+ wxLogDebug(_("Too many EndStyle calls!"));
+ return false;
+ }
+
+ wxList::compatibility_iterator node = m_attributeStack.GetLast();
+ wxRichTextAttr* attr = (wxRichTextAttr*)node->GetData();
+ m_attributeStack.Erase(node);
+
+ SetDefaultStyle(*attr);
+
+ delete attr;
+ return true;
+}
+
+/// End all styles
+bool wxRichTextBuffer::EndAllStyles()
+{
+ while (m_attributeStack.GetCount() != 0)
+ EndStyle();
+ return true;
+}
+
+/// Clear the style stack
+void wxRichTextBuffer::ClearStyleStack()
+{
+ for (wxList::compatibility_iterator node = m_attributeStack.GetFirst(); node; node = node->GetNext())
+ delete (wxRichTextAttr*) node->GetData();
+ m_attributeStack.Clear();
+}
+
+/// Begin using bold
+bool wxRichTextBuffer::BeginBold()
+{
+ wxRichTextAttr attr;
+ attr.SetFontWeight(wxFONTWEIGHT_BOLD);
+
+ return BeginStyle(attr);
+}
+
+/// Begin using italic
+bool wxRichTextBuffer::BeginItalic()
+{
+ wxRichTextAttr attr;
+ attr.SetFontStyle(wxFONTSTYLE_ITALIC);
+
+ return BeginStyle(attr);
+}
+
+/// Begin using underline
+bool wxRichTextBuffer::BeginUnderline()
+{
+ wxRichTextAttr attr;
+ attr.SetFontUnderlined(true);
+
+ return BeginStyle(attr);
+}
+
+/// Begin using point size
+bool wxRichTextBuffer::BeginFontSize(int pointSize)
+{
+ wxRichTextAttr attr;
+ attr.SetFontSize(pointSize);
+
+ return BeginStyle(attr);
+}
+
+/// Begin using this font
+bool wxRichTextBuffer::BeginFont(const wxFont& font)
+{
+ wxRichTextAttr attr;
+ attr.SetFont(font);
+
+ return BeginStyle(attr);
+}
+
+/// Begin using this colour
+bool wxRichTextBuffer::BeginTextColour(const wxColour& colour)
+{
+ wxRichTextAttr attr;
+ attr.SetFlags(wxTEXT_ATTR_TEXT_COLOUR);
+ attr.SetTextColour(colour);
+
+ return BeginStyle(attr);
+}
+
+/// Begin using alignment
+bool wxRichTextBuffer::BeginAlignment(wxTextAttrAlignment alignment)
+{
+ wxRichTextAttr attr;
+ attr.SetFlags(wxTEXT_ATTR_ALIGNMENT);
+ attr.SetAlignment(alignment);
+
+ return BeginStyle(attr);
+}
+
+/// Begin left indent
+bool wxRichTextBuffer::BeginLeftIndent(int leftIndent, int leftSubIndent)
+{
+ wxRichTextAttr attr;
+ attr.SetFlags(wxTEXT_ATTR_LEFT_INDENT);
+ attr.SetLeftIndent(leftIndent, leftSubIndent);
+
+ return BeginStyle(attr);
+}
+
+/// Begin right indent
+bool wxRichTextBuffer::BeginRightIndent(int rightIndent)
+{
+ wxRichTextAttr attr;
+ attr.SetFlags(wxTEXT_ATTR_RIGHT_INDENT);
+ attr.SetRightIndent(rightIndent);
+
+ return BeginStyle(attr);
+}
+
+/// Begin paragraph spacing
+bool wxRichTextBuffer::BeginParagraphSpacing(int before, int after)
+{
+ long flags = 0;
+ if (before != 0)
+ flags |= wxTEXT_ATTR_PARA_SPACING_BEFORE;
+ if (after != 0)
+ flags |= wxTEXT_ATTR_PARA_SPACING_AFTER;
+
+ wxRichTextAttr attr;
+ attr.SetFlags(flags);
+ attr.SetParagraphSpacingBefore(before);
+ attr.SetParagraphSpacingAfter(after);
+
+ return BeginStyle(attr);
+}
+
+/// Begin line spacing
+bool wxRichTextBuffer::BeginLineSpacing(int lineSpacing)
+{
+ wxRichTextAttr attr;
+ attr.SetFlags(wxTEXT_ATTR_LINE_SPACING);
+ attr.SetLineSpacing(lineSpacing);
+
+ return BeginStyle(attr);
+}
+
+/// Begin numbered bullet
+bool wxRichTextBuffer::BeginNumberedBullet(int bulletNumber, int leftIndent, int leftSubIndent, int bulletStyle)
+{
+ wxRichTextAttr attr;
+ attr.SetFlags(wxTEXT_ATTR_BULLET_STYLE|wxTEXT_ATTR_LEFT_INDENT);
+ attr.SetBulletStyle(bulletStyle);
+ attr.SetBulletNumber(bulletNumber);
+ attr.SetLeftIndent(leftIndent, leftSubIndent);
+
+ return BeginStyle(attr);
+}
+
+/// Begin symbol bullet
+bool wxRichTextBuffer::BeginSymbolBullet(const wxString& symbol, int leftIndent, int leftSubIndent, int bulletStyle)
+{
+ wxRichTextAttr attr;
+ attr.SetFlags(wxTEXT_ATTR_BULLET_STYLE|wxTEXT_ATTR_LEFT_INDENT);
+ attr.SetBulletStyle(bulletStyle);
+ attr.SetLeftIndent(leftIndent, leftSubIndent);
+ attr.SetBulletText(symbol);
+
+ return BeginStyle(attr);
+}
+
+/// Begin standard bullet
+bool wxRichTextBuffer::BeginStandardBullet(const wxString& bulletName, int leftIndent, int leftSubIndent, int bulletStyle)
+{
+ wxRichTextAttr attr;
+ attr.SetFlags(wxTEXT_ATTR_BULLET_STYLE|wxTEXT_ATTR_LEFT_INDENT);
+ attr.SetBulletStyle(bulletStyle);
+ attr.SetLeftIndent(leftIndent, leftSubIndent);
+ attr.SetBulletName(bulletName);
+
+ return BeginStyle(attr);
+}
+
+/// Begin named character style
+bool wxRichTextBuffer::BeginCharacterStyle(const wxString& characterStyle)
+{
+ if (GetStyleSheet())
+ {
+ wxRichTextCharacterStyleDefinition* def = GetStyleSheet()->FindCharacterStyle(characterStyle);
+ if (def)
+ {
+ wxRichTextAttr attr = def->GetStyleMergedWithBase(GetStyleSheet());
+ return BeginStyle(attr);
+ }
+ }
+ return false;
+}
+
+/// Begin named paragraph style
+bool wxRichTextBuffer::BeginParagraphStyle(const wxString& paragraphStyle)
+{
+ if (GetStyleSheet())
+ {
+ wxRichTextParagraphStyleDefinition* def = GetStyleSheet()->FindParagraphStyle(paragraphStyle);
+ if (def)
+ {
+ wxRichTextAttr attr = def->GetStyleMergedWithBase(GetStyleSheet());
+ return BeginStyle(attr);
+ }
+ }
+ return false;
+}
+
+/// Begin named list style
+bool wxRichTextBuffer::BeginListStyle(const wxString& listStyle, int level, int number)
+{
+ if (GetStyleSheet())
+ {
+ wxRichTextListStyleDefinition* def = GetStyleSheet()->FindListStyle(listStyle);
+ if (def)
+ {
+ wxRichTextAttr attr(def->GetCombinedStyleForLevel(level));
+
+ attr.SetBulletNumber(number);
+
+ return BeginStyle(attr);
+ }
+ }
+ return false;
+}
+
+/// Begin URL
+bool wxRichTextBuffer::BeginURL(const wxString& url, const wxString& characterStyle)
+{
+ wxRichTextAttr attr;
+
+ if (!characterStyle.IsEmpty() && GetStyleSheet())
+ {
+ wxRichTextCharacterStyleDefinition* def = GetStyleSheet()->FindCharacterStyle(characterStyle);
+ if (def)
+ {
+ attr = def->GetStyleMergedWithBase(GetStyleSheet());
+ }
+ }
+ attr.SetURL(url);
+
+ return BeginStyle(attr);
+}
+
+/// Adds a handler to the end
+void wxRichTextBuffer::AddHandler(wxRichTextFileHandler *handler)
+{
+ sm_handlers.Append(handler);
+}
+
+/// Inserts a handler at the front
+void wxRichTextBuffer::InsertHandler(wxRichTextFileHandler *handler)
+{
+ sm_handlers.Insert( handler );
+}
+
+/// Removes a handler
+bool wxRichTextBuffer::RemoveHandler(const wxString& name)
+{
+ wxRichTextFileHandler *handler = FindHandler(name);
+ if (handler)
+ {
+ sm_handlers.DeleteObject(handler);
+ delete handler;
+ return true;
+ }
+ else
+ return false;
+}
+
+/// Finds a handler by filename or, if supplied, type
+wxRichTextFileHandler *wxRichTextBuffer::FindHandlerFilenameOrType(const wxString& filename,
+ wxRichTextFileType imageType)
+{
+ if (imageType != wxRICHTEXT_TYPE_ANY)
+ return FindHandler(imageType);
+ else if (!filename.IsEmpty())
+ {
+ wxString path, file, ext;
+ wxFileName::SplitPath(filename, & path, & file, & ext);
+ return FindHandler(ext, imageType);
+ }
+ else
+ return NULL;
+}
+
+
+/// Finds a handler by name
+wxRichTextFileHandler* wxRichTextBuffer::FindHandler(const wxString& name)
+{
+ wxList::compatibility_iterator node = sm_handlers.GetFirst();
+ while (node)
+ {
+ wxRichTextFileHandler *handler = (wxRichTextFileHandler*)node->GetData();
+ if (handler->GetName().Lower() == name.Lower()) return handler;
+
+ node = node->GetNext();
+ }
+ return NULL;
+}
+
+/// Finds a handler by extension and type
+wxRichTextFileHandler* wxRichTextBuffer::FindHandler(const wxString& extension, wxRichTextFileType type)
+{
+ wxList::compatibility_iterator node = sm_handlers.GetFirst();
+ while (node)
+ {
+ wxRichTextFileHandler *handler = (wxRichTextFileHandler*)node->GetData();
+ if ( handler->GetExtension().Lower() == extension.Lower() &&
+ (type == wxRICHTEXT_TYPE_ANY || handler->GetType() == type) )
+ return handler;
+ node = node->GetNext();
+ }
+ return 0;
+}
+
+/// Finds a handler by type
+wxRichTextFileHandler* wxRichTextBuffer::FindHandler(wxRichTextFileType type)
+{
+ wxList::compatibility_iterator node = sm_handlers.GetFirst();
+ while (node)
+ {
+ wxRichTextFileHandler *handler = (wxRichTextFileHandler *)node->GetData();
+ if (handler->GetType() == type) return handler;
+ node = node->GetNext();
+ }
+ return NULL;
+}
+
+void wxRichTextBuffer::InitStandardHandlers()
+{
+ if (!FindHandler(wxRICHTEXT_TYPE_TEXT))
+ AddHandler(new wxRichTextPlainTextHandler);
+}
+
+void wxRichTextBuffer::CleanUpHandlers()
+{
+ wxList::compatibility_iterator node = sm_handlers.GetFirst();
+ while (node)
+ {
+ wxRichTextFileHandler* handler = (wxRichTextFileHandler*)node->GetData();
+ wxList::compatibility_iterator next = node->GetNext();
+ delete handler;
+ node = next;
+ }
+
+ sm_handlers.Clear();
+}
+
+wxString wxRichTextBuffer::GetExtWildcard(bool combine, bool save, wxArrayInt* types)
+{
+ if (types)
+ types->Clear();
+
+ wxString wildcard;
+
+ wxList::compatibility_iterator node = GetHandlers().GetFirst();
+ int count = 0;
+ while (node)
+ {
+ wxRichTextFileHandler* handler = (wxRichTextFileHandler*) node->GetData();
+ if (handler->IsVisible() && ((save && handler->CanSave()) || (!save && handler->CanLoad())))
+ {
+ if (combine)
+ {
+ if (count > 0)
+ wildcard += wxT(";");
+ wildcard += wxT("*.") + handler->GetExtension();
+ }
+ else
+ {
+ if (count > 0)
+ wildcard += wxT("|");
+ wildcard += handler->GetName();
+ wildcard += wxT(" ");
+ wildcard += _("files");
+ wildcard += wxT(" (*.");
+ wildcard += handler->GetExtension();
+ wildcard += wxT(")|*.");
+ wildcard += handler->GetExtension();
+ if (types)
+ types->Add(handler->GetType());
+ }
+ count ++;
+ }
+
+ node = node->GetNext();
+ }
+
+ if (combine)
+ wildcard = wxT("(") + wildcard + wxT(")|") + wildcard;
+ return wildcard;
+}
+
+#if wxUSE_FFILE && wxUSE_STREAMS
+/// Load a file
+bool wxRichTextBuffer::LoadFile(const wxString& filename, wxRichTextFileType type)
+{
+ wxRichTextFileHandler* handler = FindHandlerFilenameOrType(filename, type);
+ if (handler)
+ {
+ SetDefaultStyle(wxRichTextAttr());
+ handler->SetFlags(GetHandlerFlags());
+ bool success = handler->LoadFile(this, filename);
+ Invalidate(wxRICHTEXT_ALL);
+ return success;
+ }
+ else
+ return false;
+}
+
+/// Save a file
+bool wxRichTextBuffer::SaveFile(const wxString& filename, wxRichTextFileType type)
+{
+ wxRichTextFileHandler* handler = FindHandlerFilenameOrType(filename, type);
+ if (handler)
+ {
+ handler->SetFlags(GetHandlerFlags());
+ return handler->SaveFile(this, filename);
+ }
+ else
+ return false;
+}
+#endif // wxUSE_FFILE && wxUSE_STREAMS
+
+#if wxUSE_STREAMS
+/// Load from a stream
+bool wxRichTextBuffer::LoadFile(wxInputStream& stream, wxRichTextFileType type)
+{
+ wxRichTextFileHandler* handler = FindHandler(type);
+ if (handler)
+ {
+ SetDefaultStyle(wxRichTextAttr());
+ handler->SetFlags(GetHandlerFlags());
+ bool success = handler->LoadFile(this, stream);
+ Invalidate(wxRICHTEXT_ALL);
+ return success;
+ }
+ else
+ return false;
+}
+
+/// Save to a stream
+bool wxRichTextBuffer::SaveFile(wxOutputStream& stream, wxRichTextFileType type)
+{
+ wxRichTextFileHandler* handler = FindHandler(type);
+ if (handler)
+ {
+ handler->SetFlags(GetHandlerFlags());
+ return handler->SaveFile(this, stream);
+ }
+ else
+ return false;
+}
+#endif // wxUSE_STREAMS
+
+/// Copy the range to the clipboard
+bool wxRichTextBuffer::CopyToClipboard(const wxRichTextRange& range)
+{
+ bool success = false;
+ wxRichTextParagraphLayoutBox* container = this;
+ if (GetRichTextCtrl())
+ container = GetRichTextCtrl()->GetFocusObject();
+
+#if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
+
+ if (!wxTheClipboard->IsOpened() && wxTheClipboard->Open())
+ {
+ wxTheClipboard->Clear();
+
+ // Add composite object
+
+ wxDataObjectComposite* compositeObject = new wxDataObjectComposite();
+
+ {
+ wxString text = container->GetTextForRange(range);
+
+#ifdef __WXMSW__
+ text = wxTextFile::Translate(text, wxTextFileType_Dos);
+#endif
+
+ compositeObject->Add(new wxTextDataObject(text), false /* not preferred */);
+ }
+
+ // Add rich text buffer data object. This needs the XML handler to be present.
+
+ if (FindHandler(wxRICHTEXT_TYPE_XML))
+ {
+ wxRichTextBuffer* richTextBuf = new wxRichTextBuffer;
+ container->CopyFragment(range, *richTextBuf);
+
+ compositeObject->Add(new wxRichTextBufferDataObject(richTextBuf), true /* preferred */);
+ }
+
+ if (wxTheClipboard->SetData(compositeObject))
+ success = true;
+
+ wxTheClipboard->Close();
+ }
+
+#else
+ wxUnusedVar(range);
+#endif
+ return success;
+}
+
+/// Paste the clipboard content to the buffer
+bool wxRichTextBuffer::PasteFromClipboard(long position)
+{
+ bool success = false;
+ wxRichTextParagraphLayoutBox* container = this;
+ if (GetRichTextCtrl())
+ container = GetRichTextCtrl()->GetFocusObject();
+
+#if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
+ if (CanPasteFromClipboard())
+ {
+ if (wxTheClipboard->Open())
+ {
+ if (wxTheClipboard->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())))
+ {
+ wxRichTextBufferDataObject data;
+ wxTheClipboard->GetData(data);
+ wxRichTextBuffer* richTextBuffer = data.GetRichTextBuffer();
+ if (richTextBuffer)
+ {
+ container->InsertParagraphsWithUndo(this, position+1, *richTextBuffer, GetRichTextCtrl(), 0);
+ if (GetRichTextCtrl())
+ GetRichTextCtrl()->ShowPosition(position + richTextBuffer->GetOwnRange().GetEnd());
+ delete richTextBuffer;
+ }
+ }
+ else if (wxTheClipboard->IsSupported(wxDF_TEXT)
+ #if wxUSE_UNICODE
+ || wxTheClipboard->IsSupported(wxDF_UNICODETEXT)
+ #endif
+ )
+ {
+ wxTextDataObject data;
+ wxTheClipboard->GetData(data);
+ wxString text(data.GetText());
+#ifdef __WXMSW__
+ wxString text2;
+ text2.Alloc(text.Length()+1);
+ size_t i;
+ for (i = 0; i < text.Length(); i++)
+ {
+ wxChar ch = text[i];
+ if (ch != wxT('\r'))
+ text2 += ch;
+ }
+#else
+ wxString text2 = text;
+#endif
+ container->InsertTextWithUndo(this, position+1, text2, GetRichTextCtrl(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE);
+
+ if (GetRichTextCtrl())
+ GetRichTextCtrl()->ShowPosition(position + text2.Length());
+
+ success = true;
+ }
+ else if (wxTheClipboard->IsSupported(wxDF_BITMAP))
+ {
+ wxBitmapDataObject data;
+ wxTheClipboard->GetData(data);
+ wxBitmap bitmap(data.GetBitmap());
+ wxImage image(bitmap.ConvertToImage());
+
+ wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Image"), wxRICHTEXT_INSERT, this, container, GetRichTextCtrl(), false);
+
+ action->GetNewParagraphs().AddImage(image);
+
+ if (action->GetNewParagraphs().GetChildCount() == 1)
+ action->GetNewParagraphs().SetPartialParagraph(true);
+
+ action->SetPosition(position+1);
+
+ // Set the range we'll need to delete in Undo
+ action->SetRange(wxRichTextRange(position+1, position+1));
+
+ SubmitAction(action);
+
+ success = true;
+ }
+ wxTheClipboard->Close();
+ }
+ }
+#else
+ wxUnusedVar(position);
+#endif
+ return success;
+}
+
+/// Can we paste from the clipboard?
+bool wxRichTextBuffer::CanPasteFromClipboard() const
+{
+ bool canPaste = false;
+#if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
+ if (!wxTheClipboard->IsOpened() && wxTheClipboard->Open())
+ {
+ if (wxTheClipboard->IsSupported(wxDF_TEXT)
+#if wxUSE_UNICODE
+ || wxTheClipboard->IsSupported(wxDF_UNICODETEXT)
+#endif
+ || wxTheClipboard->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())) ||
+ wxTheClipboard->IsSupported(wxDF_BITMAP))
+ {
+ canPaste = true;
+ }
+ wxTheClipboard->Close();
+ }
+#endif
+ return canPaste;
+}
+
+/// Dumps contents of buffer for debugging purposes
+void wxRichTextBuffer::Dump()
+{
+ wxString text;
+ {
+ wxStringOutputStream stream(& text);
+ wxTextOutputStream textStream(stream);
+ Dump(textStream);
+ }
+
+ wxLogDebug(text);
+}
+
+/// Add an event handler
+bool wxRichTextBuffer::AddEventHandler(wxEvtHandler* handler)
+{
+ m_eventHandlers.Append(handler);
+ return true;
+}
+
+/// Remove an event handler
+bool wxRichTextBuffer::RemoveEventHandler(wxEvtHandler* handler, bool deleteHandler)
+{
+ wxList::compatibility_iterator node = m_eventHandlers.Find(handler);
+ if (node)
+ {
+ m_eventHandlers.Erase(node);
+ if (deleteHandler)
+ delete handler;
+
+ return true;
+ }
+ else
+ return false;
+}
+
+/// Clear event handlers
+void wxRichTextBuffer::ClearEventHandlers()
+{
+ m_eventHandlers.Clear();
+}
+
+/// Send event to event handlers. If sendToAll is true, will send to all event handlers,
+/// otherwise will stop at the first successful one.
+bool wxRichTextBuffer::SendEvent(wxEvent& event, bool sendToAll)
+{
+ bool success = false;
+ for (wxList::compatibility_iterator node = m_eventHandlers.GetFirst(); node; node = node->GetNext())
+ {
+ wxEvtHandler* handler = (wxEvtHandler*) node->GetData();
+ if (handler->ProcessEvent(event))
+ {
+ success = true;
+ if (!sendToAll)
+ return true;
+ }
+ }
+ return success;
+}
+
+/// Set style sheet and notify of the change
+bool wxRichTextBuffer::SetStyleSheetAndNotify(wxRichTextStyleSheet* sheet)
+{
+ wxRichTextStyleSheet* oldSheet = GetStyleSheet();
+
+ wxWindowID winid = wxID_ANY;
+ if (GetRichTextCtrl())
+ winid = GetRichTextCtrl()->GetId();
+
+ wxRichTextEvent event(wxEVT_RICHTEXT_STYLESHEET_REPLACING, winid);
+ event.SetEventObject(GetRichTextCtrl());
+ event.SetContainer(GetRichTextCtrl()->GetFocusObject());
+ event.SetOldStyleSheet(oldSheet);
+ event.SetNewStyleSheet(sheet);
+ event.Allow();
+
+ if (SendEvent(event) && !event.IsAllowed())
+ {
+ if (sheet != oldSheet)
+ delete sheet;
+
+ return false;
+ }
+
+ if (oldSheet && oldSheet != sheet)
+ delete oldSheet;
+
+ SetStyleSheet(sheet);
+
+ event.SetEventType(wxEVT_RICHTEXT_STYLESHEET_REPLACED);
+ event.SetOldStyleSheet(NULL);
+ event.Allow();
+
+ return SendEvent(event);
+}
+
+/// Set renderer, deleting old one
+void wxRichTextBuffer::SetRenderer(wxRichTextRenderer* renderer)
+{
+ if (sm_renderer)
+ delete sm_renderer;
+ sm_renderer = renderer;
+}
+
+/// Hit-testing: returns a flag indicating hit test details, plus
+/// information about position
+int wxRichTextBuffer::HitTest(wxDC& dc, wxRichTextDrawingContext& context, const wxPoint& pt, long& textPosition, wxRichTextObject** obj, wxRichTextObject** contextObj, int flags)
+{
+ int ret = wxRichTextParagraphLayoutBox::HitTest(dc, context, pt, textPosition, obj, contextObj, flags);
+ if (ret != wxRICHTEXT_HITTEST_NONE)
+ {
+ return ret;
+ }
+ else
+ {
+ textPosition = m_ownRange.GetEnd()-1;
+ *obj = this;
+ *contextObj = this;
+ return wxRICHTEXT_HITTEST_AFTER|wxRICHTEXT_HITTEST_OUTSIDE;
+ }
+}
+
+void wxRichTextBuffer::SetFontScale(double fontScale)
+{
+ m_fontScale = fontScale;
+ m_fontTable.SetFontScale(fontScale);
+}
+
+void wxRichTextBuffer::SetDimensionScale(double dimScale)
+{
+ m_dimensionScale = dimScale;
+}
+
+bool wxRichTextStdRenderer::DrawStandardBullet(wxRichTextParagraph* paragraph, wxDC& dc, const wxRichTextAttr& bulletAttr, const wxRect& rect)
+{
+ if (bulletAttr.GetTextColour().IsOk())
+ {
+ wxCheckSetPen(dc, wxPen(bulletAttr.GetTextColour()));
+ wxCheckSetBrush(dc, wxBrush(bulletAttr.GetTextColour()));
+ }
+ else
+ {
+ wxCheckSetPen(dc, *wxBLACK_PEN);
+ wxCheckSetBrush(dc, *wxBLACK_BRUSH);
+ }
+
+ wxFont font;
+ if (bulletAttr.HasFont())
+ {
+ font = paragraph->GetBuffer()->GetFontTable().FindFont(bulletAttr);
+ }
+ else
+ font = (*wxNORMAL_FONT);
+
+ wxCheckSetFont(dc, font);
+
+ int charHeight = dc.GetCharHeight();
+
+ int bulletWidth = (int) (((float) charHeight) * wxRichTextBuffer::GetBulletProportion());
+ int bulletHeight = bulletWidth;
+
+ int x = rect.x;
+
+ // Calculate the top position of the character (as opposed to the whole line height)
+ int y = rect.y + (rect.height - charHeight);
+
+ // Calculate where the bullet should be positioned
+ y = y + (charHeight+1)/2 - (bulletHeight+1)/2;
+
+ // The margin between a bullet and text.
+ int margin = paragraph->ConvertTenthsMMToPixels(dc, wxRichTextBuffer::GetBulletRightMargin());
+
+ if (bulletAttr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT)
+ x = rect.x + rect.width - bulletWidth - margin;
+ else if (bulletAttr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE)
+ x = x + (rect.width)/2 - bulletWidth/2;
+
+ if (bulletAttr.GetBulletName() == wxT("standard/square"))
+ {
+ dc.DrawRectangle(x, y, bulletWidth, bulletHeight);
+ }
+ else if (bulletAttr.GetBulletName() == wxT("standard/diamond"))
+ {
+ wxPoint pts[5];
+ pts[0].x = x; pts[0].y = y + bulletHeight/2;
+ pts[1].x = x + bulletWidth/2; pts[1].y = y;
+ pts[2].x = x + bulletWidth; pts[2].y = y + bulletHeight/2;
+ pts[3].x = x + bulletWidth/2; pts[3].y = y + bulletHeight;
+
+ dc.DrawPolygon(4, pts);
+ }
+ else if (bulletAttr.GetBulletName() == wxT("standard/triangle"))
+ {
+ wxPoint pts[3];
+ pts[0].x = x; pts[0].y = y;
+ pts[1].x = x + bulletWidth; pts[1].y = y + bulletHeight/2;
+ pts[2].x = x; pts[2].y = y + bulletHeight;
+
+ dc.DrawPolygon(3, pts);
+ }
+ else if (bulletAttr.GetBulletName() == wxT("standard/circle-outline"))
+ {
+ wxCheckSetBrush(dc, *wxTRANSPARENT_BRUSH);
+ dc.DrawEllipse(x, y, bulletWidth, bulletHeight);
+ }
+ else // "standard/circle", and catch-all
+ {
+ dc.DrawEllipse(x, y, bulletWidth, bulletHeight);
+ }
+
+ return true;
+}
+
+bool wxRichTextStdRenderer::DrawTextBullet(wxRichTextParagraph* paragraph, wxDC& dc, const wxRichTextAttr& attr, const wxRect& rect, const wxString& text)
+{
+ if (!text.empty())
+ {
+ wxFont font;
+ if ((attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL) && !attr.GetBulletFont().IsEmpty() && attr.HasFont())
+ {
+ wxRichTextAttr fontAttr;
+ if (attr.HasFontPixelSize())
+ fontAttr.SetFontPixelSize(attr.GetFontSize());
+ else
+ fontAttr.SetFontPointSize(attr.GetFontSize());
+ fontAttr.SetFontStyle(attr.GetFontStyle());
+ fontAttr.SetFontWeight(attr.GetFontWeight());
+ fontAttr.SetFontUnderlined(attr.GetFontUnderlined());
+ fontAttr.SetFontFaceName(attr.GetBulletFont());
+ font = paragraph->GetBuffer()->GetFontTable().FindFont(fontAttr);
+ }
+ else if (attr.HasFont())
+ font = paragraph->GetBuffer()->GetFontTable().FindFont(attr);
+ else
+ font = (*wxNORMAL_FONT);
+
+ wxCheckSetFont(dc, font);
+
+ if (attr.GetTextColour().IsOk())
+ dc.SetTextForeground(attr.GetTextColour());
+
+ dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT);
+
+ int charHeight = dc.GetCharHeight();
+ wxCoord tw, th;
+ dc.GetTextExtent(text, & tw, & th);
+
+ int x = rect.x;
+
+ // Calculate the top position of the character (as opposed to the whole line height)
+ int y = rect.y + (rect.height - charHeight);
+
+ // The margin between a bullet and text.
+ int margin = paragraph->ConvertTenthsMMToPixels(dc, wxRichTextBuffer::GetBulletRightMargin());
+
+ if (attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT)
+ x = (rect.x + rect.width) - tw - margin;
+ else if (attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE)
+ x = x + (rect.width)/2 - tw/2;
+
+ dc.DrawText(text, x, y);
+
+ return true;
+ }
+ else
+ return false;
+}
+
+bool wxRichTextStdRenderer::DrawBitmapBullet(wxRichTextParagraph* WXUNUSED(paragraph), wxDC& WXUNUSED(dc), const wxRichTextAttr& WXUNUSED(attr), const wxRect& WXUNUSED(rect))
+{
+ // Currently unimplemented. The intention is to store bitmaps by name in a media store associated
+ // with the buffer. The store will allow retrieval from memory, disk or other means.
+ return false;
+}
+
+/// Enumerate the standard bullet names currently supported
+bool wxRichTextStdRenderer::EnumerateStandardBulletNames(wxArrayString& bulletNames)
+{
+ bulletNames.Add(wxTRANSLATE("standard/circle"));
+ bulletNames.Add(wxTRANSLATE("standard/circle-outline"));
+ bulletNames.Add(wxTRANSLATE("standard/square"));
+ bulletNames.Add(wxTRANSLATE("standard/diamond"));
+ bulletNames.Add(wxTRANSLATE("standard/triangle"));
+
+ return true;
+}
+
+/*!
+ * wxRichTextBox
+ */
+
+IMPLEMENT_DYNAMIC_CLASS(wxRichTextBox, wxRichTextParagraphLayoutBox)
+
+wxRichTextBox::wxRichTextBox(wxRichTextObject* parent):
+ wxRichTextParagraphLayoutBox(parent)
+{
+}
+
+/// Draw the item
+bool wxRichTextBox::Draw(wxDC& dc, wxRichTextDrawingContext& context, const wxRichTextRange& range, const wxRichTextSelection& selection, const wxRect& rect, int descent, int style)
+{
+ if (!IsShown())
+ return true;
+
+ // TODO: if the active object in the control, draw an indication.
+ // We need to add the concept of active object, and not just focus object,
+ // so we can apply commands (properties, delete, ...) to objects such as text boxes and images.
+ // Ultimately we would like to be able to interactively resize an active object
+ // using drag handles.
+ return wxRichTextParagraphLayoutBox::Draw(dc, context, range, selection, rect, descent, style);
+}
+
+/// Copy
+void wxRichTextBox::Copy(const wxRichTextBox& obj)
+{
+ wxRichTextParagraphLayoutBox::Copy(obj);
+}
+
+// Edit properties via a GUI
+bool wxRichTextBox::EditProperties(wxWindow* parent, wxRichTextBuffer* buffer)
+{
+ wxRichTextObjectPropertiesDialog boxDlg(this, wxGetTopLevelParent(parent), wxID_ANY, _("Box Properties"));
+ boxDlg.SetAttributes(GetAttributes());
+
+ if (boxDlg.ShowModal() == wxID_OK)
+ {
+ // By passing wxRICHTEXT_SETSTYLE_RESET, indeterminate attributes set by the user will be set as
+ // indeterminate in the object.
+ boxDlg.ApplyStyle(buffer->GetRichTextCtrl(), wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_RESET);
+ return true;
+ }
+ else
+ return false;
+}
+
+/*!
+ * wxRichTextField
+ */
+
+IMPLEMENT_DYNAMIC_CLASS(wxRichTextField, wxRichTextParagraphLayoutBox)
+
+wxRichTextField::wxRichTextField(const wxString& fieldType, wxRichTextObject* parent):
+ wxRichTextParagraphLayoutBox(parent)
+{
+ SetFieldType(fieldType);
+}
+
+/// Draw the item
+bool wxRichTextField::Draw(wxDC& dc, wxRichTextDrawingContext& context, const wxRichTextRange& range, const wxRichTextSelection& selection, const wxRect& rect, int descent, int style)
+{
+ if (!IsShown())
+ return true;
+
+ wxRichTextFieldType* fieldType = wxRichTextBuffer::FindFieldType(GetFieldType());
+ if (fieldType && fieldType->Draw(this, dc, context, range, selection, rect, descent, style))
+ return true;
+
+ // Fallback; but don't draw guidelines.
+ style &= ~wxRICHTEXT_DRAW_GUIDELINES;
+ return wxRichTextParagraphLayoutBox::Draw(dc, context, range, selection, rect, descent, style);
+}
+
+bool wxRichTextField::Layout(wxDC& dc, wxRichTextDrawingContext& context, const wxRect& rect, const wxRect& parentRect, int style)
+{
+ wxRichTextFieldType* fieldType = wxRichTextBuffer::FindFieldType(GetFieldType());
+ if (fieldType && fieldType->Layout(this, dc, context, rect, parentRect, style))
+ return true;
+
+ // Fallback
+ return wxRichTextParagraphLayoutBox::Layout(dc, context, rect, parentRect, style);
+}
+
+bool wxRichTextField::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, wxRichTextDrawingContext& context, int flags, const wxPoint& position, const wxSize& parentSize, wxArrayInt* partialExtents) const
+{
+ wxRichTextFieldType* fieldType = wxRichTextBuffer::FindFieldType(GetFieldType());
+ if (fieldType)
+ return fieldType->GetRangeSize((wxRichTextField*) this, range, size, descent, dc, context, flags, position, parentSize, partialExtents);
+
+ return wxRichTextParagraphLayoutBox::GetRangeSize(range, size, descent, dc, context, flags, position, parentSize, partialExtents);
+}
+
+/// Calculate range
+void wxRichTextField::CalculateRange(long start, long& end)
+{
+ if (IsTopLevel())
+ wxRichTextParagraphLayoutBox::CalculateRange(start, end);
+ else
+ wxRichTextObject::CalculateRange(start, end);
+}
+
+/// Copy
+void wxRichTextField::Copy(const wxRichTextField& obj)
+{
+ wxRichTextParagraphLayoutBox::Copy(obj);
+
+ UpdateField(GetBuffer());
+}
+
+// Edit properties via a GUI
+bool wxRichTextField::EditProperties(wxWindow* parent, wxRichTextBuffer* buffer)
+{
+ wxRichTextFieldType* fieldType = wxRichTextBuffer::FindFieldType(GetFieldType());
+ if (fieldType)
+ return fieldType->EditProperties(this, parent, buffer);
+
+ return false;
+}
+
+bool wxRichTextField::CanEditProperties() const
+{
+ wxRichTextFieldType* fieldType = wxRichTextBuffer::FindFieldType(GetFieldType());
+ if (fieldType)
+ return fieldType->CanEditProperties((wxRichTextField*) this);
+
+ return false;
+}
+
+wxString wxRichTextField::GetPropertiesMenuLabel() const
+{
+ wxRichTextFieldType* fieldType = wxRichTextBuffer::FindFieldType(GetFieldType());
+ if (fieldType)
+ return fieldType->GetPropertiesMenuLabel((wxRichTextField*) this);
+
+ return wxEmptyString;
+}
+
+bool wxRichTextField::UpdateField(wxRichTextBuffer* buffer)
+{
+ wxRichTextFieldType* fieldType = wxRichTextBuffer::FindFieldType(GetFieldType());
+ if (fieldType)
+ return fieldType->UpdateField(buffer, (wxRichTextField*) this);
+
+ return false;
+}
+
+bool wxRichTextField::IsTopLevel() const
+{
+ wxRichTextFieldType* fieldType = wxRichTextBuffer::FindFieldType(GetFieldType());
+ if (fieldType)
+ return fieldType->IsTopLevel((wxRichTextField*) this);
+
+ return true;
+}
+
+IMPLEMENT_CLASS(wxRichTextFieldType, wxObject)
+
+IMPLEMENT_CLASS(wxRichTextFieldTypeStandard, wxRichTextFieldType)
+
+wxRichTextFieldTypeStandard::wxRichTextFieldTypeStandard(const wxString& name, const wxString& label, int displayStyle)
+{
+ Init();
+
+ SetName(name);
+ SetLabel(label);
+ SetDisplayStyle(displayStyle);
+}
+
+wxRichTextFieldTypeStandard::wxRichTextFieldTypeStandard(const wxString& name, const wxBitmap& bitmap, int displayStyle)
+{
+ Init();
+
+ SetName(name);
+ SetBitmap(bitmap);
+ SetDisplayStyle(displayStyle);
+}
+
+void wxRichTextFieldTypeStandard::Init()
+{
+ m_displayStyle = wxRICHTEXT_FIELD_STYLE_RECTANGLE;
+ m_font = wxFont(6, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);
+ m_textColour = *wxWHITE;
+ m_borderColour = *wxBLACK;
+ m_backgroundColour = *wxBLACK;
+ m_verticalPadding = 1;
+ m_horizontalPadding = 3;
+ m_horizontalMargin = 2;
+ m_verticalMargin = 0;
+}
+
+void wxRichTextFieldTypeStandard::Copy(const wxRichTextFieldTypeStandard& field)
+{
+ wxRichTextFieldType::Copy(field);
+
+ m_label = field.m_label;
+ m_displayStyle = field.m_displayStyle;
+ m_font = field.m_font;
+ m_textColour = field.m_textColour;
+ m_borderColour = field.m_borderColour;
+ m_backgroundColour = field.m_backgroundColour;
+ m_verticalPadding = field.m_verticalPadding;
+ m_horizontalPadding = field.m_horizontalPadding;
+ m_horizontalMargin = field.m_horizontalMargin;
+ m_bitmap = field.m_bitmap;
+}
+
+bool wxRichTextFieldTypeStandard::Draw(wxRichTextField* obj, wxDC& dc, wxRichTextDrawingContext& WXUNUSED(context), const wxRichTextRange& WXUNUSED(range), const wxRichTextSelection& selection, const wxRect& rect, int descent, int WXUNUSED(style))
+{
+ if (m_displayStyle == wxRICHTEXT_FIELD_STYLE_COMPOSITE)
+ return false; // USe default composite drawing
+ else // if (m_displayStyle == wxRICHTEXT_FIELD_STYLE_RECTANGLE || m_displayStyle == wxRICHTEXT_FIELD_STYLE_NOBORDER)
+ {
+ int borderSize = 1;
+
+ wxPen borderPen(m_borderColour, 1, wxSOLID);
+ wxBrush backgroundBrush(m_backgroundColour);
+ wxColour textColour(m_textColour);
+
+ if (selection.WithinSelection(obj->GetRange().GetStart(), obj))
+ {
+ wxColour highlightColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT));
+ wxColour highlightTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT));
+
+ borderPen = wxPen(highlightTextColour, 1, wxSOLID);
+ backgroundBrush = wxBrush(highlightColour);
+
+ wxCheckSetBrush(dc, backgroundBrush);
+ wxCheckSetPen(dc, wxPen(highlightColour, 1, wxSOLID));
+ dc.DrawRectangle(rect);
+ }
+
+ if (m_displayStyle != wxRICHTEXT_FIELD_STYLE_NO_BORDER)
+ borderSize = 0;
+
+ // objectRect is the area where the content is drawn, after margins around it have been taken into account
+ wxRect objectRect = wxRect(wxPoint(rect.x + m_horizontalMargin, rect.y + wxMax(0, rect.height - descent - obj->GetCachedSize().y)),
+ wxSize(obj->GetCachedSize().x - 2*m_horizontalMargin - borderSize, obj->GetCachedSize().y));
+
+ // clientArea is where the text is actually written
+ wxRect clientArea = objectRect;
+
+ if (m_displayStyle == wxRICHTEXT_FIELD_STYLE_RECTANGLE)
+ {
+ dc.SetPen(borderPen);
+ dc.SetBrush(backgroundBrush);
+ dc.DrawRoundedRectangle(objectRect, 4.0);
+ }
+ else if (m_displayStyle == wxRICHTEXT_FIELD_STYLE_START_TAG)
+ {
+ int arrowLength = objectRect.height/2;
+ clientArea.width -= (arrowLength - m_horizontalPadding);
+
+ wxPoint pts[5];
+ pts[0].x = objectRect.x; pts[0].y = objectRect.y;
+ pts[1].x = objectRect.x + objectRect.width - arrowLength; pts[1].y = objectRect.y;
+ pts[2].x = objectRect.x + objectRect.width; pts[2].y = objectRect.y + (objectRect.height/2);
+ pts[3].x = objectRect.x + objectRect.width - arrowLength; pts[3].y = objectRect.y + objectRect.height;
+ pts[4].x = objectRect.x; pts[4].y = objectRect.y + objectRect.height;
+ dc.SetPen(borderPen);
+ dc.SetBrush(backgroundBrush);
+ dc.DrawPolygon(5, pts);
+ }
+ else if (m_displayStyle == wxRICHTEXT_FIELD_STYLE_END_TAG)
+ {
+ int arrowLength = objectRect.height/2;
+ clientArea.width -= (arrowLength - m_horizontalPadding);
+ clientArea.x += (arrowLength - m_horizontalPadding);
+
+ wxPoint pts[5];
+ pts[0].x = objectRect.x + objectRect.width; pts[0].y = objectRect.y;
+ pts[1].x = objectRect.x + arrowLength; pts[1].y = objectRect.y;
+ pts[2].x = objectRect.x; pts[2].y = objectRect.y + (objectRect.height/2);
+ pts[3].x = objectRect.x + arrowLength; pts[3].y = objectRect.y + objectRect.height;
+ pts[4].x = objectRect.x + objectRect.width; pts[4].y = objectRect.y + objectRect.height;
+ dc.SetPen(borderPen);
+ dc.SetBrush(backgroundBrush);
+ dc.DrawPolygon(5, pts);
+ }
+
+ if (m_bitmap.IsOk())
+ {
+ int x = clientArea.x + (clientArea.width - m_bitmap.GetWidth())/2;
+ int y = clientArea.y + m_verticalPadding;
+ dc.DrawBitmap(m_bitmap, x, y, true);
+
+ if (selection.WithinSelection(obj->GetRange().GetStart(), obj))
+ {
+ wxCheckSetBrush(dc, *wxBLACK_BRUSH);
+ wxCheckSetPen(dc, *wxBLACK_PEN);
+ dc.SetLogicalFunction(wxINVERT);
+ dc.DrawRectangle(wxRect(x, y, m_bitmap.GetWidth(), m_bitmap.GetHeight()));
+ dc.SetLogicalFunction(wxCOPY);
+ }
+ }
+ else
+ {
+ wxString label(m_label);
+ if (label.IsEmpty())
+ label = wxT("??");
+ int w, h, maxDescent;
+ dc.SetFont(m_font);
+ dc.GetTextExtent(m_label, & w, &h, & maxDescent);
+ dc.SetTextForeground(textColour);
+
+ int x = clientArea.x + (clientArea.width - w)/2;
+ int y = clientArea.y + (clientArea.height - (h - maxDescent))/2;
+ dc.DrawText(m_label, x, y);
+ }
+ }
+
+ return true;
+}
+
+bool wxRichTextFieldTypeStandard::Layout(wxRichTextField* obj, wxDC& dc, wxRichTextDrawingContext& context, const wxRect& WXUNUSED(rect), const wxRect& WXUNUSED(parentRect), int style)
+{
+ if (m_displayStyle == wxRICHTEXT_FIELD_STYLE_COMPOSITE)
+ return false; // USe default composite layout
+
+ wxSize size = GetSize(obj, dc, context, style);
+ obj->SetCachedSize(size);
+ obj->SetMinSize(size);
+ obj->SetMaxSize(size);
+ return true;
+}
+
+bool wxRichTextFieldTypeStandard::GetRangeSize(wxRichTextField* obj, const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, wxRichTextDrawingContext& context, int flags, const wxPoint& position, const wxSize& parentSize, wxArrayInt* partialExtents) const
+{
+ if (IsTopLevel(obj))
+ return obj->wxRichTextParagraphLayoutBox::GetRangeSize(range, size, descent, dc, context, flags, position, parentSize);
+ else
+ {
+ wxSize sz = GetSize(obj, dc, context, 0);
+ if (partialExtents)
+ {
+ int lastSize;
+ if (partialExtents->GetCount() > 0)
+ lastSize = (*partialExtents)[partialExtents->GetCount()-1];
+ else
+ lastSize = 0;
+ partialExtents->Add(lastSize + sz.x);
+ }
+ size = sz;
+ return true;
+ }
+}
+
+wxSize wxRichTextFieldTypeStandard::GetSize(wxRichTextField* WXUNUSED(obj), wxDC& dc, wxRichTextDrawingContext& WXUNUSED(context), int WXUNUSED(style)) const
+{
+ int borderSize = 1;
+ int w = 0, h = 0, maxDescent = 0;
+
+ wxSize sz;
+ if (m_bitmap.IsOk())
+ {
+ w = m_bitmap.GetWidth();
+ h = m_bitmap.GetHeight();
+
+ sz = wxSize(w + m_horizontalMargin*2, h + m_verticalMargin*2);
+ }
+ else
+ {
+ wxString label(m_label);
+ if (label.IsEmpty())
+ label = wxT("??");
+ dc.SetFont(m_font);
+ dc.GetTextExtent(label, & w, &h, & maxDescent);
+
+ sz = wxSize(w + m_horizontalPadding*2 + m_horizontalMargin*2, h + m_verticalPadding *2 + m_verticalMargin*2);
+ }
+
+ if (m_displayStyle != wxRICHTEXT_FIELD_STYLE_NO_BORDER)
+ {
+ sz.x += borderSize*2;
+ sz.y += borderSize*2;
+ }
+
+ if (m_displayStyle == wxRICHTEXT_FIELD_STYLE_START_TAG || m_displayStyle == wxRICHTEXT_FIELD_STYLE_END_TAG)
+ {
+ // Add space for the arrow
+ sz.x += (sz.y/2 - m_horizontalPadding);
+ }
+
+ return sz;
+}
+
+IMPLEMENT_DYNAMIC_CLASS(wxRichTextCell, wxRichTextBox)
+
+wxRichTextCell::wxRichTextCell(wxRichTextObject* parent):
+ wxRichTextBox(parent)
+{
+}
+
+/// Draw the item
+bool wxRichTextCell::Draw(wxDC& dc, wxRichTextDrawingContext& context, const wxRichTextRange& range, const wxRichTextSelection& selection, const wxRect& rect, int descent, int style)
+{
+ return wxRichTextBox::Draw(dc, context, range, selection, rect, descent, style);
+}
+
+int wxRichTextCell::HitTest(wxDC& dc, wxRichTextDrawingContext& context, const wxPoint& pt, long& textPosition, wxRichTextObject** obj, wxRichTextObject** contextObj, int flags)
+{
+ int ret = wxRichTextParagraphLayoutBox::HitTest(dc, context, pt, textPosition, obj, contextObj, flags);
+ if (ret != wxRICHTEXT_HITTEST_NONE)
+ {
+ return ret;
+ }
+ else
+ {
+ textPosition = m_ownRange.GetEnd()-1;
+ *obj = this;
+ *contextObj = this;
+ return wxRICHTEXT_HITTEST_AFTER|wxRICHTEXT_HITTEST_OUTSIDE;
+ }
+}
+
+/// Copy
+void wxRichTextCell::Copy(const wxRichTextCell& obj)
+{
+ wxRichTextBox::Copy(obj);
+}
+
+// Edit properties via a GUI
+bool wxRichTextCell::EditProperties(wxWindow* parent, wxRichTextBuffer* buffer)
+{
+ // We need to gather common attributes for all selected cells.
+
+ wxRichTextTable* table = wxDynamicCast(GetParent(), wxRichTextTable);
+ bool multipleCells = false;
+ wxRichTextAttr attr;
+
+ if (table && buffer && buffer->GetRichTextCtrl() && buffer->GetRichTextCtrl()->GetSelection().IsValid() &&
+ buffer->GetRichTextCtrl()->GetSelection().GetContainer() == GetParent())
+ {
+ wxRichTextAttr clashingAttr, absentAttr;
+ const wxRichTextSelection& sel = buffer->GetRichTextCtrl()->GetSelection();
+ size_t i;
+ int selectedCellCount = 0;
+ for (i = 0; i < sel.GetCount(); i++)
+ {
+ const wxRichTextRange& range = sel[i];
+ wxRichTextCell* cell = table->GetCell(range.GetStart());
+ if (cell)
+ {
+ wxRichTextAttr cellStyle = cell->GetAttributes();
+
+ CollectStyle(attr, cellStyle, clashingAttr, absentAttr);
+
+ selectedCellCount ++;
+ }
+ }
+ multipleCells = selectedCellCount > 1;
+ }
+ else
+ {
+ attr = GetAttributes();
+ }
+
+ wxString caption;
+ if (multipleCells)
+ caption = _("Multiple Cell Properties");
+ else
+ caption = _("Cell Properties");
+
+ // We don't want position and floating controls for a cell.
+ wxRichTextSizePage::ShowPositionControls(false);
+ wxRichTextSizePage::ShowFloatingControls(false);
+ wxRichTextSizePage::ShowAlignmentControls(true);
+
+ wxRichTextObjectPropertiesDialog cellDlg(this, wxGetTopLevelParent(parent), wxID_ANY, caption);
+ cellDlg.SetAttributes(attr);
+
+ bool ok = (cellDlg.ShowModal() == wxID_OK);
+
+ wxRichTextSizePage::ShowPositionControls(true);
+ wxRichTextSizePage::ShowFloatingControls(true);
+
+ if (ok)
+ {
+ if (multipleCells)
+ {
+ const wxRichTextSelection& sel = buffer->GetRichTextCtrl()->GetSelection();
+ // Apply the style; we interpret indeterminate attributes as 'don't touch this attribute'
+ // since it may represent clashing attributes across multiple objects.
+ table->SetCellStyle(sel, attr);
+ }
+ else
+ // For a single object, indeterminate attributes set by the user should be reflected in the
+ // actual object style, so pass the wxRICHTEXT_SETSTYLE_RESET flag to assign
+ // the style directly instead of applying (which ignores indeterminate attributes,
+ // leaving them as they were).
+ cellDlg.ApplyStyle(buffer->GetRichTextCtrl(), wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_RESET);
+ return true;
+ }
+ else
+ return false;
+}
+
+// The next 2 methods return span values. Note that the default is 1, not 0
+int wxRichTextCell::GetColspan() const
+{
+ int span = 1;
+ if (GetProperties().HasProperty(wxT("colspan")))
+ {
+ span = GetProperties().GetPropertyLong(wxT("colspan"));
+ }
+
+ return span;
+}
+
+int wxRichTextCell::GetRowspan() const
+{
+ int span = 1;
+ if (GetProperties().HasProperty(wxT("rowspan")))
+ {
+ span = GetProperties().GetPropertyLong(wxT("rowspan"));
+ }
+
+ return span;
+}
+
+WX_DEFINE_OBJARRAY(wxRichTextObjectPtrArrayArray)
+
+IMPLEMENT_DYNAMIC_CLASS(wxRichTextTable, wxRichTextBox)
+
+wxRichTextTable::wxRichTextTable(wxRichTextObject* parent): wxRichTextBox(parent)
+{
+ m_rowCount = 0;
+ m_colCount = 0;
+}
+
+// Draws the object.
+bool wxRichTextTable::Draw(wxDC& dc, wxRichTextDrawingContext& context, const wxRichTextRange& range, const wxRichTextSelection& selection, const wxRect& rect, int descent, int style)
+{
+ wxRichTextBox::Draw(dc, context, range, selection, rect, descent, style);
+
+ int colCount = GetColumnCount();
+ int rowCount = GetRowCount();
+ int col, row;
+ for (col = 0; col < colCount; col++)
+ {
+ for (row = 0; row < rowCount; row++)
+ {
+ if (row == 0 || row == (rowCount-1) || col == 0 || col == (colCount-1))
+ {
+ wxRichTextCell* cell = GetCell(row, col);
+ if (cell && cell->IsShown() && !cell->GetRange().IsOutside(range))
+ {
+ wxRect childRect(cell->GetPosition(), cell->GetCachedSize());
+ wxRichTextAttr attr(cell->GetAttributes());
+ if (row != 0)
+ attr.GetTextBoxAttr().GetBorder().GetTop().Reset();
+ if (row != (rowCount-1))
+ attr.GetTextBoxAttr().GetBorder().GetBottom().Reset();
+ if (col != 0)
+ attr.GetTextBoxAttr().GetBorder().GetLeft().Reset();
+ if (col != (colCount-1))
+ attr.GetTextBoxAttr().GetBorder().GetRight().Reset();
+
+ if (attr.GetTextBoxAttr().GetBorder().IsValid())
+ {
+ wxRect boxRect(cell->GetPosition(), cell->GetCachedSize());
+ wxRect marginRect = boxRect;
+ wxRect contentRect, borderRect, paddingRect, outlineRect;
+
+ cell->GetBoxRects(dc, GetBuffer(), attr, marginRect, borderRect, contentRect, paddingRect, outlineRect);
+ cell->DrawBorder(dc, GetBuffer(), attr.GetTextBoxAttr().GetBorder(), borderRect);
+ }
+ }
+ }
+ }
+ }
+
+ return true;
+}
+
+ // Helper function for Layout() that clears the space needed by a cell with rowspan > 1
+int GetRowspanDisplacement(const wxRichTextTable* table, int row, int col, int paddingX, const wxArrayInt& colWidths)
+{
+ // If one or more cells above-left of this one has rowspan > 1, the affected cells below it
+ // will have been hidden and have width 0. As a result they are ignored by the layout algorithm,
+ // and all cells to their right are effectively shifted left. As a result there's no hole for
+ // the spanning cell to fill.
+ // So search back along the current row for hidden cells. However there's also the annoying issue of a
+ // rowspanning cell that also has colspam. So we can't rely on the rowspanning cell being directly above
+ // the first hidden one we come to. We also can't rely on a cell being hidden only by one type of span;
+ // there's nothing to stop a cell being hidden by colspan, and then again hidden from above by rowspan.
+ // The answer is to look above each hidden cell in turn, which I think covers all bases.
+ int deltaX = 0;
+ for (int prevcol = 0; prevcol < col; ++prevcol)
+ {
+ if (!table->GetCell(row, prevcol)->IsShown())
+ {
+ // We've found a hidden cell. If it's hidden because of colspan to its left, it's
+ // already been taken into account; but not if there's a rowspanning cell above
+ for (int prevrow = row-1; prevrow >= 0; --prevrow)
+ {
+ wxRichTextCell* cell = table->GetCell(prevrow, prevcol);
+ if (cell && cell->IsShown())
+ {
+ int rowSpan = cell->GetRowspan();
+ if (rowSpan > 1 && rowSpan > (row-prevrow))
+ {
+ // There is a rowspanning cell above above the hidden one, so we need
+ // to right-shift the index cell by this column's width. Furthermore,
+ // if the cell also colspans, we need to shift by all affected columns
+ for (int colSpan = 0; colSpan < cell->GetColspan(); ++colSpan)
+ deltaX += (colWidths[prevcol+colSpan] + paddingX);
+ break;
+ }
+ }
+ }
+ }
+ }
+ return deltaX;
+}
+
+ // Helper function for Layout() that expands any cell with rowspan > 1
+void ExpandCellsWithRowspan(const wxRichTextTable* table, int paddingY, int& bottomY, wxDC& dc, wxRichTextDrawingContext& context, const wxRect& availableSpace, int style)
+{
+ // This is called when the table's cell layout is otherwise complete.
+ // For any cell with rowspan > 1, expand downwards into the row(s) below.
+
+ // Start by finding the current 'y' of the top of each row, plus the bottom of the available area for cells.
+ // Deduce this from the top of a visible cell in the row below. (If none are visible, the row will be invisible anyway and can be ignored.)
+ const int rowCount = table->GetRowCount();
+ const int colCount = table->GetColumnCount();
+ wxArrayInt rowTops;
+ rowTops.Add(0, rowCount+1);
+ int row;
+ for (row = 0; row < rowCount; ++row)
+ {
+ for (int column = 0; column < colCount; ++column)
+ {
+ wxRichTextCell* cell = table->GetCell(row, column);
+ if (cell && cell->IsShown())
+ {
+ rowTops[row] = cell->GetPosition().y;
+ break;
+ }
+ }
+ }
+ rowTops[rowCount] = bottomY + paddingY; // The table bottom, which was passed to us
+
+ bool needsRelay = false;
+
+ for (row = 0; row < rowCount-1; ++row) // -1 as the bottom row can't rowspan
+ {
+ for (int col = 0; col < colCount; ++col)
+ {
+ wxRichTextCell* cell = table->GetCell(row, col);
+ if (cell && cell->IsShown())
+ {
+ int span = cell->GetRowspan();
+ if (span > 1)
+ {
+ span = wxMin(span, rowCount-row); // Don't try to span below the table!
+ if (span < 2)
+ continue;
+
+ int availableHeight = rowTops[row+span] - rowTops[row] - paddingY;
+ wxSize newSize = wxSize(cell->GetCachedSize().GetWidth(), availableHeight);
+ wxRect availableCellSpace = wxRect(cell->GetPosition(), newSize);
+ cell->Invalidate(wxRICHTEXT_ALL);
+ cell->Layout(dc, context, availableCellSpace, availableSpace, style);
+ // Ensure there's room in the span to display its contents, else it'll overwrite lower rows
+ int overhang = cell->GetCachedSize().GetHeight() - availableHeight;
+ cell->SetCachedSize(newSize);
+
+ if (overhang > 0)
+ {
+ // There are 3 things to get right:
+ // 1) The easiest is the rows below the span: they need to be downshifted by the overhang, and so does the table bottom itself
+ // 2) The rows within the span, including the one holding this cell, need to be deepened by their share of the overhang
+ // e.g. if rowspan == 3, each row should increase in depth by 1/3rd of the overhang.
+ // 3) The cell with the rowspan shouldn't be touched in 2); its height will be set to the whole span later.
+ int deltaY = overhang / span;
+ int spare = overhang % span;
+
+ // Each row in the span needs to by deepened by its share of the overhang (give the first row any spare).
+ // This is achieved by increasing the value stored in the following row's rowTops
+ for (int spannedRows = 0; spannedRows < span; ++spannedRows)
+ {
+ rowTops[row+spannedRows+1] += ((deltaY * (spannedRows+1)) + (spannedRows == 0 ? spare:0));
+ }
+
+ // Any rows below the span need shifting down
+ for (int rowsBelow = row + span+1; rowsBelow <= rowCount; ++rowsBelow)
+ {
+ rowTops[rowsBelow] += overhang;
+ }
+
+ needsRelay = true;
+ }
+ }
+ }
+ }
+ }
+
+ if (!needsRelay)
+ return;
+
+ // There were overflowing rowspanning cells, so layout yet again to make the increased row depths show
+ for (row = 0; row < rowCount; ++row)
+ {
+ for (int col = 0; col < colCount; ++col)
+ {
+ wxRichTextCell* cell = table->GetCell(row, col);
+ if (cell && cell->IsShown())
+ {
+ wxPoint position(cell->GetPosition().x, rowTops[row]);
+
+ // GetRowspan() will usually return 1, but may be greater
+ wxSize size(cell->GetCachedSize().GetWidth(), rowTops[row + cell->GetRowspan()] - rowTops[row] - paddingY);
+
+ wxRect availableCellSpace = wxRect(position, size);
+ cell->Invalidate(wxRICHTEXT_ALL);
+ cell->Layout(dc, context, availableCellSpace, availableSpace, style);
+ cell->SetCachedSize(size);
+ }
+ }
+
+ bottomY = rowTops[rowCount] - paddingY;
+ }
+}
+
+// Lays the object out. rect is the space available for layout. Often it will
+// be the specified overall space for this object, if trying to constrain
+// layout to a particular size, or it could be the total space available in the
+// parent. rect is the overall size, so we must subtract margins and padding.
+// to get the actual available space.
+bool wxRichTextTable::Layout(wxDC& dc, wxRichTextDrawingContext& context, const wxRect& rect, const wxRect& WXUNUSED(parentRect), int style)
+{
+ SetPosition(rect.GetPosition());
+
+ // The meaty bit. Calculate sizes of all cells and rows. Try to use
+ // minimum size if within alloted size, then divide up remaining size
+ // between rows/cols.
+
+ double scale = 1.0;
+ wxRichTextBuffer* buffer = GetBuffer();
+ if (buffer) scale = buffer->GetScale();
+
+ wxRect availableSpace = GetAvailableContentArea(dc, context, rect);
+ wxTextAttrDimensionConverter converter(dc, scale, availableSpace.GetSize());
+
+ wxRichTextAttr attr(GetAttributes());
+ context.ApplyVirtualAttributes(attr, this);
+
+ bool tableHasPercentWidth = (attr.GetTextBoxAttr().GetWidth().GetUnits() == wxTEXT_ATTR_UNITS_PERCENTAGE);
+ // If we have no fixed table size, and assuming we're not pushed for
+ // space, then we don't have to try to stretch the table to fit the contents.
+ bool stretchToFitTableWidth = tableHasPercentWidth;
+
+ int tableWidth = rect.width;
+ if (attr.GetTextBoxAttr().GetWidth().IsValid() && !tableHasPercentWidth)
+ {
+ tableWidth = converter.GetPixels(attr.GetTextBoxAttr().GetWidth());
+
+ // Fixed table width, so we do want to stretch columns out if necessary.
+ stretchToFitTableWidth = true;
+
+ // Shouldn't be able to exceed the size passed to this function
+ tableWidth = wxMin(rect.width, tableWidth);
+ }
+
+ // Get internal padding
+ int paddingLeft = 0, paddingTop = 0;
+ if (attr.GetTextBoxAttr().GetPadding().GetLeft().IsValid())
+ paddingLeft = converter.GetPixels(attr.GetTextBoxAttr().GetPadding().GetLeft());
+ if (attr.GetTextBoxAttr().GetPadding().GetTop().IsValid())
+ paddingTop = converter.GetPixels(attr.GetTextBoxAttr().GetPadding().GetTop());
+
+ // Assume that left and top padding are also used for inter-cell padding.
+ int paddingX = paddingLeft;
+ int paddingY = paddingTop;
+
+ int totalLeftMargin = 0, totalRightMargin = 0, totalTopMargin = 0, totalBottomMargin = 0;
+ GetTotalMargin(dc, buffer, attr, totalLeftMargin, totalRightMargin, totalTopMargin, totalBottomMargin);
+
+ // Internal table width - the area for content
+ int internalTableWidth = tableWidth - totalLeftMargin - totalRightMargin;
+
+ int rowCount = m_cells.GetCount();
+ if (m_colCount == 0 || rowCount == 0)
+ {
+ wxRect overallRect(rect.x, rect.y, totalLeftMargin + totalRightMargin, totalTopMargin + totalBottomMargin);
+ SetCachedSize(overallRect.GetSize());
+
+ // Zero content size
+ SetMinSize(overallRect.GetSize());
+ SetMaxSize(GetMinSize());
+ return true;
+ }
+
+ // The final calculated widths
+ wxArrayInt colWidths;
+ colWidths.Add(0, m_colCount);
+
+ wxArrayInt absoluteColWidths;
+ absoluteColWidths.Add(0, m_colCount);
+
+ wxArrayInt percentageColWidths;
+ percentageColWidths.Add(0, m_colCount);
+ // wxArrayInt percentageColWidthsSpanning(m_colCount);
+ // These are only relevant when the first column contains spanning information.
+ // wxArrayInt columnSpans(m_colCount); // Each contains 1 for non-spanning cell, > 1 for spanning cell.
+ wxArrayInt maxColWidths;
+ maxColWidths.Add(0, m_colCount);
+ wxArrayInt minColWidths;
+ minColWidths.Add(0, m_colCount);
+
+ wxSize tableSize(tableWidth, 0);
+
+ int i, j, k;
+
+ for (i = 0; i < m_colCount; i++)
+ {
+ absoluteColWidths[i] = 0;
+ // absoluteColWidthsSpanning[i] = 0;
+ percentageColWidths[i] = -1;
+ // percentageColWidthsSpanning[i] = -1;
+ colWidths[i] = 0;
+ maxColWidths[i] = 0;
+ minColWidths[i] = 0;
+ // columnSpans[i] = 1;
+ }
+
+ // (0) Determine which cells are visible according to spans
+ // 1 2 3 4 5
+ // __________________
+ // | | | | | 1
+ // |------| |----|
+ // |------| | | 2
+ // |------| | | 3
+ // |------------------|
+ // |__________________| 4
+
+ // To calculate cell visibility:
+ // First find all spanning cells. Build an array of span records with start x, y and end x, y.
+ // Then for each cell, test whether we're within one of those cells, and unless we're at the start of
+ // that cell, hide the cell.
+
+ // We can also use this array to match the size of spanning cells to the grid. Or just do
+ // this when we iterate through all cells.
+
+ // 0.1: add spanning cells to an array
+ wxRichTextRectArray rectArray;
+ for (j = 0; j < m_rowCount; j++)
+ {
+ for (i = 0; i < m_colCount; i++)
+ {
+ wxRichTextCell* cell = GetCell(j, i);
+ int colSpan = cell->GetColspan();
+ int rowSpan = cell->GetRowspan();
+ if (colSpan > 1 || rowSpan > 1)
+ {
+ rectArray.Add(wxRect(i, j, colSpan, rowSpan));
+ }
+ }
+ }
+ // 0.2: find which cells are subsumed by a spanning cell
+ for (j = 0; j < m_rowCount; j++)
+ {
+ for (i = 0; i < m_colCount; i++)
+ {
+ wxRichTextCell* cell = GetCell(j, i);
+ if (rectArray.GetCount() == 0)
+ {
+ cell->Show(true);
+ }
+ else
+ {
+ int colSpan = cell->GetColspan();
+ int rowSpan = cell->GetRowspan();
+
+ if (colSpan > 1 || rowSpan > 1)
+ {
+ // Assume all spanning cells are shown
+ cell->Show(true);
+ }
+ else
+ {
+ bool shown = true;
+ for (k = 0; k < (int) rectArray.GetCount(); k++)
+ {
+ if (rectArray[k].Contains(wxPoint(i, j)))
+ {
+ shown = false;
+ break;
+ }
+ }
+ cell->Show(shown);
+ }
+ }
+ }
+ }
+
+ // Find the first spanned cell in each row that spans the most columns and doesn't
+ // overlap with a spanned cell starting at a previous column position.
+ // This means we need to keep an array of rects so we can check. However
+ // it does also mean that some spans simply may not be taken into account
+ // where there are different spans happening on different rows. In these cases,
+ // they will simply be as wide as their constituent columns.
+
+ // (1) Do an initial layout for all cells to get minimum and maximum size, and get
+ // the absolute or percentage width of each column.
+
+ for (j = 0; j < m_rowCount; j++)
+ {
+ // First get the overall margins so we can calculate percentage widths based on
+ // the available content space for all cells on the row
+
+ int overallRowContentMargin = 0;
+ int visibleCellCount = 0;
+
+ for (i = 0; i < m_colCount; i++)
+ {
+ wxRichTextBox* cell = GetCell(j, i);
+ if (cell->IsShown())
+ {
+ int cellTotalLeftMargin = 0, cellTotalRightMargin = 0, cellTotalTopMargin = 0, cellTotalBottomMargin = 0;
+ GetTotalMargin(dc, buffer, cell->GetAttributes(), cellTotalLeftMargin, cellTotalRightMargin, cellTotalTopMargin, cellTotalBottomMargin);
+
+ overallRowContentMargin += (cellTotalLeftMargin + cellTotalRightMargin);
+ visibleCellCount ++;
+ }
+ }
+
+ // Add in inter-cell padding
+ overallRowContentMargin += ((visibleCellCount-1) * paddingX);
+
+ int rowContentWidth = internalTableWidth - overallRowContentMargin;
+ wxSize rowTableSize(rowContentWidth, 0);
+ wxTextAttrDimensionConverter converter(dc, scale, rowTableSize);
+
+ for (i = 0; i < m_colCount; i++)
+ {
+ wxRichTextCell* cell = GetCell(j, i);
+ if (cell->IsShown())
+ {
+ int colSpan = cell->GetColspan();
+
+ // Lay out cell to find min/max widths
+ cell->Invalidate(wxRICHTEXT_ALL);
+ cell->Layout(dc, context, availableSpace, availableSpace, style);
+
+ if (colSpan == 1)
+ {
+ int absoluteCellWidth = -1;
+ int percentageCellWidth = -1;
+
+ // I think we need to calculate percentages from the internal table size,
+ // minus the padding between cells which we'll need to calculate from the
+ // (number of VISIBLE cells - 1)*paddingX. Then percentages that add up to 100%
+ // will add up to 100%. In CSS, the width specifies the cell's content rect width,
+ // so if we want to conform to that we'll need to add in the overall cell margins.
+ // However, this will make it difficult to specify percentages that add up to
+ // 100% and still fit within the table width.
+ // Let's say two cells have 50% width. They have 10 pixels of overall margin each.
+ // The table content rect is 500 pixels and the inter-cell padding is 20 pixels.
+ // If we're using internal content size for the width, we would calculate the
+ // the overall cell width for n cells as:
+ // (500 - 20*(n-1) - overallCellMargin1 - overallCellMargin2 - ...) * percentage / 100
+ // + thisOverallCellMargin
+ // = 500 - 20 - 10 - 10) * 0.5 + 10 = 240 pixels overall cell width.
+ // Adding this back, we get 240 + 240 + 20 = 500 pixels.
+
+ if (cell->GetAttributes().GetTextBoxAttr().GetWidth().IsValid())
+ {
+ int w = converter.GetPixels(cell->GetAttributes().GetTextBoxAttr().GetWidth());
+ if (cell->GetAttributes().GetTextBoxAttr().GetWidth().GetUnits() == wxTEXT_ATTR_UNITS_PERCENTAGE)
+ {
+ percentageCellWidth = w;
+ }
+ else
+ {
+ absoluteCellWidth = w;
+ }
+ // Override absolute width with minimum width if necessary
+ if (cell->GetMinSize().x > 0 && absoluteCellWidth !=1 && cell->GetMinSize().x > absoluteCellWidth)
+ absoluteCellWidth = cell->GetMinSize().x;
+ }
+
+ if (absoluteCellWidth != -1)
+ {
+ if (absoluteCellWidth > absoluteColWidths[i])
+ absoluteColWidths[i] = absoluteCellWidth;
+ }
+
+ if (percentageCellWidth != -1)
+ {
+ if (percentageCellWidth > percentageColWidths[i])
+ percentageColWidths[i] = percentageCellWidth;
+ }
+
+ if (colSpan == 1 && cell->GetMinSize().x && cell->GetMinSize().x > minColWidths[i])
+ minColWidths[i] = cell->GetMinSize().x;
+ if (colSpan == 1 && cell->GetMaxSize().x && cell->GetMaxSize().x > maxColWidths[i])
+ maxColWidths[i] = cell->GetMaxSize().x;
+ }
+ }
+ }
+ }
+
+ // (2) Allocate initial column widths from minimum widths, absolute values and proportions
+ // TODO: simply merge this into (1).
+ for (i = 0; i < m_colCount; i++)
+ {
+ if (absoluteColWidths[i] > 0)
+ {
+ colWidths[i] = absoluteColWidths[i];
+ }
+ else if (percentageColWidths[i] > 0)
+ {
+ colWidths[i] = percentageColWidths[i];
+
+ // This is rubbish - we calculated the absolute widths from percentages, so
+ // we can't do it again here.
+ //colWidths[i] = (int) (double(percentageColWidths[i]) * double(tableWidth) / 100.0 + 0.5);
+ }
+ }
+
+ // (3) Process absolute or proportional widths of spanning columns,
+ // now that we know what our fixed column widths are going to be.
+ // Spanned cells will try to adjust columns so the span will fit.
+ // Even existing fixed column widths can be expanded if necessary.
+ // Actually, currently fixed columns widths aren't adjusted; instead,
+ // the algorithm favours earlier rows and adjusts unspecified column widths
+ // the first time only. After that, we can't know whether the column has been
+ // specified explicitly or not. (We could make a note if necessary.)
+ for (j = 0; j < m_rowCount; j++)
+ {
+ // First get the overall margins so we can calculate percentage widths based on
+ // the available content space for all cells on the row
+
+ int overallRowContentMargin = 0;
+ int visibleCellCount = 0;
+
+ for (i = 0; i < m_colCount; i++)
+ {
+ wxRichTextBox* cell = GetCell(j, i);
+ if (cell->IsShown())
+ {
+ int cellTotalLeftMargin = 0, cellTotalRightMargin = 0, cellTotalTopMargin = 0, cellTotalBottomMargin = 0;
+ GetTotalMargin(dc, buffer, cell->GetAttributes(), cellTotalLeftMargin, cellTotalRightMargin, cellTotalTopMargin, cellTotalBottomMargin);
+
+ overallRowContentMargin += (cellTotalLeftMargin + cellTotalRightMargin);
+ visibleCellCount ++;
+ }
+ }
+
+ // Add in inter-cell padding
+ overallRowContentMargin += ((visibleCellCount-1) * paddingX);
+
+ int rowContentWidth = internalTableWidth - overallRowContentMargin;
+ wxSize rowTableSize(rowContentWidth, 0);
+ wxTextAttrDimensionConverter converter(dc, scale, rowTableSize);
+
+ for (i = 0; i < m_colCount; i++)
+ {
+ wxRichTextCell* cell = GetCell(j, i);
+ if (cell->IsShown())
+ {
+ int colSpan = cell->GetColspan();
+ if (colSpan > 1)
+ {
+ int spans = wxMin(colSpan, m_colCount - i);
+ int cellWidth = 0;
+ if (spans > 0)
+ {
+ if (cell->GetAttributes().GetTextBoxAttr().GetWidth().IsValid())
+ {
+ cellWidth = converter.GetPixels(cell->GetAttributes().GetTextBoxAttr().GetWidth());
+ // Override absolute width with minimum width if necessary
+ if (cell->GetMinSize().x > 0 && cellWidth !=1 && cell->GetMinSize().x > cellWidth)
+ cellWidth = cell->GetMinSize().x;
+ }
+ else
+ {
+ // Do we want to do this? It's the only chance we get to
+ // use the cell's min/max sizes, so we need to work out
+ // how we're going to balance the unspecified spanning cell
+ // width with the possibility more-constrained constituent cell widths.
+ // Say there's a tiny bitmap giving it a max width of 10 pixels. We
+ // don't want to constraint all the spanned columns to fit into this cell.
+ // OK, let's say that if any of the constituent columns don't fit,
+ // then we simply stop constraining the columns; instead, we'll just fit the spanning
+ // cells to the columns later.
+ cellWidth = cell->GetMinSize().x;
+ if (cell->GetMaxSize().x > cellWidth)
+ cellWidth = cell->GetMaxSize().x;
+ }
+
+ // Subtract the padding between cells
+ int spanningWidth = cellWidth;
+ spanningWidth -= paddingX * (spans-1);
+
+ if (spanningWidth > 0)
+ {
+ // Now share the spanning width between columns within that span
+ // TODO: take into account min widths of columns within the span
+ int spanningWidthLeft = spanningWidth;
+ int stretchColCount = 0;
+ for (k = i; k < (i+spans); k++)
+ {
+ if (colWidths[k] > 0) // absolute or proportional width has been specified
+ spanningWidthLeft -= colWidths[k];
+ else
+ stretchColCount ++;
+ }
+ // Now divide what's left between the remaining columns
+ int colShare = 0;
+ if (stretchColCount > 0)
+ colShare = spanningWidthLeft / stretchColCount;
+ int colShareRemainder = spanningWidthLeft - (colShare * stretchColCount);
+
+ // If fixed-width columns are currently too big, then we'll later
+ // stretch the spanned cell to fit.
+
+ if (spanningWidthLeft > 0)
+ {
+ for (k = i; k < (i+spans); k++)
+ {
+ if (colWidths[k] <= 0) // absolute or proportional width has not been specified
+ {
+ int newWidth = colShare;
+ if (k == (i+spans-1))
+ newWidth += colShareRemainder; // ensure all pixels are filled
+ colWidths[k] = newWidth;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // (4) Next, share any remaining space out between columns that have not yet been calculated.
+ // TODO: take into account min widths of columns within the span
+ int tableWidthMinusPadding = internalTableWidth - (m_colCount-1)*paddingX;
+ int widthLeft = tableWidthMinusPadding;
+ int stretchColCount = 0;
+ for (i = 0; i < m_colCount; i++)
+ {
+ // Subtract min width from width left, then
+ // add the colShare to the min width
+ if (colWidths[i] > 0) // absolute or proportional width has been specified
+ widthLeft -= colWidths[i];
+ else
+ {
+ if (minColWidths[i] > 0)
+ widthLeft -= minColWidths[i];
+
+ stretchColCount ++;
+ }
+ }
+
+ // Now divide what's left between the remaining columns
+ int colShare = 0;
+ if (stretchColCount > 0)
+ colShare = widthLeft / stretchColCount;
+ int colShareRemainder = widthLeft - (colShare * stretchColCount);
+
+ // Check we don't have enough space, in which case shrink all columns, overriding
+ // any absolute/proportional widths
+ // TODO: actually we would like to divide up the shrinkage according to size.
+ // How do we calculate the proportions that will achieve this?
+ // Could first choose an arbitrary value for stretching cells, and then calculate
+ // factors to multiply each width by.
+ // TODO: want to record this fact and pass to an iteration that tries e.g. min widths
+ if (widthLeft < 0 || (stretchToFitTableWidth && (stretchColCount == 0)))
+ {
+ colShare = tableWidthMinusPadding / m_colCount;
+ colShareRemainder = tableWidthMinusPadding - (colShare * m_colCount);
+ for (i = 0; i < m_colCount; i++)
+ {
+ colWidths[i] = 0;
+ minColWidths[i] = 0;
+ }
+ }
+
+ // We have to adjust the columns if either we need to shrink the
+ // table to fit the parent/table width, or we explicitly set the
+ // table width and need to stretch out the table.
+ if (widthLeft < 0 || stretchToFitTableWidth)
+ {
+ for (i = 0; i < m_colCount; i++)
+ {
+ if (colWidths[i] <= 0) // absolute or proportional width has not been specified
+ {
+ if (minColWidths[i] > 0)
+ colWidths[i] = minColWidths[i] + colShare;
+ else
+ colWidths[i] = colShare;
+ if (i == (m_colCount-1))
+ colWidths[i] += colShareRemainder; // ensure all pixels are filled
+ }
+ }
+ }
+
+ // TODO: if spanned cells have no specified or max width, make them the
+ // as big as the columns they span. Do this for all spanned cells in all
+ // rows, of course. Size any spanned cells left over at the end - even if they
+ // have width > 0, make sure they're limited to the appropriate column edge.
+
+
+/*
+ Sort out confusion between content width
+ and overall width later. For now, assume we specify overall width.
+
+ So, now we've laid out the table to fit into the given space
+ and have used specified widths and minimum widths.
+
+ Now we need to consider how we will try to take maximum width into account.
+
+*/
+
+ // (??) TODO: take max width into account
+
+ // (6) Lay out all cells again with the current values
+
+ int maxRight = 0;
+ int y = availableSpace.y;
+ for (j = 0; j < m_rowCount; j++)
+ {
+ int x = availableSpace.x; // TODO: take into account centering etc.
+ int maxCellHeight = 0;
+ int maxSpecifiedCellHeight = 0;
+
+ wxArrayInt actualWidths;
+ actualWidths.Add(0, m_colCount);
+
+ wxTextAttrDimensionConverter converter(dc, scale);
+ for (i = 0; i < m_colCount; i++)
+ {
+ wxRichTextCell* cell = GetCell(j, i);
+ if (cell->IsShown())
+ {
+ // Get max specified cell height
+ // Don't handle percentages for height
+ if (cell->GetAttributes().GetTextBoxAttr().GetHeight().IsValid() && cell->GetAttributes().GetTextBoxAttr().GetHeight().GetUnits() != wxTEXT_ATTR_UNITS_PERCENTAGE)
+ {
+ int h = converter.GetPixels(cell->GetAttributes().GetTextBoxAttr().GetHeight());
+ if (h > maxSpecifiedCellHeight)
+ maxSpecifiedCellHeight = h;
+ }
+
+ if (colWidths[i] > 0) // absolute or proportional width has been specified
+ {
+ int colSpan = cell->GetColspan();
+ wxRect availableCellSpace;
+
+ // Take into account spans
+ if (colSpan > 1)
+ {
+ // Calculate the size of this spanning cell from its constituent columns
+ int xx = 0;
+ int spans = wxMin(colSpan, m_colCount - i);
+ for (k = i; k < (i+spans); k++)
+ {
+ if (k != i)
+ xx += paddingX;
+ xx += colWidths[k];
+ }
+ availableCellSpace = wxRect(x, y, xx, -1);
+ }
+ else
+ availableCellSpace = wxRect(x, y, colWidths[i], -1);
+
+ // Store actual width so we can force cell to be the appropriate width on the final loop
+ actualWidths[i] = availableCellSpace.GetWidth();
+
+ // We now need to shift right by the width of any rowspanning cells above-left of us
+ int deltaX = GetRowspanDisplacement(this, j, i, paddingX, colWidths);
+ availableCellSpace.SetX(availableCellSpace.GetX() + deltaX);
+
+ // Lay out cell
+ cell->Invalidate(wxRICHTEXT_ALL);
+ cell->Layout(dc, context, availableCellSpace, availableSpace, style);
+
+ // TODO: use GetCachedSize().x to compute 'natural' size
+
+ x += (availableCellSpace.GetWidth() + paddingX);
+ if ((cell->GetCachedSize().y > maxCellHeight) && (cell->GetRowspan() < 2))
+ maxCellHeight = cell->GetCachedSize().y;
+ }
+ }
+ }
+
+ maxCellHeight = wxMax(maxCellHeight, maxSpecifiedCellHeight);
+
+ for (i = 0; i < m_colCount; i++)
+ {
+ wxRichTextCell* cell = GetCell(j, i);
+ if (cell->IsShown())
+ {
+ wxRect availableCellSpace = wxRect(cell->GetPosition(), wxSize(actualWidths[i], maxCellHeight));
+ // Lay out cell with new height
+ cell->Invalidate(wxRICHTEXT_ALL);
+ cell->Layout(dc, context, availableCellSpace, availableSpace, style);
+
+ // Make sure the cell size really is the appropriate size,
+ // not the calculated box size
+ cell->SetCachedSize(wxSize(actualWidths[i], maxCellHeight));
+
+ maxRight = wxMax(maxRight, cell->GetPosition().x + cell->GetCachedSize().x);
+ }
+ }
+
+ y += maxCellHeight;
+ if (j < (m_rowCount-1))
+ y += paddingY;
+ }
+
+ // Finally we need to expand any cell with rowspan > 1. We couldn't earlier; lower rows' heights weren't known
+ ExpandCellsWithRowspan(this, paddingY, y, dc, context, availableSpace, style);
+
+ // We need to add back the margins etc.
+ {
+ wxRect marginRect, borderRect, contentRect, paddingRect, outlineRect;
+ contentRect = wxRect(wxPoint(0, 0), wxSize(maxRight - availableSpace.x, y - availableSpace.y));
+ GetBoxRects(dc, GetBuffer(), attr, marginRect, borderRect, contentRect, paddingRect, outlineRect);
+ SetCachedSize(marginRect.GetSize());
+ }
+
+ // TODO: calculate max size
+ {
+ SetMaxSize(GetCachedSize());
+ }
+
+ // TODO: calculate min size
+ {
+ SetMinSize(GetCachedSize());
+ }
+
+ // TODO: currently we use either a fixed table width or the parent's size.
+ // We also want to be able to calculate the table width from its content,
+ // whether using fixed column widths or cell content min/max width.
+ // Probably need a boolean flag to say whether we need to stretch cells
+ // to fit the table width, or to simply use min/max cell widths. The
+ // trouble with this is that if cell widths are not specified, they
+ // will be tiny; we could use arbitrary defaults but this seems unsatisfactory.
+ // Anyway, ignoring that problem, we probably need to factor layout into a function
+ // that can can calculate the maximum unconstrained layout in case table size is
+ // not specified. Then LayoutToBestSize() can choose to use either parent size to
+ // constrain Layout(), or the previously-calculated max size to constraint layout.
+
+ return true;
+}
+
+// Finds the absolute position and row height for the given character position
+bool wxRichTextTable::FindPosition(wxDC& dc, wxRichTextDrawingContext& context, long index, wxPoint& pt, int* height, bool forceLineStart)
+{
+ wxRichTextCell* child = GetCell(index+1);
+ if (child)
+ {
+ // Find the position at the start of the child cell, since the table doesn't
+ // have any caret position of its own.
+ return child->FindPosition(dc, context, -1, pt, height, forceLineStart);
+ }
+ else
+ return false;
+}
+
+// Get the cell at the given character position (in the range of the table).
+wxRichTextCell* wxRichTextTable::GetCell(long pos) const
+{
+ int row = 0, col = 0;
+ if (GetCellRowColumnPosition(pos, row, col))
+ {
+ return GetCell(row, col);
+ }
+ else
+ return NULL;
+}
+
+// Get the row/column for a given character position
+bool wxRichTextTable::GetCellRowColumnPosition(long pos, int& row, int& col) const
+{
+ if (m_colCount == 0 || m_rowCount == 0)
+ return false;
+
+ row = (int) (pos / m_colCount);
+ col = pos - (row * m_colCount);
+
+ wxASSERT(row < m_rowCount && col < m_colCount);
+
+ if (row < m_rowCount && col < m_colCount)
+ return true;
+ else
+ return false;
+}
+
+// Calculate range, taking row/cell ordering into account instead of relying
+// on list ordering.
+void wxRichTextTable::CalculateRange(long start, long& end)
+{
+ long current = start;
+ long lastEnd = current;
+
+ if (IsTopLevel())
+ {
+ current = 0;
+ lastEnd = 0;
+ }
+
+ int i, j;
+ for (i = 0; i < m_rowCount; i++)
+ {
+ for (j = 0; j < m_colCount; j++)
+ {
+ wxRichTextCell* child = GetCell(i, j);
+ if (child)
+ {
+ long childEnd = 0;
+
+ child->CalculateRange(current, childEnd);
+
+ lastEnd = childEnd;
+ current = childEnd + 1;
+ }
+ }
+ }
+
+ // A top-level object always has a range of size 1,
+ // because its children don't count at this level.
+ end = start;
+ m_range.SetRange(start, start);
+
+ // An object with no children has zero length
+ if (m_children.GetCount() == 0)
+ lastEnd --;
+ m_ownRange.SetRange(0, lastEnd);
+}
+
+// Gets the range size.
+bool wxRichTextTable::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, wxRichTextDrawingContext& context, int flags, const wxPoint& position, const wxSize& parentSize, wxArrayInt* partialExtents) const
+{
+ return wxRichTextBox::GetRangeSize(range, size, descent, dc, context, flags, position, parentSize, partialExtents);
+}
+
+// Deletes content in the given range.
+bool wxRichTextTable::DeleteRange(const wxRichTextRange& WXUNUSED(range))
+{
+ // TODO: implement deletion of cells
+ return true;
+}
+
+// Gets any text in this object for the given range.
+wxString wxRichTextTable::GetTextForRange(const wxRichTextRange& range) const
+{
+ return wxRichTextBox::GetTextForRange(range);
+}
+
+// Copies this object.
+void wxRichTextTable::Copy(const wxRichTextTable& obj)
+{
+ wxRichTextBox::Copy(obj);
+
+ ClearTable();
+
+ m_rowCount = obj.m_rowCount;
+ m_colCount = obj.m_colCount;
+
+ m_cells.Add(wxRichTextObjectPtrArray(), m_rowCount);
+
+ int i, j;
+ for (i = 0; i < m_rowCount; i++)
+ {
+ wxRichTextObjectPtrArray& colArray = m_cells[i];
+ for (j = 0; j < m_colCount; j++)
+ {
+ wxRichTextCell* cell = wxDynamicCast(obj.GetCell(i, j)->Clone(), wxRichTextCell);
+ AppendChild(cell);
+
+ colArray.Add(cell);
+ }
+ }
+}
+
+void wxRichTextTable::ClearTable()
+{
+ m_cells.Clear();
+ DeleteChildren();
+ m_rowCount = 0;
+ m_colCount = 0;
+}
+
+bool wxRichTextTable::CreateTable(int rows, int cols)
+{
+ ClearTable();
+
+ wxRichTextAttr cellattr;
+ cellattr.SetTextColour(GetBasicStyle().GetTextColour());
+
+ m_rowCount = rows;
+ m_colCount = cols;
+
+ m_cells.Add(wxRichTextObjectPtrArray(), rows);
+
+ int i, j;
+ for (i = 0; i < rows; i++)
+ {
+ wxRichTextObjectPtrArray& colArray = m_cells[i];
+ for (j = 0; j < cols; j++)
+ {
+ wxRichTextCell* cell = new wxRichTextCell;
+ cell->GetAttributes() = cellattr;
+
+ AppendChild(cell);
+ cell->AddParagraph(wxEmptyString);
+
+ colArray.Add(cell);
+ }
+ }
+
+ return true;
+}
+
+wxRichTextCell* wxRichTextTable::GetCell(int row, int col) const
+{
+ wxASSERT(row < m_rowCount);
+ wxASSERT(col < m_colCount);
+
+ if (row < m_rowCount && col < m_colCount)
+ {
+ wxRichTextObjectPtrArray& colArray = m_cells[row];
+ wxRichTextObject* obj = colArray[col];
+ return wxDynamicCast(obj, wxRichTextCell);
+ }
+ else
+ return NULL;
+}
+
+// Returns a selection object specifying the selections between start and end character positions.
+// For example, a table would deduce what cells (of range length 1) are selected when dragging across the table.
+wxRichTextSelection wxRichTextTable::GetSelection(long start, long end) const
+{
+ wxRichTextSelection selection;
+ selection.SetContainer((wxRichTextTable*) this);
+
+ if (start > end)
+ {
+ long tmp = end;
+ end = start;
+ start = tmp;
+ }
+
+ wxASSERT( start >= 0 && end < (m_colCount * m_rowCount));
+
+ if (end >= (m_colCount * m_rowCount))
+ return selection;
+
+ // We need to find the rectangle of cells that is described by the rectangle
+ // with start, end as the diagonal. Make sure we don't add cells that are
+ // not currenty visible because they are overlapped by spanning cells.
+/*
+ --------------------------
+ | 0 | 1 | 2 | 3 | 4 |
+ --------------------------
+ | 5 | 6 | 7 | 8 | 9 |
+ --------------------------
+ | 10 | 11 | 12 | 13 | 14 |
+ --------------------------
+ | 15 | 16 | 17 | 18 | 19 |
+ --------------------------
+
+ Let's say we select 6 -> 18.
+
+ Left and right edge cols of rectangle are 1 and 3 inclusive. Find least/greatest to find
+ which is left and which is right.
+
+ Top and bottom edge rows are 1 and 3 inclusive. Again, find least/greatest to find top and bottom.
+
+ Now go through rows from 1 to 3 and only add cells that are (a) within above column range
+ and (b) shown.
+
+
+*/
+
+ int leftCol = start - m_colCount * int(start/m_colCount);
+ int rightCol = end - m_colCount * int(end/m_colCount);
+
+ int topRow = int(start/m_colCount);
+ int bottomRow = int(end/m_colCount);
+
+ if (leftCol > rightCol)
+ {
+ int tmp = rightCol;
+ rightCol = leftCol;
+ leftCol = tmp;
+ }
+
+ if (topRow > bottomRow)
+ {
+ int tmp = bottomRow;
+ bottomRow = topRow;
+ topRow = tmp;
+ }
+
+ int i, j;
+ for (i = topRow; i <= bottomRow; i++)
+ {
+ for (j = leftCol; j <= rightCol; j++)
+ {
+ wxRichTextCell* cell = GetCell(i, j);
+ if (cell && cell->IsShown())
+ selection.Add(cell->GetRange());
+ }
+ }
+
+ return selection;
+}
+
+// Sets the attributes for the cells specified by the selection.
+bool wxRichTextTable::SetCellStyle(const wxRichTextSelection& selection, const wxRichTextAttr& style, int flags)
+{
+ if (selection.GetContainer() != this)
+ return false;
+
+ wxRichTextBuffer* buffer = GetBuffer();
+ bool haveControl = (buffer && buffer->GetRichTextCtrl() != NULL);
+ bool withUndo = haveControl && ((flags & wxRICHTEXT_SETSTYLE_WITH_UNDO) != 0);
+
+ if (withUndo)
+ buffer->BeginBatchUndo(_("Set Cell Style"));
+
+ wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
+ while (node)
+ {
+ wxRichTextCell* cell = wxDynamicCast(node->GetData(), wxRichTextCell);
+ if (cell && selection.WithinSelection(cell->GetRange().GetStart()))
+ SetStyle(cell, style, flags);
+ node = node->GetNext();
+ }
+
+ // Do action, or delay it until end of batch.
+ if (withUndo)
+ buffer->EndBatchUndo();
+
+ return true;
+}
+
+wxPosition wxRichTextTable::GetFocusedCell() const
+{
+ wxPosition position(-1, -1);
+ const wxRichTextObject* focus = GetBuffer()->GetRichTextCtrl()->GetFocusObject();
+
+ for (int row = 0; row < GetRowCount(); ++row)
+ {
+ for (int col = 0; col < GetColumnCount(); ++col)
+ {
+ if (GetCell(row, col) == focus)
+ {
+ position.SetRow(row);
+ position.SetCol(col);
+ return position;
+ }
+ }
+ }
+
+ return position;
+}
+
+int wxRichTextTable::HitTest(wxDC& dc, wxRichTextDrawingContext& context, const wxPoint& pt, long& textPosition, wxRichTextObject** obj, wxRichTextObject** contextObj, int flags)
+{
+ for (int row = 0; row < GetRowCount(); ++row)
+ {
+ for (int col = 0; col < GetColumnCount(); ++col)
+ {
+ wxRichTextCell* cell = GetCell(row, col);
+ if (cell->wxRichTextObject::HitTest(dc, context, pt, textPosition, obj, contextObj, flags) != wxRICHTEXT_HITTEST_NONE)
+ {
+ return cell->HitTest(dc, context, pt, textPosition, obj, contextObj, flags);
+ }
+ }
+ }
+
+ return wxRICHTEXT_HITTEST_NONE;
+}
+
+bool wxRichTextTable::DeleteRows(int startRow, int noRows)
+{
+ wxASSERT((startRow + noRows) <= m_rowCount);
+ if ((startRow + noRows) > m_rowCount)
+ return false;
+
+ wxCHECK_MSG(noRows != m_rowCount, false, "Trying to delete all the cells in a table");
+
+ wxRichTextBuffer* buffer = GetBuffer();
+ wxRichTextCtrl* rtc = buffer->GetRichTextCtrl();
+
+ wxRichTextAction* action = NULL;
+ wxRichTextTable* clone = NULL;
+ if (!rtc->SuppressingUndo())
+ {
+ // Create a clone containing the current state of the table. It will be used to Undo the action
+ clone = wxStaticCast(this->Clone(), wxRichTextTable);
+ clone->SetParent(GetParent());
+ action = new wxRichTextAction(NULL, _("Delete Row"), wxRICHTEXT_CHANGE_OBJECT, buffer, this, rtc);
+ action->SetObject(this);
+ action->SetPosition(GetRange().GetStart());
+ }
+
+ int i, j;
+ for (i = startRow; i < (startRow+noRows); i++)
+ {
+ wxRichTextObjectPtrArray& colArray = m_cells[startRow];
+ for (j = 0; j < (int) colArray.GetCount(); j++)
+ {
+ wxRichTextObject* cell = colArray[j];
+ RemoveChild(cell, true);
+ }
+
+ // Keep deleting at the same position, since we move all
+ // the others up
+ m_cells.RemoveAt(startRow);
+ }
+
+ m_rowCount = m_rowCount - noRows;
+
+ if (!rtc->SuppressingUndo())
+ {
+ buffer->SubmitAction(action);
+ // Finally store the original-state clone; doing so earlier would cause various failures
+ action->StoreObject(clone);
+ }
+
+ return true;
+}
+
+bool wxRichTextTable::DeleteColumns(int startCol, int noCols)
+{
+ wxASSERT((startCol + noCols) <= m_colCount);
+ if ((startCol + noCols) > m_colCount)
+ return false;
+
+ wxCHECK_MSG(noCols != m_colCount, false, "Trying to delete all the cells in a table");
+
+ wxRichTextBuffer* buffer = GetBuffer();
+ wxRichTextCtrl* rtc = buffer->GetRichTextCtrl();
+
+ wxRichTextAction* action = NULL;
+ wxRichTextTable* clone = NULL;
+ if (!rtc->SuppressingUndo())
+ {
+ // Create a clone containing the current state of the table. It will be used to Undo the action
+ clone = wxStaticCast(this->Clone(), wxRichTextTable);
+ clone->SetParent(GetParent());
+ action = new wxRichTextAction(NULL, _("Delete Column"), wxRICHTEXT_CHANGE_OBJECT, buffer, this, rtc);
+ action->SetObject(this);
+ action->SetPosition(GetRange().GetStart());
+ }
+
+ bool deleteRows = (noCols == m_colCount);
+
+ int i, j;
+ for (i = 0; i < m_rowCount; i++)
+ {
+ wxRichTextObjectPtrArray& colArray = m_cells[deleteRows ? 0 : i];
+ for (j = 0; j < noCols; j++)
+ {
+ wxRichTextObject* cell = colArray[startCol];
+ RemoveChild(cell, true);
+ colArray.RemoveAt(startCol);
+ }
+
+ if (deleteRows)
+ m_cells.RemoveAt(0);
+ }
+
+ if (deleteRows)
+ m_rowCount = 0;
+ m_colCount = m_colCount - noCols;
+
+ if (!rtc->SuppressingUndo())
+ {
+ buffer->SubmitAction(action);
+ // Finally store the original-state clone; doing so earlier would cause various failures
+ action->StoreObject(clone);
+ }
+
+ return true;
+}
+
+bool wxRichTextTable::AddRows(int startRow, int noRows, const wxRichTextAttr& attr)
+{
+ wxASSERT(startRow <= m_rowCount);
+ if (startRow > m_rowCount)
+ return false;
+
+ wxRichTextBuffer* buffer = GetBuffer();
+ wxRichTextAction* action = NULL;
+ wxRichTextTable* clone = NULL;
+
+ if (!buffer->GetRichTextCtrl()->SuppressingUndo())
+ {
+ // Create a clone containing the current state of the table. It will be used to Undo the action
+ clone = wxStaticCast(this->Clone(), wxRichTextTable);
+ clone->SetParent(GetParent());
+ action = new wxRichTextAction(NULL, _("Add Row"), wxRICHTEXT_CHANGE_OBJECT, buffer, this, buffer->GetRichTextCtrl());
+ action->SetObject(this);
+ action->SetPosition(GetRange().GetStart());
+ }
+
+ wxRichTextAttr cellattr = attr;
+ if (!cellattr.GetTextColour().IsOk())
+ cellattr.SetTextColour(buffer->GetBasicStyle().GetTextColour());
+
+ int i, j;
+ for (i = 0; i < noRows; i++)
+ {
+ int idx;
+ if (startRow == m_rowCount)
+ {
+ m_cells.Add(wxRichTextObjectPtrArray());
+ idx = m_cells.GetCount() - 1;
+ }
+ else
+ {
+ m_cells.Insert(wxRichTextObjectPtrArray(), startRow+i);
+ idx = startRow+i;
+ }
+
+ wxRichTextObjectPtrArray& colArray = m_cells[idx];
+ for (j = 0; j < m_colCount; j++)
+ {
+ wxRichTextCell* cell = new wxRichTextCell;
+ cell->GetAttributes() = cellattr;
+
+ AppendChild(cell);
+ cell->AddParagraph(wxEmptyString);
+ colArray.Add(cell);
+ }
+ }
+
+ m_rowCount = m_rowCount + noRows;
+
+ if (!buffer->GetRichTextCtrl()->SuppressingUndo())
+ {
+ buffer->SubmitAction(action);
+ // Finally store the original-state clone; doing so earlier would cause various failures
+ action->StoreObject(clone);
+ }
+
+ return true;
+}
+
+bool wxRichTextTable::AddColumns(int startCol, int noCols, const wxRichTextAttr& attr)
+{
+ wxASSERT(startCol <= m_colCount);
+ if (startCol > m_colCount)
+ return false;
+
+ wxRichTextBuffer* buffer = GetBuffer();
+ wxRichTextAction* action = NULL;
+ wxRichTextTable* clone = NULL;
+
+ if (!buffer->GetRichTextCtrl()->SuppressingUndo())
+ {
+ // Create a clone containing the current state of the table. It will be used to Undo the action
+ clone = wxStaticCast(this->Clone(), wxRichTextTable);
+ clone->SetParent(GetParent());
+ action = new wxRichTextAction(NULL, _("Add Column"), wxRICHTEXT_CHANGE_OBJECT, buffer, this, buffer->GetRichTextCtrl());
+ action->SetObject(this);
+ action->SetPosition(GetRange().GetStart());
+ }
+
+ wxRichTextAttr cellattr = attr;
+ if (!cellattr.GetTextColour().IsOk())
+ cellattr.SetTextColour(buffer->GetBasicStyle().GetTextColour());
+
+ int i, j;
+ for (i = 0; i < m_rowCount; i++)
+ {
+ wxRichTextObjectPtrArray& colArray = m_cells[i];
+ for (j = 0; j < noCols; j++)
+ {
+ wxRichTextCell* cell = new wxRichTextCell;
+ cell->GetAttributes() = cellattr;
+
+ AppendChild(cell);
+ cell->AddParagraph(wxEmptyString);
+
+ if (startCol == m_colCount)
+ colArray.Add(cell);
+ else
+ colArray.Insert(cell, startCol+j);
+ }
+ }
+
+ m_colCount = m_colCount + noCols;
+
+ if (!buffer->GetRichTextCtrl()->SuppressingUndo())
+ {
+ buffer->SubmitAction(action);
+ // Finally store the original-state clone; doing so earlier would cause various failures
+ action->StoreObject(clone);
+ }
+
+ return true;
+}
+
+// Edit properties via a GUI
+bool wxRichTextTable::EditProperties(wxWindow* parent, wxRichTextBuffer* buffer)
+{
+ wxRichTextObjectPropertiesDialog boxDlg(this, wxGetTopLevelParent(parent), wxID_ANY, _("Table Properties"));
+ boxDlg.SetAttributes(GetAttributes());
+
+ if (boxDlg.ShowModal() == wxID_OK)
+ {
+ boxDlg.ApplyStyle(buffer->GetRichTextCtrl(), wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_RESET);
+ return true;
+ }
+ else
+ return false;
+}
+
+bool wxRichTextTableBlock::ComputeBlockForSelection(wxRichTextTable* table, wxRichTextCtrl* ctrl, bool requireCellSelection)
+{
+ if (!ctrl)
+ return false;
+
+ ColStart() = 0;
+ ColEnd() = table->GetColumnCount()-1;
+ RowStart() = 0;
+ RowEnd() = table->GetRowCount()-1;
+
+ wxRichTextSelection selection = ctrl->GetSelection();
+ if (selection.IsValid() && selection.GetContainer() == table)
+ {
+ // Start with an invalid block and increase.
+ wxRichTextTableBlock selBlock(-1, -1, -1, -1);
+ wxRichTextRangeArray ranges = selection.GetRanges();
+ int row, col;
+ for (row = 0; row < table->GetRowCount(); row++)
+ {
+ for (col = 0; col < table->GetColumnCount(); col++)
+ {
+ if (selection.WithinSelection(table->GetCell(row, col)->GetRange().GetStart()))
+ {
+ if (selBlock.ColStart() == -1)
+ selBlock.ColStart() = col;
+ if (selBlock.ColEnd() == -1)
+ selBlock.ColEnd() = col;
+ if (col < selBlock.ColStart())
+ selBlock.ColStart() = col;
+ if (col > selBlock.ColEnd())
+ selBlock.ColEnd() = col;
+
+ if (selBlock.RowStart() == -1)
+ selBlock.RowStart() = row;
+ if (selBlock.RowEnd() == -1)
+ selBlock.RowEnd() = row;
+ if (row < selBlock.RowStart())
+ selBlock.RowStart() = row;
+ if (row > selBlock.RowEnd())
+ selBlock.RowEnd() = row;
+ }
+ }
+ }
+
+ if (selBlock.RowStart() != -1 && selBlock.RowEnd() != -1 && selBlock.ColStart() != -1 && selBlock.ColEnd() != -1)
+ (*this) = selBlock;
+ }
+ else
+ {
+ // See if a whole cell's contents is selected, in which case we can treat the cell as selected.
+ // wxRTC lacks the ability to select a single cell.
+ wxRichTextCell* cell = wxDynamicCast(ctrl->GetFocusObject(), wxRichTextCell);
+ if (cell && (!requireCellSelection || (ctrl->HasSelection() && ctrl->GetSelectionRange() == cell->GetOwnRange())))
+ {
+ int row, col;
+ if (table->GetCellRowColumnPosition(cell->GetRange().GetStart(), row, col))
+ {
+ RowStart() = row;
+ RowEnd() = row;
+ ColStart() = col;
+ ColEnd() = col;
+ }
+ }
+ }
+
+ return true;
+}
+
+// Does this block represent the whole table?
+bool wxRichTextTableBlock::IsWholeTable(wxRichTextTable* table) const
+{
+ return (ColStart() == 0 && RowStart() == 0 && ColEnd() == (table->GetColumnCount()-1) && RowEnd() == (table->GetRowCount()-1));
+}
+
+// Returns the cell focused in the table, if any
+wxRichTextCell* wxRichTextTableBlock::GetFocusedCell(wxRichTextCtrl* ctrl)
+{
+ if (!ctrl)
+ return NULL;
+
+ wxRichTextCell* cell = wxDynamicCast(ctrl->GetFocusObject(), wxRichTextCell);
+ return cell;
+}
+
+/*
+ * Module to initialise and clean up handlers
+ */
+
+class wxRichTextModule: public wxModule
+{
+DECLARE_DYNAMIC_CLASS(wxRichTextModule)
+public:
+ wxRichTextModule() {}
+ bool OnInit()
+ {
+ wxRichTextBuffer::SetRenderer(new wxRichTextStdRenderer);
+ wxRichTextBuffer::InitStandardHandlers();
+ wxRichTextParagraph::InitDefaultTabs();
+
+ wxRichTextXMLHandler::RegisterNodeName(wxT("text"), wxT("wxRichTextPlainText"));
+ wxRichTextXMLHandler::RegisterNodeName(wxT("symbol"), wxT("wxRichTextPlainText"));
+ wxRichTextXMLHandler::RegisterNodeName(wxT("image"), wxT("wxRichTextImage"));
+ wxRichTextXMLHandler::RegisterNodeName(wxT("paragraph"), wxT("wxRichTextParagraph"));
+ wxRichTextXMLHandler::RegisterNodeName(wxT("paragraphlayout"), wxT("wxRichTextParagraphLayoutBox"));
+ wxRichTextXMLHandler::RegisterNodeName(wxT("textbox"), wxT("wxRichTextBox"));
+ wxRichTextXMLHandler::RegisterNodeName(wxT("cell"), wxT("wxRichTextCell"));
+ wxRichTextXMLHandler::RegisterNodeName(wxT("table"), wxT("wxRichTextTable"));
+ wxRichTextXMLHandler::RegisterNodeName(wxT("field"), wxT("wxRichTextField"));
+
+ return true;
+ }
+ void OnExit()
+ {
+ wxRichTextBuffer::CleanUpHandlers();
+ wxRichTextBuffer::CleanUpDrawingHandlers();
+ wxRichTextBuffer::CleanUpFieldTypes();
+ wxRichTextXMLHandler::ClearNodeToClassMap();
+ wxRichTextDecimalToRoman(-1);
+ wxRichTextParagraph::ClearDefaultTabs();
+ wxRichTextCtrl::ClearAvailableFontNames();
+ wxRichTextBuffer::SetRenderer(NULL);
+ }
+};
+
+IMPLEMENT_DYNAMIC_CLASS(wxRichTextModule, wxModule)
+
+
+// If the richtext lib is dynamically loaded after the app has already started
+// (such as from wxPython) then the built-in module system will not init this
+// module. Provide this function to do it manually.
+void wxRichTextModuleInit()
+{
+ wxModule* module = new wxRichTextModule;
+ wxModule::RegisterModule(module);
+ wxModule::InitializeModules();
+}
+
+
+/*!
+ * Commands for undo/redo
+ *
+ */
+
+wxRichTextCommand::wxRichTextCommand(const wxString& name, wxRichTextCommandId id, wxRichTextBuffer* buffer,
+ wxRichTextParagraphLayoutBox* container, wxRichTextCtrl* ctrl, bool ignoreFirstTime): wxCommand(true, name)
+{
+ /* wxRichTextAction* action = */ new wxRichTextAction(this, name, id, buffer, container, ctrl, ignoreFirstTime);
+}
+
+wxRichTextCommand::wxRichTextCommand(const wxString& name): wxCommand(true, name)
+{
+}
+
+wxRichTextCommand::~wxRichTextCommand()
+{
+ ClearActions();
+}
+
+void wxRichTextCommand::AddAction(wxRichTextAction* action)
+{
+ if (!m_actions.Member(action))
+ m_actions.Append(action);
+}
+
+bool wxRichTextCommand::Do()
+{
+ for (wxList::compatibility_iterator node = m_actions.GetFirst(); node; node = node->GetNext())
+ {
+ wxRichTextAction* action = (wxRichTextAction*) node->GetData();
+ action->Do();
+ }
+
+ return true;
+}
+
+bool wxRichTextCommand::Undo()
+{
+ for (wxList::compatibility_iterator node = m_actions.GetLast(); node; node = node->GetPrevious())
+ {
+ wxRichTextAction* action = (wxRichTextAction*) node->GetData();
+ action->Undo();
+ }
+
+ return true;
+}
+
+void wxRichTextCommand::ClearActions()
+{
+ WX_CLEAR_LIST(wxList, m_actions);
+}
+
+/*!
+ * Individual action
+ *
+ */
+
+wxRichTextAction::wxRichTextAction(wxRichTextCommand* cmd, const wxString& name, wxRichTextCommandId id,
+ wxRichTextBuffer* buffer, wxRichTextParagraphLayoutBox* container,
+ wxRichTextCtrl* ctrl, bool ignoreFirstTime)
+{
+ m_buffer = buffer;
+ m_object = NULL;
+ m_containerAddress.Create(buffer, container);
+ m_ignoreThis = ignoreFirstTime;
+ m_cmdId = id;
+ m_position = -1;
+ m_ctrl = ctrl;
+ m_name = name;
+ m_newParagraphs.SetDefaultStyle(buffer->GetDefaultStyle());
+ m_newParagraphs.SetBasicStyle(buffer->GetBasicStyle());
+ if (cmd)
+ cmd->AddAction(this);
+}
+
+wxRichTextAction::~wxRichTextAction()
+{
+ if (m_object)
+ delete m_object;
+}
+
+// Returns the container that this action refers to, using the container address and top-level buffer.
+wxRichTextParagraphLayoutBox* wxRichTextAction::GetContainer() const
+{
+ wxRichTextParagraphLayoutBox* container = wxDynamicCast(GetContainerAddress().GetObject(m_buffer), wxRichTextParagraphLayoutBox);
+ return container;
+}
+
+
+void wxRichTextAction::CalculateRefreshOptimizations(wxArrayInt& optimizationLineCharPositions, wxArrayInt& optimizationLineYPositions)
+{
+ // Store a list of line start character and y positions so we can figure out which area
+ // we need to refresh
+
+#if wxRICHTEXT_USE_OPTIMIZED_DRAWING
+ wxRichTextParagraphLayoutBox* container = GetContainer();
+ wxASSERT(container != NULL);
+ if (!container)
+ return;
+
+ // NOTE: we're assuming that the buffer is laid out correctly at this point.
+ // If we had several actions, which only invalidate and leave layout until the
+ // paint handler is called, then this might not be true. So we may need to switch
+ // optimisation on only when we're simply adding text and not simultaneously
+ // deleting a selection, for example. Or, we make sure the buffer is laid out correctly
+ // first, but of course this means we'll be doing it twice.
+ if (!m_buffer->IsDirty() && m_ctrl) // can only do optimisation if the buffer is already laid out correctly
+ {
+ wxSize clientSize = m_ctrl->GetUnscaledSize(m_ctrl->GetClientSize());
+ wxPoint firstVisiblePt = m_ctrl->GetUnscaledPoint(m_ctrl->GetFirstVisiblePoint());
+ int lastY = firstVisiblePt.y + clientSize.y;
+
+ wxRichTextParagraph* para = container->GetParagraphAtPosition(GetRange().GetStart());
+ wxRichTextObjectList::compatibility_iterator node = container->GetChildren().Find(para);
+ while (node)
+ {
+ wxRichTextParagraph* child = (wxRichTextParagraph*) node->GetData();
+ wxRichTextLineList::compatibility_iterator node2 = child->GetLines().GetFirst();
+ while (node2)
+ {
+ wxRichTextLine* line = node2->GetData();
+ wxPoint pt = line->GetAbsolutePosition();
+ wxRichTextRange range = line->GetAbsoluteRange();
+
+ if (pt.y > lastY)
+ {
+ node2 = wxRichTextLineList::compatibility_iterator();
+ node = wxRichTextObjectList::compatibility_iterator();
+ }
+ else if (range.GetStart() > GetPosition() && pt.y >= firstVisiblePt.y)
+ {
+ optimizationLineCharPositions.Add(range.GetStart());
+ optimizationLineYPositions.Add(pt.y);
+ }
+
+ if (node2)
+ node2 = node2->GetNext();
+ }
+
+ if (node)
+ node = node->GetNext();
+ }
+ }
+#endif
+}
+
+bool wxRichTextAction::Do()
+{
+ m_buffer->Modify(true);
+
+ wxRichTextParagraphLayoutBox* container = GetContainer();
+ wxASSERT(container != NULL);
+ if (!container)
+ return false;
+
+ switch (m_cmdId)
+ {
+ case wxRICHTEXT_INSERT:
+ {
+ // Store a list of line start character and y positions so we can figure out which area
+ // we need to refresh
+ wxArrayInt optimizationLineCharPositions;
+ wxArrayInt optimizationLineYPositions;
+
+#if wxRICHTEXT_USE_OPTIMIZED_DRAWING
+ CalculateRefreshOptimizations(optimizationLineCharPositions, optimizationLineYPositions);
+#endif
+
+ container->InsertFragment(GetRange().GetStart(), m_newParagraphs);
+ container->UpdateRanges();
+
+ // InvalidateHierarchy goes up the hierarchy as well as down, otherwise with a nested object,
+ // Layout() would stop prematurely at the top level.
+ container->InvalidateHierarchy(wxRichTextRange(wxMax(0, GetRange().GetStart()-1), GetRange().GetEnd()));
+
+ long newCaretPosition = GetPosition() + m_newParagraphs.GetOwnRange().GetLength();
+
+ // Character position to caret position
+ newCaretPosition --;
+
+ // Don't take into account the last newline
+ if (m_newParagraphs.GetPartialParagraph())
+ newCaretPosition --;
+ else
+ if (m_newParagraphs.GetChildren().GetCount() > 1)
+ {
+ wxRichTextObject* p = (wxRichTextObject*) m_newParagraphs.GetChildren().GetLast()->GetData();
+ if (p->GetRange().GetLength() == 1)
+ newCaretPosition --;
+ }
+
+ newCaretPosition = wxMin(newCaretPosition, (container->GetOwnRange().GetEnd()-1));
+
+ UpdateAppearance(newCaretPosition, true /* send update event */, & optimizationLineCharPositions, & optimizationLineYPositions, true /* do */);
+
+ wxRichTextEvent cmdEvent(
+ wxEVT_RICHTEXT_CONTENT_INSERTED,
+ m_ctrl ? m_ctrl->GetId() : -1);
+ cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
+ cmdEvent.SetRange(GetRange());
+ cmdEvent.SetPosition(GetRange().GetStart());
+ cmdEvent.SetContainer(container);
+
+ m_buffer->SendEvent(cmdEvent);
+
+ break;
+ }
+ case wxRICHTEXT_DELETE:
+ {
+ wxArrayInt optimizationLineCharPositions;
+ wxArrayInt optimizationLineYPositions;
+
+#if wxRICHTEXT_USE_OPTIMIZED_DRAWING
+ CalculateRefreshOptimizations(optimizationLineCharPositions, optimizationLineYPositions);
+#endif
+
+ container->DeleteRange(GetRange());
+ container->UpdateRanges();
+ // InvalidateHierarchy goes up the hierarchy as well as down, otherwise with a nested object,
+ // Layout() would stop prematurely at the top level.
+ container->InvalidateHierarchy(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
+
+ long caretPos = GetRange().GetStart()-1;
+ if (caretPos >= container->GetOwnRange().GetEnd())
+ caretPos --;
+
+ UpdateAppearance(caretPos, true /* send update event */, & optimizationLineCharPositions, & optimizationLineYPositions, true /* do */);
+
+ wxRichTextEvent cmdEvent(
+ wxEVT_RICHTEXT_CONTENT_DELETED,
+ m_ctrl ? m_ctrl->GetId() : -1);
+ cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
+ cmdEvent.SetRange(GetRange());
+ cmdEvent.SetPosition(GetRange().GetStart());
+ cmdEvent.SetContainer(container);
+
+ m_buffer->SendEvent(cmdEvent);
+
+ break;
+ }
+ case wxRICHTEXT_CHANGE_STYLE:
+ case wxRICHTEXT_CHANGE_PROPERTIES:
+ {
+ ApplyParagraphs(GetNewParagraphs());
+
+ // Invalidate the whole buffer if there were floating objects
+ if (wxRichTextBuffer::GetFloatingLayoutMode() && container->GetFloatingObjectCount() > 0)
+ m_buffer->InvalidateHierarchy(wxRICHTEXT_ALL);
+ else
+ {
+ // InvalidateHierarchy goes up the hierarchy as well as down, otherwise with a nested object,
+ // Layout() would stop prematurely at the top level.
+ container->InvalidateHierarchy(GetRange());
+ }
+
+ UpdateAppearance(GetPosition());
+
+ wxRichTextEvent cmdEvent(
+ m_cmdId == wxRICHTEXT_CHANGE_STYLE ? wxEVT_RICHTEXT_STYLE_CHANGED : wxEVT_RICHTEXT_PROPERTIES_CHANGED,
+ m_ctrl ? m_ctrl->GetId() : -1);
+ cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
+ cmdEvent.SetRange(GetRange());
+ cmdEvent.SetPosition(GetRange().GetStart());
+ cmdEvent.SetContainer(container);
+
+ m_buffer->SendEvent(cmdEvent);
+
+ break;
+ }
+ case wxRICHTEXT_CHANGE_ATTRIBUTES:
+ {
+ wxRichTextObject* obj = m_objectAddress.GetObject(m_buffer); // container->GetChildAtPosition(GetRange().GetStart());
+ if (obj)
+ {
+ wxRichTextAttr oldAttr = obj->GetAttributes();
+ obj->GetAttributes() = m_attributes;
+ m_attributes = oldAttr;
+ }
+
+ // InvalidateHierarchy goes up the hierarchy as well as down, otherwise with a nested object,
+ // Layout() would stop prematurely at the top level.
+ // Invalidate the whole buffer if there were floating objects
+ if (wxRichTextBuffer::GetFloatingLayoutMode() && container->GetFloatingObjectCount() > 0)
+ m_buffer->InvalidateHierarchy(wxRICHTEXT_ALL);
+ else
+ container->InvalidateHierarchy(GetRange());
+
+ UpdateAppearance(GetPosition());
+
+ wxRichTextEvent cmdEvent(
+ wxEVT_RICHTEXT_STYLE_CHANGED,
+ m_ctrl ? m_ctrl->GetId() : -1);
+ cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
+ cmdEvent.SetRange(GetRange());
+ cmdEvent.SetPosition(GetRange().GetStart());
+ cmdEvent.SetContainer(container);
+
+ m_buffer->SendEvent(cmdEvent);
+
+ break;
+ }
+ case wxRICHTEXT_CHANGE_OBJECT:
+ {
+ wxRichTextObject* obj = m_objectAddress.GetObject(m_buffer);
+ if (obj && m_object && m_ctrl)
+ {
+ // The plan is to swap the current object with the stored, previous-state, clone
+ // We can't get 'node' from the containing buffer (as it doesn't directly store objects)
+ // so use the parent paragraph
+ wxRichTextParagraph* para = wxDynamicCast(obj->GetParent(), wxRichTextParagraph);
+ wxCHECK_MSG(para, false, "Invalid parent paragraph");
+
+ // The stored object, m_object, may have a stale parent paragraph. This would cause
+ // a crash during layout, so use obj's parent para, which should be the correct one.
+ // (An alternative would be to return the parent too from m_objectAddress.GetObject(),
+ // or to set obj's parent there before returning)
+ m_object->SetParent(para);
+
+ wxRichTextObjectList::compatibility_iterator node = para->GetChildren().Find(obj);
+ if (node)
+ {
+ wxRichTextObject* obj = node->GetData();
+ node->SetData(m_object);
+ m_object = obj;
+ }
+ }
+
+ // We can't rely on the current focus-object remaining valid, if it's e.g. a table's cell.
+ // And we can't cope with this in the calling code: a user may later click in the cell
+ // before deciding to Undo() or Redo(). So play safe and set focus to the buffer.
+ if (m_ctrl)
+ m_ctrl->SetFocusObject(m_buffer, false);
+
+ // InvalidateHierarchy goes up the hierarchy as well as down, otherwise with a nested object,
+ // Layout() would stop prematurely at the top level.
+ // Invalidate the whole buffer if there were floating objects
+ if (wxRichTextBuffer::GetFloatingLayoutMode() && container->GetFloatingObjectCount() > 0)
+ m_buffer->InvalidateHierarchy(wxRICHTEXT_ALL);
+ else
+ container->InvalidateHierarchy(GetRange());
+
+ UpdateAppearance(GetPosition(), true);
+
+ // TODO: send new kind of modification event
+
+ break;
+ }
+ default:
+ break;
+ }
+
+ return true;
+}
+
+bool wxRichTextAction::Undo()
+{
+ m_buffer->Modify(true);
+
+ wxRichTextParagraphLayoutBox* container = GetContainer();
+ wxASSERT(container != NULL);
+ if (!container)
+ return false;
+
+ switch (m_cmdId)
+ {
+ case wxRICHTEXT_INSERT:
+ {
+ wxArrayInt optimizationLineCharPositions;
+ wxArrayInt optimizationLineYPositions;
+
+#if wxRICHTEXT_USE_OPTIMIZED_DRAWING
+ CalculateRefreshOptimizations(optimizationLineCharPositions, optimizationLineYPositions);
+#endif
+
+ container->DeleteRange(GetRange());
+ container->UpdateRanges();
+
+ // InvalidateHierarchy goes up the hierarchy as well as down, otherwise with a nested object,
+ // Layout() would stop prematurely at the top level.
+ container->InvalidateHierarchy(wxRichTextRange(GetRange().GetStart(), GetRange().GetStart()));
+
+ long newCaretPosition = GetPosition() - 1;
+
+ UpdateAppearance(newCaretPosition, true, /* send update event */ & optimizationLineCharPositions, & optimizationLineYPositions, false /* undo */);
+
+ wxRichTextEvent cmdEvent(
+ wxEVT_RICHTEXT_CONTENT_DELETED,
+ m_ctrl ? m_ctrl->GetId() : -1);
+ cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
+ cmdEvent.SetRange(GetRange());
+ cmdEvent.SetPosition(GetRange().GetStart());
+ cmdEvent.SetContainer(container);
+
+ m_buffer->SendEvent(cmdEvent);
+
+ break;
+ }
+ case wxRICHTEXT_DELETE:
+ {
+ wxArrayInt optimizationLineCharPositions;
+ wxArrayInt optimizationLineYPositions;
+
+#if wxRICHTEXT_USE_OPTIMIZED_DRAWING
+ CalculateRefreshOptimizations(optimizationLineCharPositions, optimizationLineYPositions);
+#endif
+
+ container->InsertFragment(GetRange().GetStart(), m_oldParagraphs);
+ container->UpdateRanges();
+
+ // InvalidateHierarchy goes up the hierarchy as well as down, otherwise with a nested object,
+ // Layout() would stop prematurely at the top level.
+ container->InvalidateHierarchy(GetRange());
+
+ UpdateAppearance(GetPosition(), true, /* send update event */ & optimizationLineCharPositions, & optimizationLineYPositions, false /* undo */);
+
+ wxRichTextEvent cmdEvent(
+ wxEVT_RICHTEXT_CONTENT_INSERTED,
+ m_ctrl ? m_ctrl->GetId() : -1);
+ cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
+ cmdEvent.SetRange(GetRange());
+ cmdEvent.SetPosition(GetRange().GetStart());
+ cmdEvent.SetContainer(container);
+
+ m_buffer->SendEvent(cmdEvent);
+
+ break;
+ }
+ case wxRICHTEXT_CHANGE_STYLE:
+ case wxRICHTEXT_CHANGE_PROPERTIES:
+ {
+ ApplyParagraphs(GetOldParagraphs());
+ // InvalidateHierarchy goes up the hierarchy as well as down, otherwise with a nested object,
+ // Layout() would stop prematurely at the top level.
+ container->InvalidateHierarchy(GetRange());
+
+ UpdateAppearance(GetPosition());
+
+ wxRichTextEvent cmdEvent(
+ m_cmdId == wxRICHTEXT_CHANGE_STYLE ? wxEVT_RICHTEXT_STYLE_CHANGED : wxEVT_RICHTEXT_PROPERTIES_CHANGED,
+ m_ctrl ? m_ctrl->GetId() : -1);
+ cmdEvent.SetEventObject(m_ctrl ? (wxObject*) m_ctrl : (wxObject*) m_buffer);
+ cmdEvent.SetRange(GetRange());
+ cmdEvent.SetPosition(GetRange().GetStart());
+ cmdEvent.SetContainer(container);
+
+ m_buffer->SendEvent(cmdEvent);
+
+ break;
+ }
+ case wxRICHTEXT_CHANGE_ATTRIBUTES:
+ case wxRICHTEXT_CHANGE_OBJECT:
+ {
+ return Do();
+ }
+ default:
+ break;
+ }
+
+ return true;
+}
+
+/// Update the control appearance
+void wxRichTextAction::UpdateAppearance(long caretPosition, bool sendUpdateEvent, wxArrayInt* optimizationLineCharPositions, wxArrayInt* optimizationLineYPositions, bool isDoCmd)
+{
+ wxRichTextParagraphLayoutBox* container = GetContainer();
+ wxASSERT(container != NULL);
+ if (!container)
+ return;
+
+ if (m_ctrl)
+ {
+ m_ctrl->SetFocusObject(container);
+ m_ctrl->SetCaretPosition(caretPosition);
+
+ if (!m_ctrl->IsFrozen())
+ {
+ wxRect containerRect = container->GetRect();
+
+ m_ctrl->LayoutContent();
+
+ // Refresh everything if there were floating objects or the container changed size
+ // (we can't yet optimize in these cases, since more complex interaction with other content occurs)
+ if ((wxRichTextBuffer::GetFloatingLayoutMode() && container->GetFloatingObjectCount() > 0) || (container->GetParent() && containerRect != container->GetRect()))
+ {
+ m_ctrl->Refresh(false);
+ }
+ else