+ 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, const wxRect& WXUNUSED(rect), 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, 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, int WXUNUSED(flags), wxPoint position, 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());
+
+ // 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.Ok())
+ {
+ if ( textAttr.HasTextEffects() && ( (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUPERSCRIPT)
+ || (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_SUBSCRIPT) ) )
+ {
+ wxFont textFont = font;
+ double size = static_cast<double>(textFont.GetPointSize()) / wxSCRIPT_MUL_FACTOR;
+ textFont.SetPointSize( static_cast<int>(size) );
+ 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);
+ wxString toReplace = wxRichTextLineBreakChar;
+ str.Replace(toReplace, wxT(" "));
+
+ wxString stringChunk = str.Mid(startPos, (size_t) len);
+
+ if (textAttr.HasTextEffects() && (textAttr.GetTextEffects() & wxTEXT_ATTR_EFFECT_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->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) const
+{
+ return object->GetClassInfo() == CLASSINFO(wxRichTextPlainText) &&
+ (m_text.empty() || wxTextAttrEq(GetAttributes(), object->GetAttributes()));
+}
+
+/// 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)
+{
+ wxRichTextPlainText* textObject = wxDynamicCast(object, wxRichTextPlainText);
+ wxASSERT( textObject != NULL );
+
+ if (textObject)
+ {
+ m_text += textObject->GetText();
+ wxRichTextApplyStyle(m_attributes, textObject->GetAttributes());
+ return true;
+ }
+ else
+ return false;
+}
+
+/// 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;
+wxRichTextRenderer* wxRichTextBuffer::sm_renderer = NULL;
+int wxRichTextBuffer::sm_bulletRightMargin = 20;
+float wxRichTextBuffer::sm_bulletProportion = (float) 0.3;
+
+/// 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;
+}
+
+/// 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;
+}
+
+/// 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(pos, paragraphs, ctrl, this, flags);
+}
+
+/// Submit command to insert paragraphs
+bool wxRichTextParagraphLayoutBox::InsertParagraphsWithUndo(long pos, const wxRichTextParagraphLayoutBox& paragraphs, wxRichTextCtrl* ctrl, wxRichTextBuffer* buffer, int flags)
+{
+ wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Text"), wxRICHTEXT_INSERT, buffer, this, ctrl, false);
+
+ wxRichTextAttr attr(buffer->GetDefaultStyle());
+
+ wxRichTextAttr* p = NULL;
+ wxRichTextAttr paraAttr;
+ if (flags & wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE)
+ {
+ paraAttr = GetStyleForNewParagraph(buffer, pos);
+ if (!paraAttr.IsDefault())
+ p = & paraAttr;
+ }
+ else
+ p = & attr;
+
+ action->GetNewParagraphs() = paragraphs;
+
+ if (p && !p->IsDefault())
+ {
+ for (wxRichTextObjectList::compatibility_iterator node = action->GetNewParagraphs().GetChildren().GetFirst(); node; node = node->GetNext())
+ {
+ wxRichTextObject* child = node->GetData();
+ child->SetAttributes(*p);
+ }
+ }
+
+ 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)
+{
+ return ctrl->GetFocusObject()->InsertTextWithUndo(pos, text, ctrl, this, flags);
+}
+
+/// Submit command to insert the given text
+bool wxRichTextParagraphLayoutBox::InsertTextWithUndo(long pos, const wxString& text, wxRichTextCtrl* ctrl, wxRichTextBuffer* buffer, 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.length() > 0 && text.Last() != wxT('\n'))
+ {
+ // Don't count the newline when undoing
+ length --;
+ action->GetNewParagraphs().SetPartialParagraph(true);
+ }
+ else if (text.length() > 0 && 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(pos, ctrl, this, flags);
+}
+
+/// Submit command to insert the given text
+bool wxRichTextParagraphLayoutBox::InsertNewlineWithUndo(long pos, wxRichTextCtrl* ctrl, wxRichTextBuffer* buffer, 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());
+
+ 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
+ // 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());
+ 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(pos, imageBlock, ctrl, this, flags, textAttr);
+}
+
+/// Submit command to insert the given image
+bool wxRichTextParagraphLayoutBox::InsertImageWithUndo(long pos, const wxRichTextImageBlock& imageBlock,
+ wxRichTextCtrl* ctrl, wxRichTextBuffer* buffer, 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());
+
+ 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(pos, object, ctrl, this, flags);
+}
+
+// Insert an object with no change of it
+wxRichTextObject* wxRichTextParagraphLayoutBox::InsertObjectWithUndo(long pos, wxRichTextObject *object, wxRichTextCtrl* ctrl, wxRichTextBuffer* buffer, 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());
+
+ 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;
+}
+
+/// 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 (BatchingUndo() && m_batchedCommand && !SuppressingUndo())
+ {
+ 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.
+ return GetCommandProcessor()->Submit(cmd, !SuppressingUndo());
+ }
+
+ 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());
+
+ // Save the old default style
+ m_attributeStack.Append((wxObject*) new wxRichTextAttr(GetDefaultStyle()));
+
+ 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;
+}
+
+/// 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;
+}
+
+/// 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;
+}
+
+/// 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(position+1, *richTextBuffer, GetRichTextCtrl(), this, 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(position+1, text2, GetRichTextCtrl(), this, 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 id = wxID_ANY;
+ if (GetRichTextCtrl())
+ id = GetRichTextCtrl()->GetId();
+
+ wxRichTextEvent event(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING, id);
+ 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_COMMAND_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, const wxPoint& pt, long& textPosition, wxRichTextObject** obj, wxRichTextObject** contextObj, int flags)
+{
+ int ret = wxRichTextParagraphLayoutBox::HitTest(dc, 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;
+ }
+}
+
+bool wxRichTextStdRenderer::DrawStandardBullet(wxRichTextParagraph* paragraph, wxDC& dc, const wxRichTextAttr& bulletAttr, const wxRect& rect)
+{
+ if (bulletAttr.GetTextColour().Ok())
+ {
+ 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;
+ fontAttr.SetFontSize(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().Ok())
+ 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, 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, 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;
+}
+
+IMPLEMENT_DYNAMIC_CLASS(wxRichTextCell, wxRichTextBox)
+
+wxRichTextCell::wxRichTextCell(wxRichTextObject* parent):
+ wxRichTextBox(parent)
+{
+}
+
+/// Draw the item
+bool wxRichTextCell::Draw(wxDC& dc, const wxRichTextRange& range, const wxRichTextSelection& selection, const wxRect& rect, int descent, int style)
+{
+ return wxRichTextBox::Draw(dc, range, selection, rect, descent, style);
+}
+
+/// 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");
+
+ wxRichTextObjectPropertiesDialog cellDlg(this, wxGetTopLevelParent(parent), wxID_ANY, caption);
+ cellDlg.SetAttributes(attr);
+
+ wxRichTextSizePage* sizePage = wxDynamicCast(cellDlg.FindPage(CLASSINFO(wxRichTextSizePage)), wxRichTextSizePage);
+ if (sizePage)
+ {
+ // We don't want position and floating controls for a cell.
+ sizePage->ShowPositionControls(false);
+ sizePage->ShowFloatingControls(false);
+ }
+
+ if (cellDlg.ShowModal() == wxID_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;
+}
+
+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, const wxRichTextRange& range, const wxRichTextSelection& selection, const wxRect& rect, int descent, int style)
+{
+ return wxRichTextBox::Draw(dc, range, selection, rect, descent, style);
+}
+
+WX_DECLARE_OBJARRAY(wxRect, wxRichTextRectArray);
+WX_DEFINE_OBJARRAY(wxRichTextRectArray);
+
+// 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, const wxRect& rect, int style)
+{
+ SetPosition(rect.GetPosition());
+
+ // TODO: 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, rect);
+ wxTextAttrDimensionConverter converter(dc, scale, availableSpace.GetSize());
+
+ // 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 = false;
+
+ int tableWidth = rect.width;
+ if (GetAttributes().GetTextBoxAttr().GetWidth().IsValid())
+ {
+ tableWidth = converter.GetPixels(GetAttributes().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, paddingRight = 0, paddingTop = 0, paddingBottom = 0;
+ if (GetAttributes().GetTextBoxAttr().GetPadding().GetLeft().IsValid())
+ paddingLeft = converter.GetPixels(GetAttributes().GetTextBoxAttr().GetPadding().GetLeft());
+ if (GetAttributes().GetTextBoxAttr().GetPadding().GetRight().IsValid())
+ paddingRight = converter.GetPixels(GetAttributes().GetTextBoxAttr().GetPadding().GetRight());
+ if (GetAttributes().GetTextBoxAttr().GetPadding().GetTop().IsValid())
+ paddingTop = converter.GetPixels(GetAttributes().GetTextBoxAttr().GetPadding().GetTop());
+ if (GetAttributes().GetTextBoxAttr().GetPadding().GetLeft().IsValid())
+ paddingBottom = converter.GetPixels(GetAttributes().GetTextBoxAttr().GetPadding().GetBottom());
+
+ // 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, GetAttributes(), 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(m_colCount);
+
+ wxArrayInt absoluteColWidths(m_colCount);
+ // wxArrayInt absoluteColWidthsSpanning(m_colCount);
+ wxArrayInt percentageColWidths(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(m_colCount);
+ wxArrayInt minColWidths(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++)
+ {
+ wxRichTextBox* cell = GetCell(j, i);
+ int colSpan = 1, rowSpan = 1;
+ if (cell->GetProperties().HasProperty(wxT("colspan")))
+ colSpan = cell->GetProperties().GetPropertyLong(wxT("colspan"));
+ if (cell->GetProperties().HasProperty(wxT("rowspan")))
+ rowSpan = cell->GetProperties().GetPropertyLong(wxT("rowspan"));
+ 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++)
+ {
+ wxRichTextBox* cell = GetCell(j, i);
+ if (rectArray.GetCount() == 0)
+ {
+ cell->Show(true);
+ }
+ else
+ {
+ int colSpan = 1, rowSpan = 1;
+ if (cell->GetProperties().HasProperty(wxT("colspan")))
+ colSpan = cell->GetProperties().GetPropertyLong(wxT("colspan"));
+ if (cell->GetProperties().HasProperty(wxT("rowspan")))
+ rowSpan = cell->GetProperties().GetPropertyLong(wxT("rowspan"));
+ 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);
+ }
+ }
+ }
+ }
+
+ // TODO: 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++)
+ {
+ wxRichTextBox* cell = GetCell(j, i);
+ if (cell->IsShown())
+ {
+ int colSpan = 1;
+ if (cell->GetProperties().HasProperty(wxT("colspan")))
+ colSpan = cell->GetProperties().GetPropertyLong(wxT("colspan"));
+
+ // Lay out cell to find min/max widths
+ cell->Invalidate(wxRICHTEXT_ALL);
+ cell->Layout(dc, 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++)
+ {
+ wxRichTextBox* cell = GetCell(j, i);
+ if (cell->IsShown())
+ {
+ int colSpan = 1;
+ if (cell->GetProperties().HasProperty(wxT("colspan")))
+ colSpan = cell->GetProperties().GetPropertyLong(wxT("colspan"));
+
+ 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++)
+ {
+ // TODO: we need to take into account min widths.
+ // 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(m_colCount);
+
+ wxTextAttrDimensionConverter converter(dc, scale);
+ for (i = 0; i < m_colCount; i++)
+ {
+ wxRichTextCell* cell = GetCell(j, i);
+ if (cell->IsShown())
+ {
+ wxASSERT(colWidths[i] > 0);
+
+ // 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 = 1;
+ if (cell->GetProperties().HasProperty(wxT("colspan")))
+ colSpan = cell->GetProperties().GetPropertyLong(wxT("colspan"));
+
+ wxRect availableCellSpace;
+
+ // TODO: take into acount spans
+ if (colSpan > 1)
+ {
+ // Calculate the size of this spanning cell from its constituent columns
+ int xx = x;
+ int spans = wxMin(colSpan, m_colCount - i);
+ for (k = i; k < 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();
+
+ // Lay out cell
+ cell->Invalidate(wxRICHTEXT_ALL);
+ cell->Layout(dc, availableCellSpace, style);
+
+ // TODO: use GetCachedSize().x to compute 'natural' size
+
+ x += (availableCellSpace.GetWidth() + paddingX);
+ if (cell->GetCachedSize().y > maxCellHeight)
+ 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, availableCellSpace, 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;
+ }
+
+ // 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(), GetAttributes(), 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, 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, -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, int flags, wxPoint position, wxArrayInt* partialExtents) const
+{
+ return wxRichTextBox::GetRangeSize(range, size, descent, dc, flags, position, 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();
+}
+
+bool wxRichTextTable::CreateTable(int rows, int cols)
+{
+ ClearTable();
+
+ 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;
+ 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 false;
+}
+
+// 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;
+}
+
+bool wxRichTextTable::DeleteRows(int startRow, int noRows)
+{
+ wxASSERT((startRow + noRows) < m_rowCount);
+ if ((startRow + noRows) >= m_rowCount)
+ return false;
+
+ 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;
+
+ return true;
+}
+
+bool wxRichTextTable::DeleteColumns(int startCol, int noCols)
+{
+ wxASSERT((startCol + noCols) < m_colCount);
+ if ((startCol + noCols) >= m_colCount)
+ return false;
+
+ bool deleteRows = (noCols == m_colCount);
+
+ int i, j;
+ for (i = 0; i < m_rowCount; i++)
+ {
+ wxRichTextObjectPtrArray& colArray = m_cells[deleteRows ? 0 : i];
+ for (j = startCol; j < (startCol+noCols); j++)
+ {
+ wxRichTextObject* cell = colArray[j];
+ RemoveChild(cell, true);
+ }
+
+ if (deleteRows)
+ m_cells.RemoveAt(0);
+ }
+
+ if (deleteRows)
+ m_rowCount = 0;
+ m_colCount = m_colCount - noCols;
+
+ return true;
+}
+
+bool wxRichTextTable::AddRows(int startRow, int noRows, const wxRichTextAttr& attr)
+{
+ wxASSERT(startRow <= m_rowCount);
+ if (startRow > m_rowCount)
+ return false;
+
+ 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() = attr;
+
+ AppendChild(cell);
+ colArray.Add(cell);
+ }
+ }
+
+ m_rowCount = m_rowCount + noRows;
+ return true;
+}
+
+bool wxRichTextTable::AddColumns(int startCol, int noCols, const wxRichTextAttr& attr)
+{
+ wxASSERT(startCol <= m_colCount);
+ if (startCol > m_colCount)
+ return false;
+
+ 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() = attr;
+
+ AppendChild(cell);
+
+ if (startCol == m_colCount)
+ colArray.Add(cell);
+ else
+ colArray.Insert(cell, startCol+j);
+ }
+ }
+
+ m_colCount = m_colCount + noCols;
+
+ 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;
+}
+
+/*
+ * 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();
+ return true;
+ }
+ void OnExit()
+ {
+ wxRichTextBuffer::CleanUpHandlers();
+ 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;
+ module->Init();
+ wxModule::RegisterModule(module);
+}
+
+
+/*!
+ * 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->GetClientSize();
+ wxPoint firstVisiblePt = 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_COMMAND_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_COMMAND_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:
+ {
+ ApplyParagraphs(GetNewParagraphs());
+
+ // 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(
+ wxEVT_COMMAND_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_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.
+ container->InvalidateHierarchy(GetRange());
+
+ UpdateAppearance(GetPosition());
+
+ wxRichTextEvent cmdEvent(
+ wxEVT_COMMAND_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);
+ // wxRichTextObject* obj = container->GetChildAtPosition(GetRange().GetStart());
+ if (obj && m_object)
+ {
+ wxRichTextObjectList::compatibility_iterator node = container->GetChildren().Find(obj);
+ if (node)
+ {
+ wxRichTextObject* obj = node->GetData();
+ node->SetData(m_object);
+ m_object = obj;
+ }
+ }
+
+ // 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());
+
+ // 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_COMMAND_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_COMMAND_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:
+ {
+ 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(
+ wxEVT_COMMAND_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_ATTRIBUTES:
+ case wxRICHTEXT_CHANGE_OBJECT:
+ {
+ return Do();
+ }
+ default:
+ break;
+ }
+
+ return true;