+/// 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(this, position+1, *richTextBuffer, GetRichTextCtrl(), 0);
+ if (GetRichTextCtrl())
+ GetRichTextCtrl()->ShowPosition(position + richTextBuffer->GetOwnRange().GetEnd());
+ delete richTextBuffer;
+ }
+ }
+ else if (wxTheClipboard->IsSupported(wxDF_TEXT)
+ #if wxUSE_UNICODE
+ || wxTheClipboard->IsSupported(wxDF_UNICODETEXT)
+ #endif
+ )
+ {
+ wxTextDataObject data;
+ wxTheClipboard->GetData(data);
+ wxString text(data.GetText());
+#ifdef __WXMSW__
+ wxString text2;
+ text2.Alloc(text.Length()+1);
+ size_t i;
+ for (i = 0; i < text.Length(); i++)
+ {
+ wxChar ch = text[i];
+ if (ch != wxT('\r'))
+ text2 += ch;
+ }
+#else
+ wxString text2 = text;
+#endif
+ container->InsertTextWithUndo(this, position+1, text2, GetRichTextCtrl(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE);
+
+ if (GetRichTextCtrl())
+ GetRichTextCtrl()->ShowPosition(position + text2.Length());
+
+ success = true;
+ }
+ else if (wxTheClipboard->IsSupported(wxDF_BITMAP))
+ {
+ wxBitmapDataObject data;
+ wxTheClipboard->GetData(data);
+ wxBitmap bitmap(data.GetBitmap());
+ wxImage image(bitmap.ConvertToImage());
+
+ wxRichTextAction* action = new wxRichTextAction(NULL, _("Insert Image"), wxRICHTEXT_INSERT, this, container, GetRichTextCtrl(), false);
+
+ action->GetNewParagraphs().AddImage(image);
+
+ if (action->GetNewParagraphs().GetChildCount() == 1)
+ action->GetNewParagraphs().SetPartialParagraph(true);
+
+ action->SetPosition(position+1);
+
+ // Set the range we'll need to delete in Undo
+ action->SetRange(wxRichTextRange(position+1, position+1));
+
+ SubmitAction(action);
+
+ success = true;
+ }
+ wxTheClipboard->Close();
+ }
+ }
+#else
+ wxUnusedVar(position);
+#endif
+ return success;
+}
+
+/// Can we paste from the clipboard?
+bool wxRichTextBuffer::CanPasteFromClipboard() const
+{
+ bool canPaste = false;
+#if wxUSE_CLIPBOARD && wxUSE_DATAOBJ
+ if (!wxTheClipboard->IsOpened() && wxTheClipboard->Open())
+ {
+ if (wxTheClipboard->IsSupported(wxDF_TEXT)
+#if wxUSE_UNICODE
+ || wxTheClipboard->IsSupported(wxDF_UNICODETEXT)
+#endif
+ || wxTheClipboard->IsSupported(wxDataFormat(wxRichTextBufferDataObject::GetRichTextBufferFormatId())) ||
+ wxTheClipboard->IsSupported(wxDF_BITMAP))
+ {
+ canPaste = true;
+ }
+ wxTheClipboard->Close();
+ }
+#endif
+ return canPaste;
+}
+
+/// Dumps contents of buffer for debugging purposes
+void wxRichTextBuffer::Dump()
+{
+ wxString text;
+ {
+ wxStringOutputStream stream(& text);
+ wxTextOutputStream textStream(stream);
+ Dump(textStream);
+ }
+
+ wxLogDebug(text);
+}
+
+/// Add an event handler
+bool wxRichTextBuffer::AddEventHandler(wxEvtHandler* handler)
+{
+ m_eventHandlers.Append(handler);
+ return true;
+}
+
+/// Remove an event handler
+bool wxRichTextBuffer::RemoveEventHandler(wxEvtHandler* handler, bool deleteHandler)
+{
+ wxList::compatibility_iterator node = m_eventHandlers.Find(handler);
+ if (node)
+ {
+ m_eventHandlers.Erase(node);
+ if (deleteHandler)
+ delete handler;
+
+ return true;
+ }
+ else
+ return false;
+}
+
+/// Clear event handlers
+void wxRichTextBuffer::ClearEventHandlers()
+{
+ m_eventHandlers.Clear();
+}
+
+/// Send event to event handlers. If sendToAll is true, will send to all event handlers,
+/// otherwise will stop at the first successful one.
+bool wxRichTextBuffer::SendEvent(wxEvent& event, bool sendToAll)
+{
+ bool success = false;
+ for (wxList::compatibility_iterator node = m_eventHandlers.GetFirst(); node; node = node->GetNext())
+ {
+ wxEvtHandler* handler = (wxEvtHandler*) node->GetData();
+ if (handler->ProcessEvent(event))
+ {
+ success = true;
+ if (!sendToAll)
+ return true;
+ }
+ }
+ return success;
+}
+
+/// Set style sheet and notify of the change
+bool wxRichTextBuffer::SetStyleSheetAndNotify(wxRichTextStyleSheet* sheet)
+{
+ wxRichTextStyleSheet* oldSheet = GetStyleSheet();
+
+ wxWindowID winid = wxID_ANY;
+ if (GetRichTextCtrl())
+ winid = GetRichTextCtrl()->GetId();
+
+ wxRichTextEvent event(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING, winid);
+ event.SetEventObject(GetRichTextCtrl());
+ event.SetContainer(GetRichTextCtrl()->GetFocusObject());
+ event.SetOldStyleSheet(oldSheet);
+ event.SetNewStyleSheet(sheet);
+ event.Allow();
+
+ if (SendEvent(event) && !event.IsAllowed())
+ {
+ if (sheet != oldSheet)
+ delete sheet;
+
+ return false;
+ }
+
+ if (oldSheet && oldSheet != sheet)
+ delete oldSheet;
+
+ SetStyleSheet(sheet);
+
+ event.SetEventType(wxEVT_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, wxRichTextDrawingContext& context, const wxPoint& pt, long& textPosition, wxRichTextObject** obj, wxRichTextObject** contextObj, int flags)
+{
+ int ret = wxRichTextParagraphLayoutBox::HitTest(dc, context, pt, textPosition, obj, contextObj, flags);
+ if (ret != wxRICHTEXT_HITTEST_NONE)
+ {
+ return ret;
+ }
+ else
+ {
+ textPosition = m_ownRange.GetEnd()-1;
+ *obj = this;
+ *contextObj = this;
+ return wxRICHTEXT_HITTEST_AFTER|wxRICHTEXT_HITTEST_OUTSIDE;
+ }
+}
+
+void wxRichTextBuffer::SetFontScale(double fontScale)
+{
+ m_fontScale = fontScale;
+ m_fontTable.SetFontScale(fontScale);
+}
+
+void wxRichTextBuffer::SetDimensionScale(double dimScale)
+{
+ m_dimensionScale = dimScale;
+}
+
+bool wxRichTextStdRenderer::DrawStandardBullet(wxRichTextParagraph* paragraph, wxDC& dc, const wxRichTextAttr& bulletAttr, const wxRect& rect)
+{
+ if (bulletAttr.GetTextColour().IsOk())
+ {
+ wxCheckSetPen(dc, wxPen(bulletAttr.GetTextColour()));
+ wxCheckSetBrush(dc, wxBrush(bulletAttr.GetTextColour()));
+ }
+ else
+ {
+ wxCheckSetPen(dc, *wxBLACK_PEN);
+ wxCheckSetBrush(dc, *wxBLACK_BRUSH);
+ }
+
+ wxFont font;
+ if (bulletAttr.HasFont())
+ {
+ font = paragraph->GetBuffer()->GetFontTable().FindFont(bulletAttr);
+ }
+ else
+ font = (*wxNORMAL_FONT);
+
+ wxCheckSetFont(dc, font);
+
+ int charHeight = dc.GetCharHeight();
+
+ int bulletWidth = (int) (((float) charHeight) * wxRichTextBuffer::GetBulletProportion());
+ int bulletHeight = bulletWidth;
+
+ int x = rect.x;
+
+ // Calculate the top position of the character (as opposed to the whole line height)
+ int y = rect.y + (rect.height - charHeight);
+
+ // Calculate where the bullet should be positioned
+ y = y + (charHeight+1)/2 - (bulletHeight+1)/2;
+
+ // The margin between a bullet and text.
+ int margin = paragraph->ConvertTenthsMMToPixels(dc, wxRichTextBuffer::GetBulletRightMargin());
+
+ if (bulletAttr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT)
+ x = rect.x + rect.width - bulletWidth - margin;
+ else if (bulletAttr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE)
+ x = x + (rect.width)/2 - bulletWidth/2;
+
+ if (bulletAttr.GetBulletName() == wxT("standard/square"))
+ {
+ dc.DrawRectangle(x, y, bulletWidth, bulletHeight);
+ }
+ else if (bulletAttr.GetBulletName() == wxT("standard/diamond"))
+ {
+ wxPoint pts[5];
+ pts[0].x = x; pts[0].y = y + bulletHeight/2;
+ pts[1].x = x + bulletWidth/2; pts[1].y = y;
+ pts[2].x = x + bulletWidth; pts[2].y = y + bulletHeight/2;
+ pts[3].x = x + bulletWidth/2; pts[3].y = y + bulletHeight;
+
+ dc.DrawPolygon(4, pts);
+ }
+ else if (bulletAttr.GetBulletName() == wxT("standard/triangle"))
+ {
+ wxPoint pts[3];
+ pts[0].x = x; pts[0].y = y;
+ pts[1].x = x + bulletWidth; pts[1].y = y + bulletHeight/2;
+ pts[2].x = x; pts[2].y = y + bulletHeight;
+
+ dc.DrawPolygon(3, pts);
+ }
+ else if (bulletAttr.GetBulletName() == wxT("standard/circle-outline"))
+ {
+ wxCheckSetBrush(dc, *wxTRANSPARENT_BRUSH);
+ dc.DrawEllipse(x, y, bulletWidth, bulletHeight);
+ }
+ else // "standard/circle", and catch-all
+ {
+ dc.DrawEllipse(x, y, bulletWidth, bulletHeight);
+ }
+
+ return true;
+}
+
+bool wxRichTextStdRenderer::DrawTextBullet(wxRichTextParagraph* paragraph, wxDC& dc, const wxRichTextAttr& attr, const wxRect& rect, const wxString& text)
+{
+ if (!text.empty())
+ {
+ wxFont font;
+ if ((attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL) && !attr.GetBulletFont().IsEmpty() && attr.HasFont())
+ {
+ wxRichTextAttr fontAttr;
+ if (attr.HasFontPixelSize())
+ fontAttr.SetFontPixelSize(attr.GetFontSize());
+ else
+ fontAttr.SetFontPointSize(attr.GetFontSize());
+ fontAttr.SetFontStyle(attr.GetFontStyle());
+ fontAttr.SetFontWeight(attr.GetFontWeight());
+ fontAttr.SetFontUnderlined(attr.GetFontUnderlined());
+ fontAttr.SetFontFaceName(attr.GetBulletFont());
+ font = paragraph->GetBuffer()->GetFontTable().FindFont(fontAttr);
+ }
+ else if (attr.HasFont())
+ font = paragraph->GetBuffer()->GetFontTable().FindFont(attr);
+ else
+ font = (*wxNORMAL_FONT);
+
+ wxCheckSetFont(dc, font);
+
+ if (attr.GetTextColour().IsOk())
+ dc.SetTextForeground(attr.GetTextColour());
+
+ dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT);
+
+ int charHeight = dc.GetCharHeight();
+ wxCoord tw, th;
+ dc.GetTextExtent(text, & tw, & th);
+
+ int x = rect.x;
+
+ // Calculate the top position of the character (as opposed to the whole line height)
+ int y = rect.y + (rect.height - charHeight);
+
+ // The margin between a bullet and text.
+ int margin = paragraph->ConvertTenthsMMToPixels(dc, wxRichTextBuffer::GetBulletRightMargin());
+
+ if (attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT)
+ x = (rect.x + rect.width) - tw - margin;
+ else if (attr.GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE)
+ x = x + (rect.width)/2 - tw/2;
+
+ dc.DrawText(text, x, y);
+
+ return true;
+ }
+ else
+ return false;
+}
+
+bool wxRichTextStdRenderer::DrawBitmapBullet(wxRichTextParagraph* WXUNUSED(paragraph), wxDC& WXUNUSED(dc), const wxRichTextAttr& WXUNUSED(attr), const wxRect& WXUNUSED(rect))
+{
+ // Currently unimplemented. The intention is to store bitmaps by name in a media store associated
+ // with the buffer. The store will allow retrieval from memory, disk or other means.
+ return false;
+}
+
+/// Enumerate the standard bullet names currently supported
+bool wxRichTextStdRenderer::EnumerateStandardBulletNames(wxArrayString& bulletNames)
+{
+ bulletNames.Add(wxTRANSLATE("standard/circle"));
+ bulletNames.Add(wxTRANSLATE("standard/circle-outline"));
+ bulletNames.Add(wxTRANSLATE("standard/square"));
+ bulletNames.Add(wxTRANSLATE("standard/diamond"));
+ bulletNames.Add(wxTRANSLATE("standard/triangle"));
+
+ return true;
+}
+
+/*!
+ * wxRichTextBox
+ */
+
+IMPLEMENT_DYNAMIC_CLASS(wxRichTextBox, wxRichTextParagraphLayoutBox)
+
+wxRichTextBox::wxRichTextBox(wxRichTextObject* parent):
+ wxRichTextParagraphLayoutBox(parent)
+{
+}
+
+/// Draw the item
+bool wxRichTextBox::Draw(wxDC& dc, wxRichTextDrawingContext& context, const wxRichTextRange& range, const wxRichTextSelection& selection, const wxRect& rect, int descent, int style)
+{
+ if (!IsShown())
+ return true;
+
+ // TODO: if the active object in the control, draw an indication.
+ // We need to add the concept of active object, and not just focus object,
+ // so we can apply commands (properties, delete, ...) to objects such as text boxes and images.
+ // Ultimately we would like to be able to interactively resize an active object
+ // using drag handles.
+ return wxRichTextParagraphLayoutBox::Draw(dc, context, range, selection, rect, descent, style);
+}
+
+/// Copy
+void wxRichTextBox::Copy(const wxRichTextBox& obj)
+{
+ wxRichTextParagraphLayoutBox::Copy(obj);
+}
+
+// Edit properties via a GUI
+bool wxRichTextBox::EditProperties(wxWindow* parent, wxRichTextBuffer* buffer)
+{
+ wxRichTextObjectPropertiesDialog boxDlg(this, wxGetTopLevelParent(parent), wxID_ANY, _("Box Properties"));
+ boxDlg.SetAttributes(GetAttributes());
+
+ if (boxDlg.ShowModal() == wxID_OK)
+ {
+ // By passing wxRICHTEXT_SETSTYLE_RESET, indeterminate attributes set by the user will be set as
+ // indeterminate in the object.
+ boxDlg.ApplyStyle(buffer->GetRichTextCtrl(), wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_RESET);
+ return true;
+ }
+ else
+ return false;
+}
+
+/*!
+ * wxRichTextField
+ */
+
+IMPLEMENT_DYNAMIC_CLASS(wxRichTextField, wxRichTextParagraphLayoutBox)
+
+wxRichTextField::wxRichTextField(const wxString& fieldType, wxRichTextObject* parent):
+ wxRichTextParagraphLayoutBox(parent)
+{
+ SetFieldType(fieldType);
+}
+
+/// Draw the item
+bool wxRichTextField::Draw(wxDC& dc, wxRichTextDrawingContext& context, const wxRichTextRange& range, const wxRichTextSelection& selection, const wxRect& rect, int descent, int style)
+{
+ if (!IsShown())
+ return true;
+
+ wxRichTextFieldType* fieldType = wxRichTextBuffer::FindFieldType(GetFieldType());
+ if (fieldType && fieldType->Draw(this, dc, context, range, selection, rect, descent, style))
+ return true;
+
+ // Fallback; but don't draw guidelines.
+ style &= ~wxRICHTEXT_DRAW_GUIDELINES;
+ return wxRichTextParagraphLayoutBox::Draw(dc, context, range, selection, rect, descent, style);
+}
+
+bool wxRichTextField::Layout(wxDC& dc, wxRichTextDrawingContext& context, const wxRect& rect, const wxRect& parentRect, int style)
+{
+ wxRichTextFieldType* fieldType = wxRichTextBuffer::FindFieldType(GetFieldType());
+ if (fieldType && fieldType->Layout(this, dc, context, rect, parentRect, style))
+ return true;
+
+ // Fallback
+ return wxRichTextParagraphLayoutBox::Layout(dc, context, rect, parentRect, style);
+}
+
+bool wxRichTextField::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, wxRichTextDrawingContext& context, int flags, wxPoint position, wxArrayInt* partialExtents) const
+{
+ wxRichTextFieldType* fieldType = wxRichTextBuffer::FindFieldType(GetFieldType());
+ if (fieldType)
+ return fieldType->GetRangeSize((wxRichTextField*) this, range, size, descent, dc, context, flags, position, partialExtents);
+
+ return wxRichTextParagraphLayoutBox::GetRangeSize(range, size, descent, dc, context, flags, position, partialExtents);
+}
+
+/// Calculate range
+void wxRichTextField::CalculateRange(long start, long& end)
+{
+ if (IsTopLevel())
+ wxRichTextParagraphLayoutBox::CalculateRange(start, end);
+ else
+ wxRichTextObject::CalculateRange(start, end);
+}
+
+/// Copy
+void wxRichTextField::Copy(const wxRichTextField& obj)
+{
+ wxRichTextParagraphLayoutBox::Copy(obj);
+
+ UpdateField(GetBuffer());
+}
+
+// Edit properties via a GUI
+bool wxRichTextField::EditProperties(wxWindow* parent, wxRichTextBuffer* buffer)
+{
+ wxRichTextFieldType* fieldType = wxRichTextBuffer::FindFieldType(GetFieldType());
+ if (fieldType)
+ return fieldType->EditProperties(this, parent, buffer);
+
+ return false;
+}
+
+bool wxRichTextField::CanEditProperties() const
+{
+ wxRichTextFieldType* fieldType = wxRichTextBuffer::FindFieldType(GetFieldType());
+ if (fieldType)
+ return fieldType->CanEditProperties((wxRichTextField*) this);
+
+ return false;
+}
+
+wxString wxRichTextField::GetPropertiesMenuLabel() const
+{
+ wxRichTextFieldType* fieldType = wxRichTextBuffer::FindFieldType(GetFieldType());
+ if (fieldType)
+ return fieldType->GetPropertiesMenuLabel((wxRichTextField*) this);
+
+ return wxEmptyString;
+}
+
+bool wxRichTextField::UpdateField(wxRichTextBuffer* buffer)
+{
+ wxRichTextFieldType* fieldType = wxRichTextBuffer::FindFieldType(GetFieldType());
+ if (fieldType)
+ return fieldType->UpdateField(buffer, (wxRichTextField*) this);
+
+ return false;
+}
+
+bool wxRichTextField::IsTopLevel() const
+{
+ wxRichTextFieldType* fieldType = wxRichTextBuffer::FindFieldType(GetFieldType());
+ if (fieldType)
+ return fieldType->IsTopLevel((wxRichTextField*) this);
+
+ return true;
+}
+
+IMPLEMENT_CLASS(wxRichTextFieldType, wxObject)
+
+IMPLEMENT_CLASS(wxRichTextFieldTypeStandard, wxRichTextFieldType)
+
+wxRichTextFieldTypeStandard::wxRichTextFieldTypeStandard(const wxString& name, const wxString& label, int displayStyle)
+{
+ Init();
+
+ SetName(name);
+ SetLabel(label);
+ SetDisplayStyle(displayStyle);
+}
+
+wxRichTextFieldTypeStandard::wxRichTextFieldTypeStandard(const wxString& name, const wxBitmap& bitmap, int displayStyle)
+{
+ Init();
+
+ SetName(name);
+ SetBitmap(bitmap);
+ SetDisplayStyle(displayStyle);
+}
+
+void wxRichTextFieldTypeStandard::Init()
+{
+ m_displayStyle = wxRICHTEXT_FIELD_STYLE_RECTANGLE;
+ m_font = wxFont(6, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);
+ m_textColour = *wxWHITE;
+ m_borderColour = *wxBLACK;
+ m_backgroundColour = *wxBLACK;
+ m_verticalPadding = 1;
+ m_horizontalPadding = 3;
+ m_horizontalMargin = 2;
+ m_verticalMargin = 0;
+}
+
+void wxRichTextFieldTypeStandard::Copy(const wxRichTextFieldTypeStandard& field)
+{
+ wxRichTextFieldType::Copy(field);
+
+ m_label = field.m_label;
+ m_displayStyle = field.m_displayStyle;
+ m_font = field.m_font;
+ m_textColour = field.m_textColour;
+ m_borderColour = field.m_borderColour;
+ m_backgroundColour = field.m_backgroundColour;
+ m_verticalPadding = field.m_verticalPadding;
+ m_horizontalPadding = field.m_horizontalPadding;
+ m_horizontalMargin = field.m_horizontalMargin;
+ m_bitmap = field.m_bitmap;
+}
+
+bool wxRichTextFieldTypeStandard::Draw(wxRichTextField* obj, wxDC& dc, wxRichTextDrawingContext& WXUNUSED(context), const wxRichTextRange& WXUNUSED(range), const wxRichTextSelection& selection, const wxRect& rect, int descent, int WXUNUSED(style))
+{
+ if (m_displayStyle == wxRICHTEXT_FIELD_STYLE_COMPOSITE)
+ return false; // USe default composite drawing
+ else // if (m_displayStyle == wxRICHTEXT_FIELD_STYLE_RECTANGLE || m_displayStyle == wxRICHTEXT_FIELD_STYLE_NOBORDER)
+ {
+ int borderSize = 1;
+
+ wxPen borderPen(m_borderColour, 1, wxSOLID);
+ wxBrush backgroundBrush(m_backgroundColour);
+ wxColour textColour(m_textColour);
+
+ if (selection.WithinSelection(obj->GetRange().GetStart(), obj))
+ {
+ wxColour highlightColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT));
+ wxColour highlightTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT));
+
+ borderPen = wxPen(highlightTextColour, 1, wxSOLID);
+ backgroundBrush = wxBrush(highlightColour);
+
+ wxCheckSetBrush(dc, backgroundBrush);
+ wxCheckSetPen(dc, wxPen(highlightColour, 1, wxSOLID));
+ dc.DrawRectangle(rect);
+ }
+
+ if (m_displayStyle != wxRICHTEXT_FIELD_STYLE_NO_BORDER)
+ borderSize = 0;
+
+ // objectRect is the area where the content is drawn, after margins around it have been taken into account
+ wxRect objectRect = wxRect(wxPoint(rect.x + m_horizontalMargin, rect.y + wxMax(0, rect.height - descent - obj->GetCachedSize().y)),
+ wxSize(obj->GetCachedSize().x - 2*m_horizontalMargin - borderSize, obj->GetCachedSize().y));
+
+ // clientArea is where the text is actually written
+ wxRect clientArea = objectRect;
+
+ if (m_displayStyle == wxRICHTEXT_FIELD_STYLE_RECTANGLE)
+ {
+ dc.SetPen(borderPen);
+ dc.SetBrush(backgroundBrush);
+ dc.DrawRoundedRectangle(objectRect, 4.0);
+ }
+ else if (m_displayStyle == wxRICHTEXT_FIELD_STYLE_START_TAG)
+ {
+ int arrowLength = objectRect.height/2;
+ clientArea.width -= (arrowLength - m_horizontalPadding);
+
+ wxPoint pts[5];
+ pts[0].x = objectRect.x; pts[0].y = objectRect.y;
+ pts[1].x = objectRect.x + objectRect.width - arrowLength; pts[1].y = objectRect.y;
+ pts[2].x = objectRect.x + objectRect.width; pts[2].y = objectRect.y + (objectRect.height/2);
+ pts[3].x = objectRect.x + objectRect.width - arrowLength; pts[3].y = objectRect.y + objectRect.height;
+ pts[4].x = objectRect.x; pts[4].y = objectRect.y + objectRect.height;
+ dc.SetPen(borderPen);
+ dc.SetBrush(backgroundBrush);
+ dc.DrawPolygon(5, pts);
+ }
+ else if (m_displayStyle == wxRICHTEXT_FIELD_STYLE_END_TAG)
+ {
+ int arrowLength = objectRect.height/2;
+ clientArea.width -= (arrowLength - m_horizontalPadding);
+ clientArea.x += (arrowLength - m_horizontalPadding);
+
+ wxPoint pts[5];
+ pts[0].x = objectRect.x + objectRect.width; pts[0].y = objectRect.y;
+ pts[1].x = objectRect.x + arrowLength; pts[1].y = objectRect.y;
+ pts[2].x = objectRect.x; pts[2].y = objectRect.y + (objectRect.height/2);
+ pts[3].x = objectRect.x + arrowLength; pts[3].y = objectRect.y + objectRect.height;
+ pts[4].x = objectRect.x + objectRect.width; pts[4].y = objectRect.y + objectRect.height;
+ dc.SetPen(borderPen);
+ dc.SetBrush(backgroundBrush);
+ dc.DrawPolygon(5, pts);
+ }
+
+ if (m_bitmap.IsOk())
+ {
+ int x = clientArea.x + (clientArea.width - m_bitmap.GetWidth())/2;
+ int y = clientArea.y + m_verticalPadding;
+ dc.DrawBitmap(m_bitmap, x, y, true);
+
+ if (selection.WithinSelection(obj->GetRange().GetStart(), obj))
+ {
+ wxCheckSetBrush(dc, *wxBLACK_BRUSH);
+ wxCheckSetPen(dc, *wxBLACK_PEN);
+ dc.SetLogicalFunction(wxINVERT);
+ dc.DrawRectangle(wxRect(x, y, m_bitmap.GetWidth(), m_bitmap.GetHeight()));
+ dc.SetLogicalFunction(wxCOPY);
+ }
+ }
+ else
+ {
+ wxString label(m_label);
+ if (label.IsEmpty())
+ label = wxT("??");
+ int w, h, maxDescent;
+ dc.SetFont(m_font);
+ dc.GetTextExtent(m_label, & w, &h, & maxDescent);
+ dc.SetTextForeground(textColour);
+
+ int x = clientArea.x + (clientArea.width - w)/2;
+ int y = clientArea.y + (clientArea.height - (h - maxDescent))/2;
+ dc.DrawText(m_label, x, y);
+ }
+ }
+
+ return true;
+}
+
+bool wxRichTextFieldTypeStandard::Layout(wxRichTextField* obj, wxDC& dc, wxRichTextDrawingContext& context, const wxRect& WXUNUSED(rect), const wxRect& WXUNUSED(parentRect), int style)
+{
+ if (m_displayStyle == wxRICHTEXT_FIELD_STYLE_COMPOSITE)
+ return false; // USe default composite layout
+
+ wxSize size = GetSize(obj, dc, context, style);
+ obj->SetCachedSize(size);
+ obj->SetMinSize(size);
+ obj->SetMaxSize(size);
+ return true;
+}
+
+bool wxRichTextFieldTypeStandard::GetRangeSize(wxRichTextField* obj, const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, wxRichTextDrawingContext& context, int flags, wxPoint position, wxArrayInt* partialExtents) const
+{
+ if (IsTopLevel(obj))
+ return obj->wxRichTextParagraphLayoutBox::GetRangeSize(range, size, descent, dc, context, flags, position);
+ else
+ {
+ wxSize sz = GetSize(obj, dc, context, 0);
+ if (partialExtents)
+ {
+ int lastSize;
+ if (partialExtents->GetCount() > 0)
+ lastSize = (*partialExtents)[partialExtents->GetCount()-1];
+ else
+ lastSize = 0;
+ partialExtents->Add(lastSize + sz.x);
+ }
+ size = sz;
+ return true;
+ }
+}
+
+wxSize wxRichTextFieldTypeStandard::GetSize(wxRichTextField* WXUNUSED(obj), wxDC& dc, wxRichTextDrawingContext& WXUNUSED(context), int WXUNUSED(style)) const
+{
+ int borderSize = 1;
+ int w = 0, h = 0, maxDescent = 0;
+
+ wxSize sz;
+ if (m_bitmap.IsOk())
+ {
+ w = m_bitmap.GetWidth();
+ h = m_bitmap.GetHeight();
+
+ sz = wxSize(w + m_horizontalMargin*2, h + m_verticalMargin*2);
+ }
+ else
+ {
+ wxString label(m_label);
+ if (label.IsEmpty())
+ label = wxT("??");
+ dc.SetFont(m_font);
+ dc.GetTextExtent(label, & w, &h, & maxDescent);
+
+ sz = wxSize(w + m_horizontalPadding*2 + m_horizontalMargin*2, h + m_verticalPadding *2 + m_verticalMargin*2);
+ }
+
+ if (m_displayStyle != wxRICHTEXT_FIELD_STYLE_NO_BORDER)
+ {
+ sz.x += borderSize*2;
+ sz.y += borderSize*2;
+ }
+
+ if (m_displayStyle == wxRICHTEXT_FIELD_STYLE_START_TAG || m_displayStyle == wxRICHTEXT_FIELD_STYLE_END_TAG)
+ {
+ // Add space for the arrow
+ sz.x += (sz.y/2 - m_horizontalPadding);
+ }
+
+ return sz;
+}
+
+IMPLEMENT_DYNAMIC_CLASS(wxRichTextCell, wxRichTextBox)
+
+wxRichTextCell::wxRichTextCell(wxRichTextObject* parent):
+ wxRichTextBox(parent)
+{
+}
+
+/// Draw the item
+bool wxRichTextCell::Draw(wxDC& dc, wxRichTextDrawingContext& context, const wxRichTextRange& range, const wxRichTextSelection& selection, const wxRect& rect, int descent, int style)
+{
+ return wxRichTextBox::Draw(dc, context, range, selection, rect, descent, style);
+}
+
+/// 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(wxCLASSINFO(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, wxRichTextDrawingContext& context, const wxRichTextRange& range, const wxRichTextSelection& selection, const wxRect& rect, int descent, int style)
+{
+ return wxRichTextBox::Draw(dc, context, range, selection, rect, descent, style);
+}
+
+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, wxRichTextDrawingContext& context, const wxRect& rect, const wxRect& WXUNUSED(parentRect), 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, context, rect);
+ wxTextAttrDimensionConverter converter(dc, scale, availableSpace.GetSize());
+
+ wxRichTextAttr attr(GetAttributes());
+ context.ApplyVirtualAttributes(attr, this);
+
+ // 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 (attr.GetTextBoxAttr().GetWidth().IsValid())
+ {
+ tableWidth = converter.GetPixels(attr.GetTextBoxAttr().GetWidth());
+
+ // Fixed table width, so we do want to stretch columns out if necessary.
+ stretchToFitTableWidth = true;
+
+ // Shouldn't be able to exceed the size passed to this function
+ tableWidth = wxMin(rect.width, tableWidth);
+ }
+
+ // Get internal padding
+ int paddingLeft = 0, paddingTop = 0;
+ if (attr.GetTextBoxAttr().GetPadding().GetLeft().IsValid())
+ paddingLeft = converter.GetPixels(attr.GetTextBoxAttr().GetPadding().GetLeft());
+ if (attr.GetTextBoxAttr().GetPadding().GetTop().IsValid())
+ paddingTop = converter.GetPixels(attr.GetTextBoxAttr().GetPadding().GetTop());
+
+ // Assume that left and top padding are also used for inter-cell padding.
+ int paddingX = paddingLeft;
+ int paddingY = paddingTop;
+
+ int totalLeftMargin = 0, totalRightMargin = 0, totalTopMargin = 0, totalBottomMargin = 0;
+ GetTotalMargin(dc, buffer, attr, totalLeftMargin, totalRightMargin, totalTopMargin, totalBottomMargin);
+
+ // Internal table width - the area for content
+ int internalTableWidth = tableWidth - totalLeftMargin - totalRightMargin;
+
+ int rowCount = m_cells.GetCount();
+ if (m_colCount == 0 || rowCount == 0)
+ {
+ wxRect overallRect(rect.x, rect.y, totalLeftMargin + totalRightMargin, totalTopMargin + totalBottomMargin);
+ SetCachedSize(overallRect.GetSize());
+
+ // Zero content size
+ SetMinSize(overallRect.GetSize());
+ SetMaxSize(GetMinSize());
+ return true;
+ }
+
+ // The final calculated widths
+ wxArrayInt colWidths;
+ colWidths.Add(0, m_colCount);
+
+ wxArrayInt absoluteColWidths;
+ absoluteColWidths.Add(0, m_colCount);
+
+ wxArrayInt percentageColWidths;
+ percentageColWidths.Add(0, m_colCount);
+ // wxArrayInt percentageColWidthsSpanning(m_colCount);
+ // These are only relevant when the first column contains spanning information.
+ // wxArrayInt columnSpans(m_colCount); // Each contains 1 for non-spanning cell, > 1 for spanning cell.
+ wxArrayInt maxColWidths;
+ maxColWidths.Add(0, m_colCount);
+ wxArrayInt minColWidths;
+ minColWidths.Add(0, m_colCount);
+
+ wxSize tableSize(tableWidth, 0);
+
+ int i, j, k;
+
+ for (i = 0; i < m_colCount; i++)
+ {
+ absoluteColWidths[i] = 0;
+ // absoluteColWidthsSpanning[i] = 0;
+ percentageColWidths[i] = -1;
+ // percentageColWidthsSpanning[i] = -1;
+ colWidths[i] = 0;
+ maxColWidths[i] = 0;
+ minColWidths[i] = 0;
+ // columnSpans[i] = 1;
+ }
+
+ // (0) Determine which cells are visible according to spans
+ // 1 2 3 4 5
+ // __________________
+ // | | | | | 1
+ // |------| |----|
+ // |------| | | 2
+ // |------| | | 3
+ // |------------------|
+ // |__________________| 4
+
+ // To calculate cell visibility:
+ // First find all spanning cells. Build an array of span records with start x, y and end x, y.
+ // Then for each cell, test whether we're within one of those cells, and unless we're at the start of
+ // that cell, hide the cell.
+
+ // We can also use this array to match the size of spanning cells to the grid. Or just do
+ // this when we iterate through all cells.
+
+ // 0.1: add spanning cells to an array
+ wxRichTextRectArray rectArray;
+ for (j = 0; j < m_rowCount; j++)
+ {
+ for (i = 0; i < m_colCount; i++)
+ {
+ 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, context, availableSpace, availableSpace, style);
+
+ if (colSpan == 1)
+ {
+ int absoluteCellWidth = -1;
+ int percentageCellWidth = -1;
+
+ // I think we need to calculate percentages from the internal table size,
+ // minus the padding between cells which we'll need to calculate from the
+ // (number of VISIBLE cells - 1)*paddingX. Then percentages that add up to 100%
+ // will add up to 100%. In CSS, the width specifies the cell's content rect width,
+ // so if we want to conform to that we'll need to add in the overall cell margins.
+ // However, this will make it difficult to specify percentages that add up to
+ // 100% and still fit within the table width.
+ // Let's say two cells have 50% width. They have 10 pixels of overall margin each.
+ // The table content rect is 500 pixels and the inter-cell padding is 20 pixels.
+ // If we're using internal content size for the width, we would calculate the
+ // the overall cell width for n cells as:
+ // (500 - 20*(n-1) - overallCellMargin1 - overallCellMargin2 - ...) * percentage / 100
+ // + thisOverallCellMargin
+ // = 500 - 20 - 10 - 10) * 0.5 + 10 = 240 pixels overall cell width.
+ // Adding this back, we get 240 + 240 + 20 = 500 pixels.
+
+ if (cell->GetAttributes().GetTextBoxAttr().GetWidth().IsValid())
+ {
+ int w = converter.GetPixels(cell->GetAttributes().GetTextBoxAttr().GetWidth());
+ if (cell->GetAttributes().GetTextBoxAttr().GetWidth().GetUnits() == wxTEXT_ATTR_UNITS_PERCENTAGE)
+ {
+ percentageCellWidth = w;
+ }
+ else
+ {
+ absoluteCellWidth = w;
+ }
+ // Override absolute width with minimum width if necessary
+ if (cell->GetMinSize().x > 0 && absoluteCellWidth !=1 && cell->GetMinSize().x > absoluteCellWidth)
+ absoluteCellWidth = cell->GetMinSize().x;
+ }
+
+ if (absoluteCellWidth != -1)
+ {
+ if (absoluteCellWidth > absoluteColWidths[i])
+ absoluteColWidths[i] = absoluteCellWidth;
+ }
+
+ if (percentageCellWidth != -1)
+ {
+ if (percentageCellWidth > percentageColWidths[i])
+ percentageColWidths[i] = percentageCellWidth;
+ }
+
+ if (colSpan == 1 && cell->GetMinSize().x && cell->GetMinSize().x > minColWidths[i])
+ minColWidths[i] = cell->GetMinSize().x;
+ if (colSpan == 1 && cell->GetMaxSize().x && cell->GetMaxSize().x > maxColWidths[i])
+ maxColWidths[i] = cell->GetMaxSize().x;
+ }
+ }
+ }
+ }
+
+ // (2) Allocate initial column widths from minimum widths, absolute values and proportions
+ // TODO: simply merge this into (1).
+ for (i = 0; i < m_colCount; i++)
+ {
+ if (absoluteColWidths[i] > 0)
+ {
+ colWidths[i] = absoluteColWidths[i];
+ }
+ else if (percentageColWidths[i] > 0)
+ {
+ colWidths[i] = percentageColWidths[i];
+
+ // This is rubbish - we calculated the absolute widths from percentages, so
+ // we can't do it again here.
+ //colWidths[i] = (int) (double(percentageColWidths[i]) * double(tableWidth) / 100.0 + 0.5);
+ }
+ }
+
+ // (3) Process absolute or proportional widths of spanning columns,
+ // now that we know what our fixed column widths are going to be.
+ // Spanned cells will try to adjust columns so the span will fit.
+ // Even existing fixed column widths can be expanded if necessary.
+ // Actually, currently fixed columns widths aren't adjusted; instead,
+ // the algorithm favours earlier rows and adjusts unspecified column widths
+ // the first time only. After that, we can't know whether the column has been
+ // specified explicitly or not. (We could make a note if necessary.)
+ for (j = 0; j < m_rowCount; j++)
+ {
+ // First get the overall margins so we can calculate percentage widths based on
+ // the available content space for all cells on the row
+
+ int overallRowContentMargin = 0;
+ int visibleCellCount = 0;
+
+ for (i = 0; i < m_colCount; i++)
+ {
+ wxRichTextBox* cell = GetCell(j, i);
+ if (cell->IsShown())
+ {
+ int cellTotalLeftMargin = 0, cellTotalRightMargin = 0, cellTotalTopMargin = 0, cellTotalBottomMargin = 0;
+ GetTotalMargin(dc, buffer, cell->GetAttributes(), cellTotalLeftMargin, cellTotalRightMargin, cellTotalTopMargin, cellTotalBottomMargin);
+
+ overallRowContentMargin += (cellTotalLeftMargin + cellTotalRightMargin);
+ visibleCellCount ++;
+ }
+ }
+
+ // Add in inter-cell padding
+ overallRowContentMargin += ((visibleCellCount-1) * paddingX);
+
+ int rowContentWidth = internalTableWidth - overallRowContentMargin;
+ wxSize rowTableSize(rowContentWidth, 0);
+ wxTextAttrDimensionConverter converter(dc, scale, rowTableSize);
+
+ for (i = 0; i < m_colCount; i++)
+ {
+ 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;
+ actualWidths.Add(0, m_colCount);
+
+ wxTextAttrDimensionConverter converter(dc, scale);
+ for (i = 0; i < m_colCount; i++)
+ {
+ wxRichTextCell* cell = GetCell(j, i);
+ if (cell->IsShown())
+ {
+ // Get max specified cell height
+ // Don't handle percentages for height
+ if (cell->GetAttributes().GetTextBoxAttr().GetHeight().IsValid() && cell->GetAttributes().GetTextBoxAttr().GetHeight().GetUnits() != wxTEXT_ATTR_UNITS_PERCENTAGE)
+ {
+ int h = converter.GetPixels(cell->GetAttributes().GetTextBoxAttr().GetHeight());
+ if (h > maxSpecifiedCellHeight)
+ maxSpecifiedCellHeight = h;
+ }
+
+ if (colWidths[i] > 0) // absolute or proportional width has been specified
+ {
+ int colSpan = 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, context, availableCellSpace, availableSpace, 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, context, availableCellSpace, availableSpace, style);
+
+ // Make sure the cell size really is the appropriate size,
+ // not the calculated box size
+ cell->SetCachedSize(wxSize(actualWidths[i], maxCellHeight));
+
+ maxRight = wxMax(maxRight, cell->GetPosition().x + cell->GetCachedSize().x);
+ }
+ }
+
+ y += maxCellHeight;
+ if (j < (m_rowCount-1))
+ y += paddingY;
+ }
+
+ // We need to add back the margins etc.
+ {
+ wxRect marginRect, borderRect, contentRect, paddingRect, outlineRect;
+ contentRect = wxRect(wxPoint(0, 0), wxSize(maxRight - availableSpace.x, y - availableSpace.y));
+ GetBoxRects(dc, GetBuffer(), attr, marginRect, borderRect, contentRect, paddingRect, outlineRect);
+ SetCachedSize(marginRect.GetSize());
+ }
+
+ // TODO: calculate max size
+ {
+ SetMaxSize(GetCachedSize());
+ }
+
+ // TODO: calculate min size
+ {
+ SetMinSize(GetCachedSize());
+ }
+
+ // TODO: currently we use either a fixed table width or the parent's size.
+ // We also want to be able to calculate the table width from its content,
+ // whether using fixed column widths or cell content min/max width.
+ // Probably need a boolean flag to say whether we need to stretch cells
+ // to fit the table width, or to simply use min/max cell widths. The
+ // trouble with this is that if cell widths are not specified, they
+ // will be tiny; we could use arbitrary defaults but this seems unsatisfactory.
+ // Anyway, ignoring that problem, we probably need to factor layout into a function
+ // that can can calculate the maximum unconstrained layout in case table size is
+ // not specified. Then LayoutToBestSize() can choose to use either parent size to
+ // constrain Layout(), or the previously-calculated max size to constraint layout.
+
+ return true;
+}
+
+// Finds the absolute position and row height for the given character position
+bool wxRichTextTable::FindPosition(wxDC& dc, wxRichTextDrawingContext& context, long index, wxPoint& pt, int* height, bool forceLineStart)
+{
+ wxRichTextCell* child = GetCell(index+1);
+ if (child)
+ {
+ // Find the position at the start of the child cell, since the table doesn't
+ // have any caret position of its own.
+ return child->FindPosition(dc, context, -1, pt, height, forceLineStart);
+ }
+ else
+ return false;
+}
+
+// Get the cell at the given character position (in the range of the table).
+wxRichTextCell* wxRichTextTable::GetCell(long pos) const
+{
+ int row = 0, col = 0;
+ if (GetCellRowColumnPosition(pos, row, col))
+ {
+ return GetCell(row, col);
+ }
+ else
+ return NULL;
+}
+
+// Get the row/column for a given character position
+bool wxRichTextTable::GetCellRowColumnPosition(long pos, int& row, int& col) const
+{
+ if (m_colCount == 0 || m_rowCount == 0)
+ return false;
+
+ row = (int) (pos / m_colCount);
+ col = pos - (row * m_colCount);
+
+ wxASSERT(row < m_rowCount && col < m_colCount);
+
+ if (row < m_rowCount && col < m_colCount)
+ return true;
+ else
+ return false;
+}
+
+// Calculate range, taking row/cell ordering into account instead of relying
+// on list ordering.
+void wxRichTextTable::CalculateRange(long start, long& end)
+{
+ long current = start;
+ long lastEnd = current;
+
+ if (IsTopLevel())
+ {
+ current = 0;
+ lastEnd = 0;
+ }
+
+ int i, j;
+ for (i = 0; i < m_rowCount; i++)
+ {
+ for (j = 0; j < m_colCount; j++)
+ {
+ wxRichTextCell* child = GetCell(i, j);
+ if (child)
+ {
+ long childEnd = 0;
+
+ child->CalculateRange(current, childEnd);
+
+ lastEnd = childEnd;
+ current = childEnd + 1;
+ }
+ }
+ }
+
+ // A top-level object always has a range of size 1,
+ // because its children don't count at this level.
+ end = start;
+ m_range.SetRange(start, start);
+
+ // An object with no children has zero length
+ if (m_children.GetCount() == 0)
+ lastEnd --;
+ m_ownRange.SetRange(0, lastEnd);
+}
+
+// Gets the range size.
+bool wxRichTextTable::GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, wxRichTextDrawingContext& context, int flags, wxPoint position, wxArrayInt* partialExtents) const
+{
+ return wxRichTextBox::GetRangeSize(range, size, descent, dc, context, 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 NULL;
+}
+
+// Returns a selection object specifying the selections between start and end character positions.
+// For example, a table would deduce what cells (of range length 1) are selected when dragging across the table.
+wxRichTextSelection wxRichTextTable::GetSelection(long start, long end) const
+{
+ wxRichTextSelection selection;
+ selection.SetContainer((wxRichTextTable*) this);
+
+ if (start > end)
+ {
+ long tmp = end;
+ end = start;
+ start = tmp;
+ }
+
+ wxASSERT( start >= 0 && end < (m_colCount * m_rowCount));
+
+ if (end >= (m_colCount * m_rowCount))
+ return selection;
+
+ // We need to find the rectangle of cells that is described by the rectangle
+ // with start, end as the diagonal. Make sure we don't add cells that are
+ // not currenty visible because they are overlapped by spanning cells.
+/*
+ --------------------------
+ | 0 | 1 | 2 | 3 | 4 |
+ --------------------------
+ | 5 | 6 | 7 | 8 | 9 |
+ --------------------------
+ | 10 | 11 | 12 | 13 | 14 |
+ --------------------------
+ | 15 | 16 | 17 | 18 | 19 |
+ --------------------------
+
+ Let's say we select 6 -> 18.
+
+ Left and right edge cols of rectangle are 1 and 3 inclusive. Find least/greatest to find
+ which is left and which is right.
+
+ Top and bottom edge rows are 1 and 3 inclusive. Again, find least/greatest to find top and bottom.
+
+ Now go through rows from 1 to 3 and only add cells that are (a) within above column range
+ and (b) shown.
+
+
+*/
+
+ int leftCol = start - m_colCount * int(start/m_colCount);
+ int rightCol = end - m_colCount * int(end/m_colCount);
+
+ int topRow = int(start/m_colCount);
+ int bottomRow = int(end/m_colCount);
+
+ if (leftCol > rightCol)
+ {
+ int tmp = rightCol;
+ rightCol = leftCol;
+ leftCol = tmp;
+ }
+
+ if (topRow > bottomRow)
+ {
+ int tmp = bottomRow;
+ bottomRow = topRow;
+ topRow = tmp;
+ }
+
+ int i, j;
+ for (i = topRow; i <= bottomRow; i++)
+ {
+ for (j = leftCol; j <= rightCol; j++)
+ {
+ wxRichTextCell* cell = GetCell(i, j);
+ if (cell && cell->IsShown())
+ selection.Add(cell->GetRange());
+ }
+ }
+
+ return selection;
+}
+
+// Sets the attributes for the cells specified by the selection.
+bool wxRichTextTable::SetCellStyle(const wxRichTextSelection& selection, const wxRichTextAttr& style, int flags)
+{
+ if (selection.GetContainer() != this)
+ return false;
+
+ wxRichTextBuffer* buffer = GetBuffer();
+ bool haveControl = (buffer && buffer->GetRichTextCtrl() != NULL);
+ bool withUndo = haveControl && ((flags & wxRICHTEXT_SETSTYLE_WITH_UNDO) != 0);
+
+ if (withUndo)
+ buffer->BeginBatchUndo(_("Set Cell Style"));
+
+ wxRichTextObjectList::compatibility_iterator node = m_children.GetFirst();
+ while (node)
+ {
+ wxRichTextCell* cell = wxDynamicCast(node->GetData(), wxRichTextCell);
+ if (cell && selection.WithinSelection(cell->GetRange().GetStart()))
+ SetStyle(cell, style, flags);
+ node = node->GetNext();
+ }
+
+ // Do action, or delay it until end of batch.
+ if (withUndo)
+ buffer->EndBatchUndo();
+
+ return true;
+}
+
+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();
+
+ wxRichTextXMLHandler::RegisterNodeName(wxT("text"), wxT("wxRichTextPlainText"));
+ wxRichTextXMLHandler::RegisterNodeName(wxT("symbol"), wxT("wxRichTextPlainText"));
+ wxRichTextXMLHandler::RegisterNodeName(wxT("image"), wxT("wxRichTextImage"));
+ wxRichTextXMLHandler::RegisterNodeName(wxT("paragraph"), wxT("wxRichTextParagraph"));
+ wxRichTextXMLHandler::RegisterNodeName(wxT("paragraphlayout"), wxT("wxRichTextParagraphLayoutBox"));
+ wxRichTextXMLHandler::RegisterNodeName(wxT("textbox"), wxT("wxRichTextBox"));
+ wxRichTextXMLHandler::RegisterNodeName(wxT("cell"), wxT("wxRichTextCell"));
+ wxRichTextXMLHandler::RegisterNodeName(wxT("table"), wxT("wxRichTextTable"));
+ wxRichTextXMLHandler::RegisterNodeName(wxT("field"), wxT("wxRichTextField"));
+
+ return true;
+ }
+ void OnExit()
+ {
+ wxRichTextBuffer::CleanUpHandlers();
+ wxRichTextBuffer::CleanUpDrawingHandlers();
+ wxRichTextBuffer::CleanUpFieldTypes();
+ wxRichTextXMLHandler::ClearNodeToClassMap();
+ wxRichTextDecimalToRoman(-1);
+ wxRichTextParagraph::ClearDefaultTabs();
+ wxRichTextCtrl::ClearAvailableFontNames();
+ wxRichTextBuffer::SetRenderer(NULL);
+ }
+};
+
+IMPLEMENT_DYNAMIC_CLASS(wxRichTextModule, wxModule)
+
+
+// If the richtext lib is dynamically loaded after the app has already started
+// (such as from wxPython) then the built-in module system will not init this
+// module. Provide this function to do it manually.
+void wxRichTextModuleInit()
+{
+ wxModule* module = new wxRichTextModule;
+ 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->GetUnscaledSize(m_ctrl->GetClientSize());
+ wxPoint firstVisiblePt = m_ctrl->GetUnscaledPoint(m_ctrl->GetFirstVisiblePoint());
+ int lastY = firstVisiblePt.y + clientSize.y;
+
+ wxRichTextParagraph* para = container->GetParagraphAtPosition(GetRange().GetStart());
+ wxRichTextObjectList::compatibility_iterator node = container->GetChildren().Find(para);
+ while (node)
+ {
+ wxRichTextParagraph* child = (wxRichTextParagraph*) node->GetData();
+ wxRichTextLineList::compatibility_iterator node2 = child->GetLines().GetFirst();
+ while (node2)
+ {
+ wxRichTextLine* line = node2->GetData();
+ wxPoint pt = line->GetAbsolutePosition();
+ wxRichTextRange range = line->GetAbsoluteRange();
+
+ if (pt.y > lastY)
+ {
+ node2 = wxRichTextLineList::compatibility_iterator();
+ node = wxRichTextObjectList::compatibility_iterator();
+ }
+ else if (range.GetStart() > GetPosition() && pt.y >= firstVisiblePt.y)
+ {
+ optimizationLineCharPositions.Add(range.GetStart());
+ optimizationLineYPositions.Add(pt.y);
+ }
+
+ if (node2)
+ node2 = node2->GetNext();
+ }
+
+ if (node)
+ node = node->GetNext();
+ }
+ }
+#endif
+}
+
+bool wxRichTextAction::Do()
+{
+ m_buffer->Modify(true);
+
+ wxRichTextParagraphLayoutBox* container = GetContainer();
+ wxASSERT(container != NULL);
+ if (!container)
+ return false;
+
+ switch (m_cmdId)
+ {
+ case wxRICHTEXT_INSERT:
+ {
+ // Store a list of line start character and y positions so we can figure out which area
+ // we need to refresh
+ wxArrayInt optimizationLineCharPositions;
+ wxArrayInt optimizationLineYPositions;
+
+#if wxRICHTEXT_USE_OPTIMIZED_DRAWING
+ CalculateRefreshOptimizations(optimizationLineCharPositions, optimizationLineYPositions);
+#endif
+
+ container->InsertFragment(GetRange().GetStart(), m_newParagraphs);
+ container->UpdateRanges();
+
+ // InvalidateHierarchy goes up the hierarchy as well as down, otherwise with a nested object,
+ // Layout() would stop prematurely at the top level.
+ container->InvalidateHierarchy(wxRichTextRange(wxMax(0, GetRange().GetStart()-1), GetRange().GetEnd()));
+
+ long newCaretPosition = GetPosition() + m_newParagraphs.GetOwnRange().GetLength();
+
+ // Character position to caret position
+ newCaretPosition --;
+
+ // Don't take into account the last newline
+ if (m_newParagraphs.GetPartialParagraph())
+ newCaretPosition --;
+ else
+ if (m_newParagraphs.GetChildren().GetCount() > 1)
+ {
+ wxRichTextObject* p = (wxRichTextObject*) m_newParagraphs.GetChildren().GetLast()->GetData();
+ if (p->GetRange().GetLength() == 1)
+ newCaretPosition --;
+ }
+
+ newCaretPosition = wxMin(newCaretPosition, (container->GetOwnRange().GetEnd()-1));
+
+ UpdateAppearance(newCaretPosition, true /* send update event */, & optimizationLineCharPositions, & optimizationLineYPositions, true /* do */);
+
+ wxRichTextEvent cmdEvent(
+ wxEVT_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()));