1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/richtext/richtextctrl.cpp
3 // Purpose: A rich edit control
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // For compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
21 #include "wx/richtext/richtextctrl.h"
22 #include "wx/richtext/richtextstyles.h"
26 #include "wx/settings.h"
30 #include "wx/textfile.h"
32 #include "wx/filename.h"
33 #include "wx/dcbuffer.h"
34 #include "wx/arrimpl.cpp"
35 #include "wx/fontenum.h"
38 #if defined (__WXGTK__) || defined(__WXX11__) || defined(__WXMOTIF__)
39 #define wxHAVE_PRIMARY_SELECTION 1
41 #define wxHAVE_PRIMARY_SELECTION 0
44 #if wxUSE_CLIPBOARD && wxHAVE_PRIMARY_SELECTION
45 #include "wx/clipbrd.h"
48 // DLL options compatibility check:
50 WX_CHECK_BUILD_OPTIONS("wxRichTextCtrl")
52 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_LEFT_CLICK
, wxRichTextEvent
);
53 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK
, wxRichTextEvent
);
54 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_RIGHT_CLICK
, wxRichTextEvent
);
55 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_LEFT_DCLICK
, wxRichTextEvent
);
56 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_RETURN
, wxRichTextEvent
);
57 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_CHARACTER
, wxRichTextEvent
);
58 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_DELETE
, wxRichTextEvent
);
60 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING
, wxRichTextEvent
);
61 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED
, wxRichTextEvent
);
62 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGING
, wxRichTextEvent
);
63 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGED
, wxRichTextEvent
);
65 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED
, wxRichTextEvent
);
66 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED
, wxRichTextEvent
);
67 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED
, wxRichTextEvent
);
68 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_SELECTION_CHANGED
, wxRichTextEvent
);
69 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_BUFFER_RESET
, wxRichTextEvent
);
70 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_FOCUS_OBJECT_CHANGED
, wxRichTextEvent
);
72 #if wxRICHTEXT_USE_OWN_CARET
77 * This implements a non-flashing cursor in case there
78 * are platform-specific problems with the generic caret.
79 * wxRICHTEXT_USE_OWN_CARET is set in richtextbuffer.h.
82 class wxRichTextCaret
;
83 class wxRichTextCaretTimer
: public wxTimer
86 wxRichTextCaretTimer(wxRichTextCaret
* caret
)
90 virtual void Notify();
91 wxRichTextCaret
* m_caret
;
94 class wxRichTextCaret
: public wxCaret
99 // default - use Create()
100 wxRichTextCaret(): m_timer(this) { Init(); }
101 // creates a block caret associated with the given window
102 wxRichTextCaret(wxRichTextCtrl
*window
, int width
, int height
)
103 : wxCaret(window
, width
, height
), m_timer(this) { Init(); m_richTextCtrl
= window
; }
104 wxRichTextCaret(wxRichTextCtrl
*window
, const wxSize
& size
)
105 : wxCaret(window
, size
), m_timer(this) { Init(); m_richTextCtrl
= window
; }
107 virtual ~wxRichTextCaret();
112 // called by wxWindow (not using the event tables)
113 virtual void OnSetFocus();
114 virtual void OnKillFocus();
116 // draw the caret on the given DC
117 void DoDraw(wxDC
*dc
);
119 // get the visible count
120 int GetVisibleCount() const { return m_countVisible
; }
122 // delay repositioning
123 bool GetNeedsUpdate() const { return m_needsUpdate
; }
124 void SetNeedsUpdate(bool needsUpdate
= true ) { m_needsUpdate
= needsUpdate
; }
129 virtual void DoShow();
130 virtual void DoHide();
131 virtual void DoMove();
132 virtual void DoSize();
142 bool m_hasFocus
; // true => our window has focus
143 bool m_needsUpdate
; // must be repositioned
145 wxRichTextCaretTimer m_timer
;
146 wxRichTextCtrl
* m_richTextCtrl
;
150 IMPLEMENT_DYNAMIC_CLASS( wxRichTextCtrl
, wxControl
)
152 IMPLEMENT_DYNAMIC_CLASS( wxRichTextEvent
, wxNotifyEvent
)
154 BEGIN_EVENT_TABLE( wxRichTextCtrl
, wxControl
)
155 EVT_PAINT(wxRichTextCtrl::OnPaint
)
156 EVT_ERASE_BACKGROUND(wxRichTextCtrl::OnEraseBackground
)
157 EVT_IDLE(wxRichTextCtrl::OnIdle
)
158 EVT_SCROLLWIN(wxRichTextCtrl::OnScroll
)
159 EVT_LEFT_DOWN(wxRichTextCtrl::OnLeftClick
)
160 EVT_MOTION(wxRichTextCtrl::OnMoveMouse
)
161 EVT_LEFT_UP(wxRichTextCtrl::OnLeftUp
)
162 EVT_RIGHT_DOWN(wxRichTextCtrl::OnRightClick
)
163 EVT_MIDDLE_DOWN(wxRichTextCtrl::OnMiddleClick
)
164 EVT_LEFT_DCLICK(wxRichTextCtrl::OnLeftDClick
)
165 EVT_CHAR(wxRichTextCtrl::OnChar
)
166 EVT_KEY_DOWN(wxRichTextCtrl::OnChar
)
167 EVT_SIZE(wxRichTextCtrl::OnSize
)
168 EVT_SET_FOCUS(wxRichTextCtrl::OnSetFocus
)
169 EVT_KILL_FOCUS(wxRichTextCtrl::OnKillFocus
)
170 EVT_MOUSE_CAPTURE_LOST(wxRichTextCtrl::OnCaptureLost
)
171 EVT_CONTEXT_MENU(wxRichTextCtrl::OnContextMenu
)
172 EVT_SYS_COLOUR_CHANGED(wxRichTextCtrl::OnSysColourChanged
)
174 EVT_MENU(wxID_UNDO
, wxRichTextCtrl::OnUndo
)
175 EVT_UPDATE_UI(wxID_UNDO
, wxRichTextCtrl::OnUpdateUndo
)
177 EVT_MENU(wxID_REDO
, wxRichTextCtrl::OnRedo
)
178 EVT_UPDATE_UI(wxID_REDO
, wxRichTextCtrl::OnUpdateRedo
)
180 EVT_MENU(wxID_COPY
, wxRichTextCtrl::OnCopy
)
181 EVT_UPDATE_UI(wxID_COPY
, wxRichTextCtrl::OnUpdateCopy
)
183 EVT_MENU(wxID_PASTE
, wxRichTextCtrl::OnPaste
)
184 EVT_UPDATE_UI(wxID_PASTE
, wxRichTextCtrl::OnUpdatePaste
)
186 EVT_MENU(wxID_CUT
, wxRichTextCtrl::OnCut
)
187 EVT_UPDATE_UI(wxID_CUT
, wxRichTextCtrl::OnUpdateCut
)
189 EVT_MENU(wxID_CLEAR
, wxRichTextCtrl::OnClear
)
190 EVT_UPDATE_UI(wxID_CLEAR
, wxRichTextCtrl::OnUpdateClear
)
192 EVT_MENU(wxID_SELECTALL
, wxRichTextCtrl::OnSelectAll
)
193 EVT_UPDATE_UI(wxID_SELECTALL
, wxRichTextCtrl::OnUpdateSelectAll
)
195 EVT_MENU(wxID_RICHTEXT_PROPERTIES1
, wxRichTextCtrl::OnProperties
)
196 EVT_UPDATE_UI(wxID_RICHTEXT_PROPERTIES1
, wxRichTextCtrl::OnUpdateProperties
)
198 EVT_MENU(wxID_RICHTEXT_PROPERTIES2
, wxRichTextCtrl::OnProperties
)
199 EVT_UPDATE_UI(wxID_RICHTEXT_PROPERTIES2
, wxRichTextCtrl::OnUpdateProperties
)
201 EVT_MENU(wxID_RICHTEXT_PROPERTIES3
, wxRichTextCtrl::OnProperties
)
202 EVT_UPDATE_UI(wxID_RICHTEXT_PROPERTIES3
, wxRichTextCtrl::OnUpdateProperties
)
210 wxArrayString
wxRichTextCtrl::sm_availableFontNames
;
212 wxRichTextCtrl::wxRichTextCtrl()
213 : wxScrollHelper(this)
218 wxRichTextCtrl::wxRichTextCtrl(wxWindow
* parent
,
220 const wxString
& value
,
224 const wxValidator
& validator
,
225 const wxString
& name
)
226 : wxScrollHelper(this)
229 Create(parent
, id
, value
, pos
, size
, style
, validator
, name
);
231 SetDropTarget(new wxRichTextDropTarget(this));
235 bool wxRichTextCtrl::Create( wxWindow
* parent
, wxWindowID id
, const wxString
& value
, const wxPoint
& pos
, const wxSize
& size
, long style
,
236 const wxValidator
& validator
, const wxString
& name
)
240 if (!wxControl::Create(parent
, id
, pos
, size
,
241 style
|wxFULL_REPAINT_ON_RESIZE
,
245 if (!GetFont().IsOk())
247 SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT
));
250 // No physical scrolling, so we can preserve margins
251 EnableScrolling(false, false);
253 if (style
& wxTE_READONLY
)
256 // The base attributes must all have default values
257 wxRichTextAttr attributes
;
258 attributes
.SetFont(GetFont());
259 attributes
.SetTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT
));
260 attributes
.SetAlignment(wxTEXT_ALIGNMENT_LEFT
);
261 attributes
.SetLineSpacing(10);
262 attributes
.SetParagraphSpacingAfter(10);
263 attributes
.SetParagraphSpacingBefore(0);
265 SetBasicStyle(attributes
);
268 SetMargins(margin
, margin
);
270 // The default attributes will be merged with base attributes, so
271 // can be empty to begin with
272 wxRichTextAttr defaultAttributes
;
273 SetDefaultStyle(defaultAttributes
);
275 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
));
276 SetBackgroundStyle(wxBG_STYLE_CUSTOM
);
279 GetBuffer().SetRichTextCtrl(this);
281 #if wxRICHTEXT_USE_OWN_CARET
282 SetCaret(new wxRichTextCaret(this, wxRICHTEXT_DEFAULT_CARET_WIDTH
, 16));
284 SetCaret(new wxCaret(this, wxRICHTEXT_DEFAULT_CARET_WIDTH
, 16));
287 // Tell the sizers to use the given or best size
288 SetInitialSize(size
);
290 #if wxRICHTEXT_BUFFERED_PAINTING
292 RecreateBuffer(size
);
295 m_textCursor
= wxCursor(wxCURSOR_IBEAM
);
296 m_urlCursor
= wxCursor(wxCURSOR_HAND
);
298 SetCursor(m_textCursor
);
300 if (!value
.IsEmpty())
303 GetBuffer().AddEventHandler(this);
306 wxAcceleratorEntry entries
[6];
308 entries
[0].Set(wxACCEL_CTRL
, (int) 'C', wxID_COPY
);
309 entries
[1].Set(wxACCEL_CTRL
, (int) 'X', wxID_CUT
);
310 entries
[2].Set(wxACCEL_CTRL
, (int) 'V', wxID_PASTE
);
311 entries
[3].Set(wxACCEL_CTRL
, (int) 'A', wxID_SELECTALL
);
312 entries
[4].Set(wxACCEL_CTRL
, (int) 'Z', wxID_UNDO
);
313 entries
[5].Set(wxACCEL_CTRL
, (int) 'Y', wxID_REDO
);
315 wxAcceleratorTable
accel(6, entries
);
316 SetAcceleratorTable(accel
);
318 m_contextMenu
= new wxMenu
;
319 m_contextMenu
->Append(wxID_UNDO
, _("&Undo"));
320 m_contextMenu
->Append(wxID_REDO
, _("&Redo"));
321 m_contextMenu
->AppendSeparator();
322 m_contextMenu
->Append(wxID_CUT
, _("Cu&t"));
323 m_contextMenu
->Append(wxID_COPY
, _("&Copy"));
324 m_contextMenu
->Append(wxID_PASTE
, _("&Paste"));
325 m_contextMenu
->Append(wxID_CLEAR
, _("&Delete"));
326 m_contextMenu
->AppendSeparator();
327 m_contextMenu
->Append(wxID_SELECTALL
, _("Select &All"));
328 m_contextMenu
->AppendSeparator();
329 m_contextMenu
->Append(wxID_RICHTEXT_PROPERTIES1
, _("&Properties"));
334 wxRichTextCtrl::~wxRichTextCtrl()
336 SetFocusObject(& GetBuffer(), false);
337 GetBuffer().RemoveEventHandler(this);
339 delete m_contextMenu
;
342 /// Member initialisation
343 void wxRichTextCtrl::Init()
345 m_contextMenu
= NULL
;
347 m_caretPosition
= -1;
348 m_selectionAnchor
= -2;
349 m_selectionAnchorObject
= NULL
;
350 m_selectionState
= wxRichTextCtrlSelectionState_Normal
;
352 m_caretAtLineStart
= false;
355 m_fullLayoutRequired
= false;
356 m_fullLayoutTime
= 0;
357 m_fullLayoutSavedPosition
= 0;
358 m_delayedLayoutThreshold
= wxRICHTEXT_DEFAULT_DELAYED_LAYOUT_THRESHOLD
;
359 m_caretPositionForDefaultStyle
= -2;
360 m_focusObject
= & m_buffer
;
363 void wxRichTextCtrl::DoThaw()
365 if (GetBuffer().IsDirty())
374 void wxRichTextCtrl::Clear()
376 if (GetFocusObject() == & GetBuffer())
378 m_buffer
.ResetAndClearCommands();
379 m_buffer
.Invalidate(wxRICHTEXT_ALL
);
383 GetFocusObject()->Reset();
386 m_caretPosition
= -1;
387 m_caretPositionForDefaultStyle
= -2;
388 m_caretAtLineStart
= false;
390 m_selectionState
= wxRichTextCtrlSelectionState_Normal
;
400 wxTextCtrl::SendTextUpdatedEvent(this);
404 void wxRichTextCtrl::OnPaint(wxPaintEvent
& WXUNUSED(event
))
406 #if !wxRICHTEXT_USE_OWN_CARET
407 if (GetCaret() && !IsFrozen())
412 #if wxRICHTEXT_BUFFERED_PAINTING
413 wxBufferedPaintDC
dc(this, m_bufferBitmap
);
423 dc
.SetFont(GetFont());
425 // Paint the background
428 // wxRect drawingArea(GetLogicalPoint(wxPoint(0, 0)), GetClientSize());
430 wxRect
drawingArea(GetUpdateRegion().GetBox());
431 drawingArea
.SetPosition(GetLogicalPoint(drawingArea
.GetPosition()));
433 wxRect
availableSpace(GetClientSize());
434 if (GetBuffer().IsDirty())
436 GetBuffer().Layout(dc
, availableSpace
, wxRICHTEXT_FIXED_WIDTH
|wxRICHTEXT_VARIABLE_HEIGHT
);
437 GetBuffer().Invalidate(wxRICHTEXT_NONE
);
441 wxRect
clipRect(availableSpace
);
442 clipRect
.x
+= GetBuffer().GetLeftMargin();
443 clipRect
.y
+= GetBuffer().GetTopMargin();
444 clipRect
.width
-= (GetBuffer().GetLeftMargin() + GetBuffer().GetRightMargin());
445 clipRect
.height
-= (GetBuffer().GetTopMargin() + GetBuffer().GetBottomMargin());
446 clipRect
.SetPosition(GetLogicalPoint(clipRect
.GetPosition()));
447 dc
.SetClippingRegion(clipRect
);
450 if ((GetExtraStyle() & wxRICHTEXT_EX_NO_GUIDELINES
) == 0)
451 flags
|= wxRICHTEXT_DRAW_GUIDELINES
;
453 GetBuffer().Draw(dc
, GetBuffer().GetOwnRange(), GetSelection(), drawingArea
, 0 /* descent */, flags
);
455 dc
.DestroyClippingRegion();
457 // Other user defined painting after everything else (i.e. all text) is painted
458 PaintAboveContent(dc
);
460 #if wxRICHTEXT_USE_OWN_CARET
461 if (GetCaret()->IsVisible())
463 ((wxRichTextCaret
*) GetCaret())->DoDraw(& dc
);
468 #if !wxRICHTEXT_USE_OWN_CARET
473 #if !defined(__WXMAC__)
474 // Causes caret dropouts on Mac
480 // Empty implementation, to prevent flicker
481 void wxRichTextCtrl::OnEraseBackground(wxEraseEvent
& WXUNUSED(event
))
485 void wxRichTextCtrl::OnSetFocus(wxFocusEvent
& WXUNUSED(event
))
489 #if !wxRICHTEXT_USE_OWN_CARET
495 #if defined(__WXGTK__) && !wxRICHTEXT_USE_OWN_CARET
496 // Work around dropouts when control is focused
504 void wxRichTextCtrl::OnKillFocus(wxFocusEvent
& WXUNUSED(event
))
509 #if defined(__WXGTK__) && !wxRICHTEXT_USE_OWN_CARET
510 // Work around dropouts when control is focused
518 void wxRichTextCtrl::OnCaptureLost(wxMouseCaptureLostEvent
& WXUNUSED(event
))
523 // Set up the caret for the given position and container, after a mouse click
524 bool wxRichTextCtrl::SetCaretPositionAfterClick(wxRichTextParagraphLayoutBox
* container
, long position
, int hitTestFlags
, bool extendSelection
)
526 bool caretAtLineStart
= false;
528 if (hitTestFlags
& wxRICHTEXT_HITTEST_BEFORE
)
530 // If we're at the start of a line (but not first in para)
531 // then we should keep the caret showing at the start of the line
532 // by showing the m_caretAtLineStart flag.
533 wxRichTextParagraph
* para
= container
->GetParagraphAtPosition(position
);
534 wxRichTextLine
* line
= container
->GetLineAtPosition(position
);
536 if (line
&& para
&& line
->GetAbsoluteRange().GetStart() == position
&& para
->GetRange().GetStart() != position
)
537 caretAtLineStart
= true;
541 if (extendSelection
&& (m_caretPosition
!= position
))
542 ExtendSelection(m_caretPosition
, position
, wxRICHTEXT_SHIFT_DOWN
);
544 MoveCaret(position
, caretAtLineStart
);
545 SetDefaultStyleToCursorStyle();
551 void wxRichTextCtrl::OnLeftClick(wxMouseEvent
& event
)
557 dc
.SetFont(GetFont());
559 // TODO: detect change of focus object
561 wxRichTextObject
* hitObj
= NULL
;
562 wxRichTextObject
* contextObj
= NULL
;
563 int hit
= GetBuffer().HitTest(dc
, event
.GetLogicalPosition(dc
), position
, & hitObj
, & contextObj
);
565 #if wxUSE_DRAG_AND_DROP
566 // If there's no selection, or we're not inside it, this isn't an attempt to initiate Drag'n'Drop
567 if (IsEditable() && HasSelection() && GetSelectionRange().ToInternal().Contains(position
))
569 // This might be an attempt at initiating Drag'n'Drop. So set the time & flags
571 m_dragStartPoint
= event
.GetPosition(); // No need to worry about logical positions etc, we only care about the distance from the original pt
574 m_dragStartTime
= wxDateTime::UNow();
575 #endif // wxUSE_DATETIME
577 // Preserve behaviour of clicking on an object within the selection
578 if (hit
!= wxRICHTEXT_HITTEST_NONE
&& hitObj
)
581 return; // Don't skip the event, else the selection will be lost
583 #endif // wxUSE_DRAG_AND_DROP
585 if (hit
!= wxRICHTEXT_HITTEST_NONE
&& hitObj
)
587 wxRichTextParagraphLayoutBox
* oldFocusObject
= GetFocusObject();
588 wxRichTextParagraphLayoutBox
* container
= wxDynamicCast(contextObj
, wxRichTextParagraphLayoutBox
);
589 if (container
&& container
!= GetFocusObject() && container
->AcceptsFocus())
591 SetFocusObject(container
, false /* don't set caret position yet */);
597 long oldCaretPos
= m_caretPosition
;
599 SetCaretPositionAfterClick(container
, position
, hit
);
601 // For now, don't handle shift-click when we're selecting multiple objects.
602 if (event
.ShiftDown() && GetFocusObject() == oldFocusObject
&& m_selectionState
== wxRichTextCtrlSelectionState_Normal
)
603 ExtendSelection(oldCaretPos
, m_caretPosition
, wxRICHTEXT_SHIFT_DOWN
);
612 void wxRichTextCtrl::OnLeftUp(wxMouseEvent
& event
)
617 if (GetCapture() == this)
620 // See if we clicked on a URL
623 dc
.SetFont(GetFont());
626 wxPoint logicalPt
= event
.GetLogicalPosition(dc
);
627 wxRichTextObject
* hitObj
= NULL
;
628 wxRichTextObject
* contextObj
= NULL
;
629 // Only get objects at this level, not nested, because otherwise we couldn't swipe text at a single level.
630 int hit
= GetFocusObject()->HitTest(dc
, logicalPt
, position
, & hitObj
, & contextObj
, wxRICHTEXT_HITTEST_NO_NESTED_OBJECTS
);
632 #if wxUSE_DRAG_AND_DROP
635 // Preserve the behaviour that would have happened without drag-and-drop detection, in OnLeftClick
636 m_preDrag
= false; // Tell DnD not to happen now: we are processing Left Up ourselves.
638 // Do the actions that would have been done in OnLeftClick if we hadn't tried to drag
640 wxRichTextObject
* hitObj
= NULL
;
641 wxRichTextObject
* contextObj
= NULL
;
642 int hit
= GetBuffer().HitTest(dc
, event
.GetLogicalPosition(dc
), position
, & hitObj
, & contextObj
);
643 wxRichTextParagraphLayoutBox
* oldFocusObject
= GetFocusObject();
644 wxRichTextParagraphLayoutBox
* container
= wxDynamicCast(contextObj
, wxRichTextParagraphLayoutBox
);
645 if (container
&& container
!= GetFocusObject() && container
->AcceptsFocus())
647 SetFocusObject(container
, false /* don't set caret position yet */);
650 long oldCaretPos
= m_caretPosition
;
652 SetCaretPositionAfterClick(container
, position
, hit
);
654 // For now, don't handle shift-click when we're selecting multiple objects.
655 if (event
.ShiftDown() && GetFocusObject() == oldFocusObject
&& m_selectionState
== wxRichTextCtrlSelectionState_Normal
)
656 ExtendSelection(oldCaretPos
, m_caretPosition
, wxRICHTEXT_SHIFT_DOWN
);
662 if ((hit
!= wxRICHTEXT_HITTEST_NONE
) && !(hit
& wxRICHTEXT_HITTEST_OUTSIDE
))
664 wxRichTextEvent
cmdEvent(
665 wxEVT_COMMAND_RICHTEXT_LEFT_CLICK
,
667 cmdEvent
.SetEventObject(this);
668 cmdEvent
.SetPosition(position
);
670 cmdEvent
.SetContainer(hitObj
->GetContainer());
672 if (!GetEventHandler()->ProcessEvent(cmdEvent
))
675 if (GetStyle(position
, attr
))
677 if (attr
.HasFlag(wxTEXT_ATTR_URL
))
679 wxString urlTarget
= attr
.GetURL();
680 if (!urlTarget
.IsEmpty())
682 wxMouseEvent
mouseEvent(event
);
684 long startPos
= 0, endPos
= 0;
685 wxRichTextObject
* obj
= GetFocusObject()->GetLeafObjectAtPosition(position
);
688 startPos
= obj
->GetRange().GetStart();
689 endPos
= obj
->GetRange().GetEnd();
692 wxTextUrlEvent
urlEvent(GetId(), mouseEvent
, startPos
, endPos
);
693 InitCommandEvent(urlEvent
);
695 urlEvent
.SetString(urlTarget
);
697 GetEventHandler()->ProcessEvent(urlEvent
);
705 #if wxUSE_DRAG_AND_DROP
707 #endif // wxUSE_DRAG_AND_DROP
709 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ && wxHAVE_PRIMARY_SELECTION
710 if (HasSelection() && GetFocusObject() && GetFocusObject()->GetBuffer())
712 // Put the selection in PRIMARY, if it exists
713 wxTheClipboard
->UsePrimarySelection(true);
715 wxRichTextRange range
= GetInternalSelectionRange();
716 GetFocusObject()->GetBuffer()->CopyToClipboard(range
);
718 wxTheClipboard
->UsePrimarySelection(false);
724 void wxRichTextCtrl::OnMoveMouse(wxMouseEvent
& event
)
726 #if wxUSE_DRAG_AND_DROP
727 // See if we're starting Drag'n'Drop
730 int x
= m_dragStartPoint
.x
- event
.GetPosition().x
;
731 int y
= m_dragStartPoint
.y
- event
.GetPosition().y
;
732 size_t distance
= abs(x
) + abs(y
);
734 wxTimeSpan diff
= wxDateTime::UNow() - m_dragStartTime
;
738 && (diff
.GetMilliseconds() > 100)
745 wxRichTextRange range
= GetInternalSelectionRange();
746 if (range
== wxRICHTEXT_NONE
)
748 // Don't try to drag an empty range
753 // Cache the current situation, to be restored if Drag'n'Drop is cancelled
754 long oldPos
= GetCaretPosition();
755 wxRichTextParagraphLayoutBox
* oldFocus
= GetFocusObject();
757 wxDataObjectComposite
* compositeObject
= new wxDataObjectComposite();
758 wxString text
= GetFocusObject()->GetTextForRange(range
);
760 text
= wxTextFile::Translate(text
, wxTextFileType_Dos
);
762 compositeObject
->Add(new wxTextDataObject(text
), false /* not preferred */);
764 wxRichTextBuffer
* richTextBuf
= new wxRichTextBuffer
;
765 GetFocusObject()->CopyFragment(range
, *richTextBuf
);
766 compositeObject
->Add(new wxRichTextBufferDataObject(richTextBuf
), true /* preferred */);
768 wxRichTextDropSource
source(*compositeObject
, this);
769 // Use wxDrag_DefaultMove, not because it's the likelier choice but because pressing Ctrl for Copy obeys the principle of least surprise
770 // The alternative, wxDrag_DefaultCopy, requires the user to know that Move needs the Shift key pressed
771 BeginBatchUndo(_("Drag"));
772 switch (source
.DoDragDrop(wxDrag_AllowMove
| wxDrag_DefaultMove
))
775 case wxDragCopy
: break;
778 wxLogError(wxT("An error occurred during drag and drop operation"));
781 Refresh(); // This is needed in wxMSW, otherwise resetting the position doesn't 'take'
782 SetCaretPosition(oldPos
);
783 SetFocusObject(oldFocus
, false);
792 #endif // wxUSE_DRAG_AND_DROP
796 dc
.SetFont(GetFont());
799 wxPoint logicalPt
= event
.GetLogicalPosition(dc
);
800 wxRichTextObject
* hitObj
= NULL
;
801 wxRichTextObject
* contextObj
= NULL
;
805 // If we're dragging, let's only consider positions at this level; otherwise
806 // selecting a range is not going to work.
807 wxRichTextParagraphLayoutBox
* container
= & GetBuffer();
810 flags
= wxRICHTEXT_HITTEST_NO_NESTED_OBJECTS
;
811 container
= GetFocusObject();
813 int hit
= container
->HitTest(dc
, logicalPt
, position
, & hitObj
, & contextObj
, flags
);
815 // See if we need to change the cursor
818 if (hit
!= wxRICHTEXT_HITTEST_NONE
&& !(hit
& wxRICHTEXT_HITTEST_OUTSIDE
) && hitObj
)
820 wxRichTextParagraphLayoutBox
* actualContainer
= wxDynamicCast(contextObj
, wxRichTextParagraphLayoutBox
);
822 if (actualContainer
&& GetStyle(position
, attr
, actualContainer
))
824 if (attr
.HasFlag(wxTEXT_ATTR_URL
))
826 SetCursor(m_urlCursor
);
828 else if (!attr
.HasFlag(wxTEXT_ATTR_URL
))
830 SetCursor(m_textCursor
);
835 SetCursor(m_textCursor
);
838 if (!event
.Dragging())
845 #if wxUSE_DRAG_AND_DROP
850 wxRichTextParagraphLayoutBox
* commonAncestor
= NULL
;
851 wxRichTextParagraphLayoutBox
* otherContainer
= NULL
;
852 wxRichTextParagraphLayoutBox
* firstContainer
= NULL
;
854 // Check for dragging across multiple containers
856 wxRichTextObject
* hitObj2
= NULL
, *contextObj2
= NULL
;
857 int hit2
= GetBuffer().HitTest(dc
, logicalPt
, position2
, & hitObj2
, & contextObj2
, 0);
858 if (hit2
!= wxRICHTEXT_HITTEST_NONE
&& !(hit2
& wxRICHTEXT_HITTEST_OUTSIDE
) && hitObj2
&& hitObj
!= hitObj2
)
860 // See if we can find a common ancestor
861 if (m_selectionState
== wxRichTextCtrlSelectionState_Normal
)
863 firstContainer
= GetFocusObject();
864 commonAncestor
= wxDynamicCast(firstContainer
->GetParent(), wxRichTextParagraphLayoutBox
);
868 firstContainer
= wxDynamicCast(m_selectionAnchorObject
, wxRichTextParagraphLayoutBox
);
869 //commonAncestor = GetFocusObject(); // when the selection state is not normal, the focus object (e.g. table)
870 // is the common ancestor.
871 commonAncestor
= wxDynamicCast(firstContainer
->GetParent(), wxRichTextParagraphLayoutBox
);
874 if (commonAncestor
&& commonAncestor
->HandlesChildSelections())
876 wxRichTextObject
* p
= hitObj2
;
879 if (p
->GetParent() == commonAncestor
)
881 otherContainer
= wxDynamicCast(p
, wxRichTextParagraphLayoutBox
);
888 if (commonAncestor
&& firstContainer
&& otherContainer
)
890 // We have now got a second container that shares a parent with the current or anchor object.
891 if (m_selectionState
== wxRichTextCtrlSelectionState_Normal
)
893 // Don't go into common-ancestor selection mode if we still have the same
895 if (otherContainer
!= firstContainer
)
897 m_selectionState
= wxRichTextCtrlSelectionState_CommonAncestor
;
898 m_selectionAnchorObject
= firstContainer
;
899 m_selectionAnchor
= firstContainer
->GetRange().GetStart();
901 // The common ancestor, such as a table, returns the cell selection
902 // between the anchor and current position.
903 m_selection
= commonAncestor
->GetSelection(m_selectionAnchor
, otherContainer
->GetRange().GetStart());
908 m_selection
= commonAncestor
->GetSelection(m_selectionAnchor
, otherContainer
->GetRange().GetStart());
913 if (otherContainer
->AcceptsFocus())
914 SetFocusObject(otherContainer
, false /* don't set caret and clear selection */);
915 MoveCaret(-1, false);
916 SetDefaultStyleToCursorStyle();
921 if (hitObj
&& m_dragging
&& hit
!= wxRICHTEXT_HITTEST_NONE
&& m_selectionState
== wxRichTextCtrlSelectionState_Normal
922 #if wxUSE_DRAG_AND_DROP
927 // TODO: test closeness
928 SetCaretPositionAfterClick(container
, position
, hit
, true /* extend selection */);
933 void wxRichTextCtrl::OnRightClick(wxMouseEvent
& event
)
939 dc
.SetFont(GetFont());
942 wxPoint logicalPt
= event
.GetLogicalPosition(dc
);
943 wxRichTextObject
* hitObj
= NULL
;
944 wxRichTextObject
* contextObj
= NULL
;
945 int hit
= GetFocusObject()->HitTest(dc
, logicalPt
, position
, & hitObj
, & contextObj
);
947 if (hitObj
&& hitObj
->GetContainer() != GetFocusObject())
949 wxRichTextParagraphLayoutBox
* actualContainer
= wxDynamicCast(contextObj
, wxRichTextParagraphLayoutBox
);
950 if (actualContainer
&& actualContainer
->AcceptsFocus())
952 SetFocusObject(actualContainer
, false /* don't set caret position yet */);
953 SetCaretPositionAfterClick(actualContainer
, position
, hit
);
957 wxRichTextEvent
cmdEvent(
958 wxEVT_COMMAND_RICHTEXT_RIGHT_CLICK
,
960 cmdEvent
.SetEventObject(this);
961 cmdEvent
.SetPosition(position
);
963 cmdEvent
.SetContainer(hitObj
->GetContainer());
965 if (!GetEventHandler()->ProcessEvent(cmdEvent
))
969 /// Left-double-click
970 void wxRichTextCtrl::OnLeftDClick(wxMouseEvent
& WXUNUSED(event
))
972 wxRichTextEvent
cmdEvent(
973 wxEVT_COMMAND_RICHTEXT_LEFT_DCLICK
,
975 cmdEvent
.SetEventObject(this);
976 cmdEvent
.SetPosition(m_caretPosition
+1);
977 cmdEvent
.SetContainer(GetFocusObject());
979 if (!GetEventHandler()->ProcessEvent(cmdEvent
))
981 SelectWord(GetCaretPosition()+1);
986 void wxRichTextCtrl::OnMiddleClick(wxMouseEvent
& event
)
988 wxRichTextEvent
cmdEvent(
989 wxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK
,
991 cmdEvent
.SetEventObject(this);
992 cmdEvent
.SetPosition(m_caretPosition
+1);
993 cmdEvent
.SetContainer(GetFocusObject());
995 if (!GetEventHandler()->ProcessEvent(cmdEvent
))
998 #if wxUSE_CLIPBOARD && wxUSE_DATAOBJ && wxHAVE_PRIMARY_SELECTION
999 // Paste any PRIMARY selection, if it exists
1000 wxTheClipboard
->UsePrimarySelection(true);
1002 wxTheClipboard
->UsePrimarySelection(false);
1007 void wxRichTextCtrl::OnChar(wxKeyEvent
& event
)
1010 if (event
.CmdDown())
1011 flags
|= wxRICHTEXT_CTRL_DOWN
;
1012 if (event
.ShiftDown())
1013 flags
|= wxRICHTEXT_SHIFT_DOWN
;
1014 if (event
.AltDown())
1015 flags
|= wxRICHTEXT_ALT_DOWN
;
1017 if (event
.GetEventType() == wxEVT_KEY_DOWN
)
1019 if (event
.IsKeyInCategory(WXK_CATEGORY_NAVIGATION
))
1021 KeyboardNavigate(event
.GetKeyCode(), flags
);
1025 long keycode
= event
.GetKeyCode();
1085 case WXK_NUMPAD_HOME
:
1086 case WXK_NUMPAD_LEFT
:
1088 case WXK_NUMPAD_RIGHT
:
1089 case WXK_NUMPAD_DOWN
:
1090 case WXK_NUMPAD_PAGEUP
:
1091 case WXK_NUMPAD_PAGEDOWN
:
1092 case WXK_NUMPAD_END
:
1093 case WXK_NUMPAD_BEGIN
:
1094 case WXK_NUMPAD_INSERT
:
1095 case WXK_WINDOWS_LEFT
:
1104 // Must process this before translation, otherwise it's translated into a WXK_DELETE event.
1105 if (event
.CmdDown() && event
.GetKeyCode() == WXK_BACK
)
1107 BeginBatchUndo(_("Delete Text"));
1109 long newPos
= m_caretPosition
;
1111 bool processed
= DeleteSelectedContent(& newPos
);
1113 // Submit range in character positions, which are greater than caret positions,
1114 // so subtract 1 for deleted character and add 1 for conversion to character position.
1117 if (event
.CmdDown())
1119 long pos
= wxRichTextCtrl::FindNextWordPosition(-1);
1122 GetFocusObject()->DeleteRangeWithUndo(wxRichTextRange(pos
+1, newPos
), this, & GetBuffer());
1128 GetFocusObject()->DeleteRangeWithUndo(wxRichTextRange(newPos
, newPos
), this, & GetBuffer());
1133 if (GetLastPosition() == -1)
1135 GetFocusObject()->Reset();
1137 m_caretPosition
= -1;
1139 SetDefaultStyleToCursorStyle();
1142 ScrollIntoView(m_caretPosition
, WXK_LEFT
);
1144 wxRichTextEvent
cmdEvent(
1145 wxEVT_COMMAND_RICHTEXT_DELETE
,
1147 cmdEvent
.SetEventObject(this);
1148 cmdEvent
.SetFlags(flags
);
1149 cmdEvent
.SetPosition(m_caretPosition
+1);
1150 cmdEvent
.SetContainer(GetFocusObject());
1151 GetEventHandler()->ProcessEvent(cmdEvent
);
1161 // all the other keys modify the controls contents which shouldn't be
1162 // possible if we're read-only
1163 if ( !IsEditable() )
1169 if (event
.GetKeyCode() == WXK_RETURN
)
1171 BeginBatchUndo(_("Insert Text"));
1173 long newPos
= m_caretPosition
;
1175 DeleteSelectedContent(& newPos
);
1177 if (event
.ShiftDown())
1180 text
= wxRichTextLineBreakChar
;
1181 GetFocusObject()->InsertTextWithUndo(newPos
+1, text
, this, & GetBuffer());
1182 m_caretAtLineStart
= true;
1186 GetFocusObject()->InsertNewlineWithUndo(newPos
+1, this, & GetBuffer(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
|wxRICHTEXT_INSERT_INTERACTIVE
);
1189 SetDefaultStyleToCursorStyle();
1191 ScrollIntoView(m_caretPosition
, WXK_RIGHT
);
1193 wxRichTextEvent
cmdEvent(
1194 wxEVT_COMMAND_RICHTEXT_RETURN
,
1196 cmdEvent
.SetEventObject(this);
1197 cmdEvent
.SetFlags(flags
);
1198 cmdEvent
.SetPosition(newPos
+1);
1199 cmdEvent
.SetContainer(GetFocusObject());
1201 if (!GetEventHandler()->ProcessEvent(cmdEvent
))
1203 // Generate conventional event
1204 wxCommandEvent
textEvent(wxEVT_COMMAND_TEXT_ENTER
, GetId());
1205 InitCommandEvent(textEvent
);
1207 GetEventHandler()->ProcessEvent(textEvent
);
1211 else if (event
.GetKeyCode() == WXK_BACK
)
1213 BeginBatchUndo(_("Delete Text"));
1215 long newPos
= m_caretPosition
;
1217 bool processed
= DeleteSelectedContent(& newPos
);
1219 // Submit range in character positions, which are greater than caret positions,
1220 // so subtract 1 for deleted character and add 1 for conversion to character position.
1223 if (event
.CmdDown())
1225 long pos
= wxRichTextCtrl::FindNextWordPosition(-1);
1228 GetFocusObject()->DeleteRangeWithUndo(wxRichTextRange(pos
+1, newPos
), this, & GetBuffer());
1234 GetFocusObject()->DeleteRangeWithUndo(wxRichTextRange(newPos
, newPos
), this, & GetBuffer());
1239 if (GetLastPosition() == -1)
1241 GetFocusObject()->Reset();
1243 m_caretPosition
= -1;
1245 SetDefaultStyleToCursorStyle();
1248 ScrollIntoView(m_caretPosition
, WXK_LEFT
);
1250 wxRichTextEvent
cmdEvent(
1251 wxEVT_COMMAND_RICHTEXT_DELETE
,
1253 cmdEvent
.SetEventObject(this);
1254 cmdEvent
.SetFlags(flags
);
1255 cmdEvent
.SetPosition(m_caretPosition
+1);
1256 cmdEvent
.SetContainer(GetFocusObject());
1257 GetEventHandler()->ProcessEvent(cmdEvent
);
1261 else if (event
.GetKeyCode() == WXK_DELETE
)
1263 BeginBatchUndo(_("Delete Text"));
1265 long newPos
= m_caretPosition
;
1267 bool processed
= DeleteSelectedContent(& newPos
);
1269 // Submit range in character positions, which are greater than caret positions,
1270 if (newPos
< GetFocusObject()->GetOwnRange().GetEnd()+1)
1272 if (event
.CmdDown())
1274 long pos
= wxRichTextCtrl::FindNextWordPosition(1);
1275 if (pos
!= -1 && (pos
> newPos
))
1277 GetFocusObject()->DeleteRangeWithUndo(wxRichTextRange(newPos
+1, pos
), this, & GetBuffer());
1282 if (!processed
&& newPos
< (GetLastPosition()-1))
1283 GetFocusObject()->DeleteRangeWithUndo(wxRichTextRange(newPos
+1, newPos
+1), this, & GetBuffer());
1288 if (GetLastPosition() == -1)
1290 GetFocusObject()->Reset();
1292 m_caretPosition
= -1;
1294 SetDefaultStyleToCursorStyle();
1297 ScrollIntoView(m_caretPosition
, WXK_LEFT
);
1299 wxRichTextEvent
cmdEvent(
1300 wxEVT_COMMAND_RICHTEXT_DELETE
,
1302 cmdEvent
.SetEventObject(this);
1303 cmdEvent
.SetFlags(flags
);
1304 cmdEvent
.SetPosition(m_caretPosition
+1);
1305 cmdEvent
.SetContainer(GetFocusObject());
1306 GetEventHandler()->ProcessEvent(cmdEvent
);
1312 long keycode
= event
.GetKeyCode();
1324 if (event
.CmdDown())
1326 // Fixes AltGr+key with European input languages on Windows
1327 if ((event
.CmdDown() && !event
.AltDown()) || (event
.AltDown() && !event
.CmdDown()))
1334 wxRichTextEvent
cmdEvent(
1335 wxEVT_COMMAND_RICHTEXT_CHARACTER
,
1337 cmdEvent
.SetEventObject(this);
1338 cmdEvent
.SetFlags(flags
);
1340 cmdEvent
.SetCharacter(event
.GetUnicodeKey());
1342 cmdEvent
.SetCharacter((wxChar
) keycode
);
1344 cmdEvent
.SetPosition(m_caretPosition
+1);
1345 cmdEvent
.SetContainer(GetFocusObject());
1347 if (keycode
== wxT('\t'))
1349 // See if we need to promote or demote the selection or paragraph at the cursor
1350 // position, instead of inserting a tab.
1351 long pos
= GetAdjustedCaretPosition(GetCaretPosition());
1352 wxRichTextParagraph
* para
= GetFocusObject()->GetParagraphAtPosition(pos
);
1353 if (para
&& para
->GetRange().GetStart() == pos
&& para
->GetAttributes().HasListStyleName())
1355 wxRichTextRange range
;
1357 range
= GetSelectionRange();
1359 range
= para
->GetRange().FromInternal();
1361 int promoteBy
= event
.ShiftDown() ? 1 : -1;
1363 PromoteList(promoteBy
, range
, NULL
);
1365 GetEventHandler()->ProcessEvent(cmdEvent
);
1371 BeginBatchUndo(_("Insert Text"));
1373 long newPos
= m_caretPosition
;
1374 DeleteSelectedContent(& newPos
);
1377 wxString str
= event
.GetUnicodeKey();
1379 wxString str
= (wxChar
) event
.GetKeyCode();
1381 GetFocusObject()->InsertTextWithUndo(newPos
+1, str
, this, & GetBuffer(), 0);
1385 SetDefaultStyleToCursorStyle();
1386 ScrollIntoView(m_caretPosition
, WXK_RIGHT
);
1388 cmdEvent
.SetPosition(m_caretPosition
);
1389 GetEventHandler()->ProcessEvent(cmdEvent
);
1397 /// Delete content if there is a selection, e.g. when pressing a key.
1398 bool wxRichTextCtrl::DeleteSelectedContent(long* newPos
)
1402 long pos
= m_selection
.GetRange().GetStart();
1403 wxRichTextRange range
= m_selection
.GetRange();
1405 // SelectAll causes more to be selected than doing it interactively,
1406 // and causes a new paragraph to be inserted. So for multiline buffers,
1407 // don't delete the final position.
1408 if (range
.GetEnd() == GetLastPosition() && GetNumberOfLines() > 0)
1409 range
.SetEnd(range
.GetEnd()-1);
1411 GetFocusObject()->DeleteRangeWithUndo(range
, this, & GetBuffer());
1412 m_selection
.Reset();
1413 m_selectionState
= wxRichTextCtrlSelectionState_Normal
;
1423 /// Keyboard navigation
1427 Left: left one character
1428 Right: right one character
1431 Ctrl-Left: left one word
1432 Ctrl-Right: right one word
1433 Ctrl-Up: previous paragraph start
1434 Ctrl-Down: next start of paragraph
1437 Ctrl-Home: start of document
1438 Ctrl-End: end of document
1439 Page-Up: Up a screen
1440 Page-Down: Down a screen
1444 Ctrl-Alt-PgUp: Start of window
1445 Ctrl-Alt-PgDn: End of window
1446 F8: Start selection mode
1447 Esc: End selection mode
1449 Adding Shift does the above but starts/extends selection.
1454 bool wxRichTextCtrl::KeyboardNavigate(int keyCode
, int flags
)
1456 bool success
= false;
1458 if (keyCode
== WXK_RIGHT
|| keyCode
== WXK_NUMPAD_RIGHT
)
1460 if (flags
& wxRICHTEXT_CTRL_DOWN
)
1461 success
= WordRight(1, flags
);
1463 success
= MoveRight(1, flags
);
1465 else if (keyCode
== WXK_LEFT
|| keyCode
== WXK_NUMPAD_LEFT
)
1467 if (flags
& wxRICHTEXT_CTRL_DOWN
)
1468 success
= WordLeft(1, flags
);
1470 success
= MoveLeft(1, flags
);
1472 else if (keyCode
== WXK_UP
|| keyCode
== WXK_NUMPAD_UP
)
1474 if (flags
& wxRICHTEXT_CTRL_DOWN
)
1475 success
= MoveToParagraphStart(flags
);
1477 success
= MoveUp(1, flags
);
1479 else if (keyCode
== WXK_DOWN
|| keyCode
== WXK_NUMPAD_DOWN
)
1481 if (flags
& wxRICHTEXT_CTRL_DOWN
)
1482 success
= MoveToParagraphEnd(flags
);
1484 success
= MoveDown(1, flags
);
1486 else if (keyCode
== WXK_PAGEUP
|| keyCode
== WXK_NUMPAD_PAGEUP
)
1488 success
= PageUp(1, flags
);
1490 else if (keyCode
== WXK_PAGEDOWN
|| keyCode
== WXK_NUMPAD_PAGEDOWN
)
1492 success
= PageDown(1, flags
);
1494 else if (keyCode
== WXK_HOME
|| keyCode
== WXK_NUMPAD_HOME
)
1496 if (flags
& wxRICHTEXT_CTRL_DOWN
)
1497 success
= MoveHome(flags
);
1499 success
= MoveToLineStart(flags
);
1501 else if (keyCode
== WXK_END
|| keyCode
== WXK_NUMPAD_END
)
1503 if (flags
& wxRICHTEXT_CTRL_DOWN
)
1504 success
= MoveEnd(flags
);
1506 success
= MoveToLineEnd(flags
);
1511 ScrollIntoView(m_caretPosition
, keyCode
);
1512 SetDefaultStyleToCursorStyle();
1518 /// Extend the selection. Selections are in caret positions.
1519 bool wxRichTextCtrl::ExtendSelection(long oldPos
, long newPos
, int flags
)
1521 if (flags
& wxRICHTEXT_SHIFT_DOWN
)
1523 if (oldPos
== newPos
)
1526 wxRichTextSelection oldSelection
= m_selection
;
1528 m_selection
.SetContainer(GetFocusObject());
1530 wxRichTextRange oldRange
;
1531 if (m_selection
.IsValid())
1532 oldRange
= m_selection
.GetRange();
1534 oldRange
= wxRICHTEXT_NO_SELECTION
;
1535 wxRichTextRange newRange
;
1537 // If not currently selecting, start selecting
1538 if (oldRange
.GetStart() == -2)
1540 m_selectionAnchor
= oldPos
;
1542 if (oldPos
> newPos
)
1543 newRange
.SetRange(newPos
+1, oldPos
);
1545 newRange
.SetRange(oldPos
+1, newPos
);
1549 // Always ensure that the selection range start is greater than
1551 if (newPos
> m_selectionAnchor
)
1552 newRange
.SetRange(m_selectionAnchor
+1, newPos
);
1553 else if (newPos
== m_selectionAnchor
)
1554 newRange
= wxRichTextRange(-2, -2);
1556 newRange
.SetRange(newPos
+1, m_selectionAnchor
);
1559 m_selection
.SetRange(newRange
);
1561 RefreshForSelectionChange(oldSelection
, m_selection
);
1563 if (newRange
.GetStart() > newRange
.GetEnd())
1565 wxLogDebug(wxT("Strange selection range"));
1574 /// Scroll into view, returning true if we scrolled.
1575 /// This takes a _caret_ position.
1576 bool wxRichTextCtrl::ScrollIntoView(long position
, int keyCode
)
1578 wxRichTextLine
* line
= GetVisibleLineForCaretPosition(position
);
1584 GetScrollPixelsPerUnit(& ppuX
, & ppuY
);
1586 int startXUnits
, startYUnits
;
1587 GetViewStart(& startXUnits
, & startYUnits
);
1588 int startY
= startYUnits
* ppuY
;
1591 GetVirtualSize(& sx
, & sy
);
1597 wxRect rect
= line
->GetRect();
1599 bool scrolled
= false;
1601 wxSize clientSize
= GetClientSize();
1603 int leftMargin
, rightMargin
, topMargin
, bottomMargin
;
1606 wxClientDC
dc(this);
1607 wxRichTextObject::GetTotalMargin(dc
, & GetBuffer(), GetBuffer().GetAttributes(), leftMargin
, rightMargin
,
1608 topMargin
, bottomMargin
);
1610 // clientSize.y -= GetBuffer().GetBottomMargin();
1611 clientSize
.y
-= bottomMargin
;
1613 if (GetWindowStyle() & wxRE_CENTRE_CARET
)
1615 int y
= rect
.y
- GetClientSize().y
/2;
1616 int yUnits
= (int) (0.5 + ((float) y
)/(float) ppuY
);
1617 if (y
>= 0 && (y
+ clientSize
.y
) < GetBuffer().GetCachedSize().y
)
1619 if (startYUnits
!= yUnits
)
1621 SetScrollbars(ppuX
, ppuY
, sxUnits
, syUnits
, 0, yUnits
);
1624 #if !wxRICHTEXT_USE_OWN_CARET
1634 if (keyCode
== WXK_DOWN
|| keyCode
== WXK_NUMPAD_DOWN
||
1635 keyCode
== WXK_RIGHT
|| keyCode
== WXK_NUMPAD_RIGHT
||
1636 keyCode
== WXK_END
|| keyCode
== WXK_NUMPAD_END
||
1637 keyCode
== WXK_PAGEDOWN
|| keyCode
== WXK_NUMPAD_PAGEDOWN
)
1639 if ((rect
.y
+ rect
.height
) > (clientSize
.y
+ startY
))
1641 // Make it scroll so this item is at the bottom
1643 int y
= rect
.y
- (clientSize
.y
- rect
.height
);
1644 int yUnits
= (int) (0.5 + ((float) y
)/(float) ppuY
);
1646 // If we're still off the screen, scroll another line down
1647 if ((rect
.y
+ rect
.height
) > (clientSize
.y
+ (yUnits
*ppuY
)))
1650 if (startYUnits
!= yUnits
)
1652 SetScrollbars(ppuX
, ppuY
, sxUnits
, syUnits
, 0, yUnits
);
1656 else if (rect
.y
< (startY
+ GetBuffer().GetTopMargin()))
1658 // Make it scroll so this item is at the top
1660 int y
= rect
.y
- GetBuffer().GetTopMargin();
1661 int yUnits
= (int) (0.5 + ((float) y
)/(float) ppuY
);
1663 if (startYUnits
!= yUnits
)
1665 SetScrollbars(ppuX
, ppuY
, sxUnits
, syUnits
, 0, yUnits
);
1671 else if (keyCode
== WXK_UP
|| keyCode
== WXK_NUMPAD_UP
||
1672 keyCode
== WXK_LEFT
|| keyCode
== WXK_NUMPAD_LEFT
||
1673 keyCode
== WXK_HOME
|| keyCode
== WXK_NUMPAD_HOME
||
1674 keyCode
== WXK_PAGEUP
|| keyCode
== WXK_NUMPAD_PAGEUP
)
1676 if (rect
.y
< (startY
+ GetBuffer().GetBottomMargin()))
1678 // Make it scroll so this item is at the top
1680 int y
= rect
.y
- GetBuffer().GetTopMargin();
1681 int yUnits
= (int) (0.5 + ((float) y
)/(float) ppuY
);
1683 if (startYUnits
!= yUnits
)
1685 SetScrollbars(ppuX
, ppuY
, sxUnits
, syUnits
, 0, yUnits
);
1689 else if ((rect
.y
+ rect
.height
) > (clientSize
.y
+ startY
))
1691 // Make it scroll so this item is at the bottom
1693 int y
= rect
.y
- (clientSize
.y
- rect
.height
);
1694 int yUnits
= (int) (0.5 + ((float) y
)/(float) ppuY
);
1696 // If we're still off the screen, scroll another line down
1697 if ((rect
.y
+ rect
.height
) > (clientSize
.y
+ (yUnits
*ppuY
)))
1700 if (startYUnits
!= yUnits
)
1702 SetScrollbars(ppuX
, ppuY
, sxUnits
, syUnits
, 0, yUnits
);
1708 #if !wxRICHTEXT_USE_OWN_CARET
1716 /// Is the given position visible on the screen?
1717 bool wxRichTextCtrl::IsPositionVisible(long pos
) const
1719 wxRichTextLine
* line
= GetVisibleLineForCaretPosition(pos
-1);
1725 GetScrollPixelsPerUnit(& ppuX
, & ppuY
);
1728 GetViewStart(& startX
, & startY
);
1730 startY
= startY
* ppuY
;
1732 wxRect rect
= line
->GetRect();
1733 wxSize clientSize
= GetClientSize();
1734 clientSize
.y
-= GetBuffer().GetBottomMargin();
1736 return (rect
.GetTop() >= (startY
+ GetBuffer().GetTopMargin())) && (rect
.GetBottom() <= (startY
+ clientSize
.y
));
1739 void wxRichTextCtrl::SetCaretPosition(long position
, bool showAtLineStart
)
1741 m_caretPosition
= position
;
1742 m_caretAtLineStart
= showAtLineStart
;
1745 /// Move caret one visual step forward: this may mean setting a flag
1746 /// and keeping the same position if we're going from the end of one line
1747 /// to the start of the next, which may be the exact same caret position.
1748 void wxRichTextCtrl::MoveCaretForward(long oldPosition
)
1750 wxRichTextParagraph
* para
= GetFocusObject()->GetParagraphAtPosition(oldPosition
);
1752 // Only do the check if we're not at the end of the paragraph (where things work OK
1754 if (para
&& (oldPosition
!= para
->GetRange().GetEnd() - 1))
1756 wxRichTextLine
* line
= GetFocusObject()->GetLineAtPosition(oldPosition
);
1760 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
1762 // We're at the end of a line. See whether we need to
1763 // stay at the same actual caret position but change visual
1764 // position, or not.
1765 if (oldPosition
== lineRange
.GetEnd())
1767 if (m_caretAtLineStart
)
1769 // We're already at the start of the line, so actually move on now.
1770 m_caretPosition
= oldPosition
+ 1;
1771 m_caretAtLineStart
= false;
1775 // We're showing at the end of the line, so keep to
1776 // the same position but indicate that we're to show
1777 // at the start of the next line.
1778 m_caretPosition
= oldPosition
;
1779 m_caretAtLineStart
= true;
1781 SetDefaultStyleToCursorStyle();
1787 SetDefaultStyleToCursorStyle();
1790 /// Move caret one visual step backward: this may mean setting a flag
1791 /// and keeping the same position if we're going from the end of one line
1792 /// to the start of the next, which may be the exact same caret position.
1793 void wxRichTextCtrl::MoveCaretBack(long oldPosition
)
1795 wxRichTextParagraph
* para
= GetFocusObject()->GetParagraphAtPosition(oldPosition
);
1797 // Only do the check if we're not at the start of the paragraph (where things work OK
1799 if (para
&& (oldPosition
!= para
->GetRange().GetStart()))
1801 wxRichTextLine
* line
= GetFocusObject()->GetLineAtPosition(oldPosition
);
1805 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
1807 // We're at the start of a line. See whether we need to
1808 // stay at the same actual caret position but change visual
1809 // position, or not.
1810 if (oldPosition
== lineRange
.GetStart())
1812 m_caretPosition
= oldPosition
-1;
1813 m_caretAtLineStart
= true;
1816 else if (oldPosition
== lineRange
.GetEnd())
1818 if (m_caretAtLineStart
)
1820 // We're at the start of the line, so keep the same caret position
1821 // but clear the start-of-line flag.
1822 m_caretPosition
= oldPosition
;
1823 m_caretAtLineStart
= false;
1827 // We're showing at the end of the line, so go back
1828 // to the previous character position.
1829 m_caretPosition
= oldPosition
- 1;
1831 SetDefaultStyleToCursorStyle();
1837 SetDefaultStyleToCursorStyle();
1841 bool wxRichTextCtrl::MoveRight(int noPositions
, int flags
)
1843 long endPos
= GetFocusObject()->GetOwnRange().GetEnd();
1845 if (m_caretPosition
+ noPositions
< endPos
)
1847 long oldPos
= m_caretPosition
;
1848 long newPos
= m_caretPosition
+ noPositions
;
1850 bool extendSel
= ExtendSelection(m_caretPosition
, newPos
, flags
);
1854 // Determine by looking at oldPos and m_caretPosition whether
1855 // we moved from the end of a line to the start of the next line, in which case
1856 // we want to adjust the caret position such that it is positioned at the
1857 // start of the next line, rather than jumping past the first character of the
1859 if (noPositions
== 1 && !extendSel
)
1860 MoveCaretForward(oldPos
);
1862 SetCaretPosition(newPos
);
1865 SetDefaultStyleToCursorStyle();
1874 bool wxRichTextCtrl::MoveLeft(int noPositions
, int flags
)
1878 if (m_caretPosition
> startPos
- noPositions
+ 1)
1880 long oldPos
= m_caretPosition
;
1881 long newPos
= m_caretPosition
- noPositions
;
1882 bool extendSel
= ExtendSelection(m_caretPosition
, newPos
, flags
);
1886 if (noPositions
== 1 && !extendSel
)
1887 MoveCaretBack(oldPos
);
1889 SetCaretPosition(newPos
);
1892 SetDefaultStyleToCursorStyle();
1900 // Find the caret position for the combination of hit-test flags and character position.
1901 // Returns the caret position and also an indication of where to place the caret (caretLineStart)
1902 // since this is ambiguous (same position used for end of line and start of next).
1903 long wxRichTextCtrl::FindCaretPositionForCharacterPosition(long position
, int hitTestFlags
, wxRichTextParagraphLayoutBox
* container
,
1904 bool& caretLineStart
)
1906 // If end of previous line, and hitTest is wxRICHTEXT_HITTEST_BEFORE,
1907 // we want to be at the end of the last line but with m_caretAtLineStart set to true,
1908 // so we view the caret at the start of the line.
1909 caretLineStart
= false;
1910 long caretPosition
= position
;
1912 if (hitTestFlags
& wxRICHTEXT_HITTEST_BEFORE
)
1914 wxRichTextLine
* thisLine
= container
->GetLineAtPosition(position
-1);
1915 wxRichTextRange lineRange
;
1917 lineRange
= thisLine
->GetAbsoluteRange();
1919 if (thisLine
&& (position
-1) == lineRange
.GetEnd())
1922 caretLineStart
= true;
1926 wxRichTextParagraph
* para
= container
->GetParagraphAtPosition(position
);
1927 if (para
&& para
->GetRange().GetStart() == position
)
1931 return caretPosition
;
1935 bool wxRichTextCtrl::MoveUp(int noLines
, int flags
)
1937 return MoveDown(- noLines
, flags
);
1941 bool wxRichTextCtrl::MoveDown(int noLines
, int flags
)
1946 long lineNumber
= GetFocusObject()->GetVisibleLineNumber(m_caretPosition
, true, m_caretAtLineStart
);
1947 wxPoint pt
= GetCaret()->GetPosition();
1948 long newLine
= lineNumber
+ noLines
;
1949 bool notInThisObject
= false;
1951 if (lineNumber
!= -1)
1955 long lastLine
= GetFocusObject()->GetVisibleLineNumber(GetFocusObject()->GetOwnRange().GetEnd());
1956 if (newLine
> lastLine
)
1957 notInThisObject
= true;
1962 notInThisObject
= true;
1966 wxRichTextParagraphLayoutBox
* container
= GetFocusObject();
1967 int hitTestFlags
= wxRICHTEXT_HITTEST_NO_NESTED_OBJECTS
|wxRICHTEXT_HITTEST_NO_FLOATING_OBJECTS
;
1969 if (notInThisObject
)
1971 // If we know we're navigating out of the current object,
1972 // try to find an object anywhere in the buffer at the new position (up or down a bit)
1973 container
= & GetBuffer();
1974 hitTestFlags
&= ~wxRICHTEXT_HITTEST_NO_NESTED_OBJECTS
;
1976 if (noLines
> 0) // going down
1978 pt
.y
= GetFocusObject()->GetPosition().y
+ GetFocusObject()->GetCachedSize().y
+ 2;
1982 pt
.y
= GetFocusObject()->GetPosition().y
- 2;
1987 wxRichTextLine
* lineObj
= GetFocusObject()->GetLineForVisibleLineNumber(newLine
);
1989 pt
.y
= lineObj
->GetAbsolutePosition().y
+ 2;
1995 wxClientDC
dc(this);
1997 dc
.SetFont(GetFont());
1999 wxRichTextObject
* hitObj
= NULL
;
2000 wxRichTextObject
* contextObj
= NULL
;
2001 int hitTest
= container
->HitTest(dc
, pt
, newPos
, & hitObj
, & contextObj
, hitTestFlags
);
2004 ((hitTest
& wxRICHTEXT_HITTEST_NONE
) == 0) &&
2005 (! (hitObj
== (& m_buffer
) && ((hitTest
& wxRICHTEXT_HITTEST_OUTSIDE
) != 0))) // outside the buffer counts as 'do nothing'
2008 if (notInThisObject
)
2010 wxRichTextParagraphLayoutBox
* actualContainer
= wxDynamicCast(contextObj
, wxRichTextParagraphLayoutBox
);
2011 if (actualContainer
&& actualContainer
!= GetFocusObject() && actualContainer
->AcceptsFocus())
2013 SetFocusObject(actualContainer
, false /* don't set caret position yet */);
2015 container
= actualContainer
;
2019 bool caretLineStart
= true;
2020 long caretPosition
= FindCaretPositionForCharacterPosition(newPos
, hitTest
, container
, caretLineStart
);
2021 long newSelEnd
= caretPosition
;
2024 if (notInThisObject
)
2027 extendSel
= ExtendSelection(m_caretPosition
, newSelEnd
, flags
);
2032 SetCaretPosition(caretPosition
, caretLineStart
);
2034 SetDefaultStyleToCursorStyle();
2042 /// Move to the end of the paragraph
2043 bool wxRichTextCtrl::MoveToParagraphEnd(int flags
)
2045 wxRichTextParagraph
* para
= GetFocusObject()->GetParagraphAtPosition(m_caretPosition
, true);
2048 long newPos
= para
->GetRange().GetEnd() - 1;
2049 bool extendSel
= ExtendSelection(m_caretPosition
, newPos
, flags
);
2053 SetCaretPosition(newPos
);
2055 SetDefaultStyleToCursorStyle();
2063 /// Move to the start of the paragraph
2064 bool wxRichTextCtrl::MoveToParagraphStart(int flags
)
2066 wxRichTextParagraph
* para
= GetFocusObject()->GetParagraphAtPosition(m_caretPosition
, true);
2069 long newPos
= para
->GetRange().GetStart() - 1;
2070 bool extendSel
= ExtendSelection(m_caretPosition
, newPos
, flags
);
2074 SetCaretPosition(newPos
);
2076 SetDefaultStyleToCursorStyle();
2084 /// Move to the end of the line
2085 bool wxRichTextCtrl::MoveToLineEnd(int flags
)
2087 wxRichTextLine
* line
= GetVisibleLineForCaretPosition(m_caretPosition
);
2091 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
2092 long newPos
= lineRange
.GetEnd();
2093 bool extendSel
= ExtendSelection(m_caretPosition
, newPos
, flags
);
2097 SetCaretPosition(newPos
);
2099 SetDefaultStyleToCursorStyle();
2107 /// Move to the start of the line
2108 bool wxRichTextCtrl::MoveToLineStart(int flags
)
2110 wxRichTextLine
* line
= GetVisibleLineForCaretPosition(m_caretPosition
);
2113 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
2114 long newPos
= lineRange
.GetStart()-1;
2116 bool extendSel
= ExtendSelection(m_caretPosition
, newPos
, flags
);
2120 wxRichTextParagraph
* para
= GetFocusObject()->GetParagraphForLine(line
);
2122 SetCaretPosition(newPos
, para
->GetRange().GetStart() != lineRange
.GetStart());
2124 SetDefaultStyleToCursorStyle();
2132 /// Move to the start of the buffer
2133 bool wxRichTextCtrl::MoveHome(int flags
)
2135 if (m_caretPosition
!= -1)
2137 bool extendSel
= ExtendSelection(m_caretPosition
, -1, flags
);
2141 SetCaretPosition(-1);
2143 SetDefaultStyleToCursorStyle();
2151 /// Move to the end of the buffer
2152 bool wxRichTextCtrl::MoveEnd(int flags
)
2154 long endPos
= GetFocusObject()->GetOwnRange().GetEnd()-1;
2156 if (m_caretPosition
!= endPos
)
2158 bool extendSel
= ExtendSelection(m_caretPosition
, endPos
, flags
);
2162 SetCaretPosition(endPos
);
2164 SetDefaultStyleToCursorStyle();
2172 /// Move noPages pages up
2173 bool wxRichTextCtrl::PageUp(int noPages
, int flags
)
2175 return PageDown(- noPages
, flags
);
2178 /// Move noPages pages down
2179 bool wxRichTextCtrl::PageDown(int noPages
, int flags
)
2181 // Calculate which line occurs noPages * screen height further down.
2182 wxRichTextLine
* line
= GetVisibleLineForCaretPosition(m_caretPosition
);
2185 wxSize clientSize
= GetClientSize();
2186 int newY
= line
->GetAbsolutePosition().y
+ noPages
*clientSize
.y
;
2188 wxRichTextLine
* newLine
= GetFocusObject()->GetLineAtYPosition(newY
);
2191 wxRichTextRange lineRange
= newLine
->GetAbsoluteRange();
2192 long pos
= lineRange
.GetStart()-1;
2193 if (pos
!= m_caretPosition
)
2195 wxRichTextParagraph
* para
= GetFocusObject()->GetParagraphForLine(newLine
);
2197 bool extendSel
= ExtendSelection(m_caretPosition
, pos
, flags
);
2201 SetCaretPosition(pos
, para
->GetRange().GetStart() != lineRange
.GetStart());
2203 SetDefaultStyleToCursorStyle();
2213 static bool wxRichTextCtrlIsWhitespace(const wxString
& str
)
2215 return str
== wxT(" ") || str
== wxT("\t");
2218 // Finds the caret position for the next word
2219 long wxRichTextCtrl::FindNextWordPosition(int direction
) const
2221 long endPos
= GetFocusObject()->GetOwnRange().GetEnd();
2225 long i
= m_caretPosition
+1+direction
; // +1 for conversion to character pos
2227 // First skip current text to space
2228 while (i
< endPos
&& i
> -1)
2230 // i is in character, not caret positions
2231 wxString text
= GetFocusObject()->GetTextForRange(wxRichTextRange(i
, i
));
2232 wxRichTextLine
* line
= GetFocusObject()->GetLineAtPosition(i
, false);
2233 if (line
&& (i
== line
->GetAbsoluteRange().GetEnd()))
2237 else if (!wxRichTextCtrlIsWhitespace(text
) && !text
.empty())
2244 while (i
< endPos
&& i
> -1)
2246 // i is in character, not caret positions
2247 wxString text
= GetFocusObject()->GetTextForRange(wxRichTextRange(i
, i
));
2248 wxRichTextLine
* line
= GetFocusObject()->GetLineAtPosition(i
, false);
2249 if (line
&& (i
== line
->GetAbsoluteRange().GetEnd()))
2250 return wxMax(-1, i
);
2252 if (text
.empty()) // End of paragraph, or maybe an image
2253 return wxMax(-1, i
- 1);
2254 else if (wxRichTextCtrlIsWhitespace(text
) || text
.empty())
2258 // Convert to caret position
2259 return wxMax(-1, i
- 1);
2268 long i
= m_caretPosition
;
2270 // First skip white space
2271 while (i
< endPos
&& i
> -1)
2273 // i is in character, not caret positions
2274 wxString text
= GetFocusObject()->GetTextForRange(wxRichTextRange(i
, i
));
2275 wxRichTextLine
* line
= GetFocusObject()->GetLineAtPosition(i
, false);
2277 if (text
.empty() || (line
&& (i
== line
->GetAbsoluteRange().GetStart()))) // End of paragraph, or maybe an image
2279 else if (wxRichTextCtrlIsWhitespace(text
) || text
.empty())
2284 // Next skip current text to space
2285 while (i
< endPos
&& i
> -1)
2287 // i is in character, not caret positions
2288 wxString text
= GetFocusObject()->GetTextForRange(wxRichTextRange(i
, i
));
2289 wxRichTextLine
* line
= GetFocusObject()->GetLineAtPosition(i
, false);
2290 if (line
&& line
->GetAbsoluteRange().GetStart() == i
)
2293 if (!wxRichTextCtrlIsWhitespace(text
) /* && !text.empty() */)
2306 /// Move n words left
2307 bool wxRichTextCtrl::WordLeft(int WXUNUSED(n
), int flags
)
2309 long pos
= FindNextWordPosition(-1);
2310 if (pos
!= m_caretPosition
)
2312 wxRichTextParagraph
* para
= GetFocusObject()->GetParagraphAtPosition(pos
, true);
2314 bool extendSel
= ExtendSelection(m_caretPosition
, pos
, flags
);
2318 SetCaretPosition(pos
, para
->GetRange().GetStart() != pos
);
2320 SetDefaultStyleToCursorStyle();
2328 /// Move n words right
2329 bool wxRichTextCtrl::WordRight(int WXUNUSED(n
), int flags
)
2331 long pos
= FindNextWordPosition(1);
2332 if (pos
!= m_caretPosition
)
2334 wxRichTextParagraph
* para
= GetFocusObject()->GetParagraphAtPosition(pos
, true);
2336 bool extendSel
= ExtendSelection(m_caretPosition
, pos
, flags
);
2340 SetCaretPosition(pos
, para
->GetRange().GetStart() != pos
);
2342 SetDefaultStyleToCursorStyle();
2351 void wxRichTextCtrl::OnSize(wxSizeEvent
& event
)
2353 // Only do sizing optimization for large buffers
2354 if (GetBuffer().GetOwnRange().GetEnd() > m_delayedLayoutThreshold
)
2356 m_fullLayoutRequired
= true;
2357 m_fullLayoutTime
= wxGetLocalTimeMillis();
2358 m_fullLayoutSavedPosition
= GetFirstVisiblePosition();
2359 LayoutContent(true /* onlyVisibleRect */);
2362 GetBuffer().Invalidate(wxRICHTEXT_ALL
);
2364 #if wxRICHTEXT_BUFFERED_PAINTING
2371 // Force any pending layout due to large buffer
2372 void wxRichTextCtrl::ForceDelayedLayout()
2374 if (m_fullLayoutRequired
)
2376 m_fullLayoutRequired
= false;
2377 m_fullLayoutTime
= 0;
2378 GetBuffer().Invalidate(wxRICHTEXT_ALL
);
2379 ShowPosition(m_fullLayoutSavedPosition
);
2385 /// Idle-time processing
2386 void wxRichTextCtrl::OnIdle(wxIdleEvent
& event
)
2388 #if wxRICHTEXT_USE_OWN_CARET
2389 if (((wxRichTextCaret
*) GetCaret())->GetNeedsUpdate())
2391 ((wxRichTextCaret
*) GetCaret())->SetNeedsUpdate(false);
2397 const int layoutInterval
= wxRICHTEXT_DEFAULT_LAYOUT_INTERVAL
;
2399 if (m_fullLayoutRequired
&& (wxGetLocalTimeMillis() > (m_fullLayoutTime
+ layoutInterval
)))
2401 m_fullLayoutRequired
= false;
2402 m_fullLayoutTime
= 0;
2403 GetBuffer().Invalidate(wxRICHTEXT_ALL
);
2404 ShowPosition(m_fullLayoutSavedPosition
);
2408 if (m_caretPositionForDefaultStyle
!= -2)
2410 // If the caret position has changed, no longer reflect the default style
2412 if (GetCaretPosition() != m_caretPositionForDefaultStyle
)
2413 m_caretPositionForDefaultStyle
= -2;
2420 void wxRichTextCtrl::OnScroll(wxScrollWinEvent
& event
)
2422 #if wxRICHTEXT_USE_OWN_CARET
2423 if (!((wxRichTextCaret
*) GetCaret())->GetNeedsUpdate())
2426 ((wxRichTextCaret
*) GetCaret())->SetNeedsUpdate();
2433 /// Set up scrollbars, e.g. after a resize
2434 void wxRichTextCtrl::SetupScrollbars(bool atTop
)
2439 if (GetBuffer().IsEmpty())
2441 SetScrollbars(0, 0, 0, 0, 0, 0);
2445 // TODO: reimplement scrolling so we scroll by line, not by fixed number
2446 // of pixels. See e.g. wxVScrolledWindow for ideas.
2447 int pixelsPerUnit
= 5;
2448 wxSize clientSize
= GetClientSize();
2450 int maxHeight
= GetBuffer().GetCachedSize().y
+ GetBuffer().GetTopMargin();
2452 // Round up so we have at least maxHeight pixels
2453 int unitsY
= (int) (((float)maxHeight
/(float)pixelsPerUnit
) + 0.5);
2455 int startX
= 0, startY
= 0;
2457 GetViewStart(& startX
, & startY
);
2459 int maxPositionX
= 0;
2460 int maxPositionY
= (int) ((((float)(wxMax((unitsY
*pixelsPerUnit
) - clientSize
.y
, 0)))/((float)pixelsPerUnit
)) + 0.5);
2462 int newStartX
= wxMin(maxPositionX
, startX
);
2463 int newStartY
= wxMin(maxPositionY
, startY
);
2465 int oldPPUX
, oldPPUY
;
2466 int oldStartX
, oldStartY
;
2467 int oldVirtualSizeX
= 0, oldVirtualSizeY
= 0;
2468 GetScrollPixelsPerUnit(& oldPPUX
, & oldPPUY
);
2469 GetViewStart(& oldStartX
, & oldStartY
);
2470 GetVirtualSize(& oldVirtualSizeX
, & oldVirtualSizeY
);
2472 oldVirtualSizeY
/= oldPPUY
;
2474 if (oldPPUX
== 0 && oldPPUY
== pixelsPerUnit
&& oldVirtualSizeY
== unitsY
&& oldStartX
== newStartX
&& oldStartY
== newStartY
)
2477 // Don't set scrollbars if there were none before, and there will be none now.
2478 if (oldPPUY
!= 0 && (oldVirtualSizeY
*oldPPUY
< clientSize
.y
) && (unitsY
*pixelsPerUnit
< clientSize
.y
))
2481 // Move to previous scroll position if
2483 SetScrollbars(0, pixelsPerUnit
, 0, unitsY
, newStartX
, newStartY
);
2486 /// Paint the background
2487 void wxRichTextCtrl::PaintBackground(wxDC
& dc
)
2489 wxColour backgroundColour
= GetBackgroundColour();
2490 if (!backgroundColour
.IsOk())
2491 backgroundColour
= wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE
);
2493 // Clear the background
2494 dc
.SetBrush(wxBrush(backgroundColour
));
2495 dc
.SetPen(*wxTRANSPARENT_PEN
);
2496 wxRect
windowRect(GetClientSize());
2497 windowRect
.x
-= 2; windowRect
.y
-= 2;
2498 windowRect
.width
+= 4; windowRect
.height
+= 4;
2500 // We need to shift the rectangle to take into account
2501 // scrolling. Converting device to logical coordinates.
2502 CalcUnscrolledPosition(windowRect
.x
, windowRect
.y
, & windowRect
.x
, & windowRect
.y
);
2503 dc
.DrawRectangle(windowRect
);
2506 #if wxRICHTEXT_BUFFERED_PAINTING
2507 /// Recreate buffer bitmap if necessary
2508 bool wxRichTextCtrl::RecreateBuffer(const wxSize
& size
)
2511 if (sz
== wxDefaultSize
)
2512 sz
= GetClientSize();
2514 if (sz
.x
< 1 || sz
.y
< 1)
2517 if (!m_bufferBitmap
.IsOk() || m_bufferBitmap
.GetWidth() < sz
.x
|| m_bufferBitmap
.GetHeight() < sz
.y
)
2518 m_bufferBitmap
= wxBitmap(sz
.x
, sz
.y
);
2519 return m_bufferBitmap
.IsOk();
2523 // ----------------------------------------------------------------------------
2524 // file IO functions
2525 // ----------------------------------------------------------------------------
2527 bool wxRichTextCtrl::DoLoadFile(const wxString
& filename
, int fileType
)
2529 bool success
= GetBuffer().LoadFile(filename
, (wxRichTextFileType
)fileType
);
2531 m_filename
= filename
;
2534 SetInsertionPoint(0);
2537 SetupScrollbars(true);
2539 wxTextCtrl::SendTextUpdatedEvent(this);
2545 wxLogError(_("File couldn't be loaded."));
2551 bool wxRichTextCtrl::DoSaveFile(const wxString
& filename
, int fileType
)
2553 if (GetBuffer().SaveFile(filename
, (wxRichTextFileType
)fileType
))
2555 m_filename
= filename
;
2562 wxLogError(_("The text couldn't be saved."));
2567 // ----------------------------------------------------------------------------
2568 // wxRichTextCtrl specific functionality
2569 // ----------------------------------------------------------------------------
2571 /// Add a new paragraph of text to the end of the buffer
2572 wxRichTextRange
wxRichTextCtrl::AddParagraph(const wxString
& text
)
2574 wxRichTextRange range
= GetFocusObject()->AddParagraph(text
);
2575 GetBuffer().Invalidate();
2581 wxRichTextRange
wxRichTextCtrl::AddImage(const wxImage
& image
)
2583 wxRichTextRange range
= GetFocusObject()->AddImage(image
);
2584 GetBuffer().Invalidate();
2589 // ----------------------------------------------------------------------------
2590 // selection and ranges
2591 // ----------------------------------------------------------------------------
2593 void wxRichTextCtrl::SelectAll()
2595 SetSelection(-1, -1);
2599 void wxRichTextCtrl::SelectNone()
2601 if (m_selection
.IsValid())
2603 wxRichTextSelection oldSelection
= m_selection
;
2605 m_selection
.Reset();
2607 RefreshForSelectionChange(oldSelection
, m_selection
);
2609 m_selectionAnchor
= -2;
2610 m_selectionAnchorObject
= NULL
;
2611 m_selectionState
= wxRichTextCtrlSelectionState_Normal
;
2614 static bool wxIsWordDelimiter(const wxString
& text
)
2616 return !text
.IsEmpty() && !wxIsalnum(text
[0]);
2619 /// Select the word at the given character position
2620 bool wxRichTextCtrl::SelectWord(long position
)
2622 if (position
< 0 || position
> GetFocusObject()->GetOwnRange().GetEnd())
2625 wxRichTextParagraph
* para
= GetFocusObject()->GetParagraphAtPosition(position
);
2629 if (position
== para
->GetRange().GetEnd())
2632 long positionStart
= position
;
2633 long positionEnd
= position
;
2635 for (positionStart
= position
; positionStart
>= para
->GetRange().GetStart(); positionStart
--)
2637 wxString text
= GetFocusObject()->GetTextForRange(wxRichTextRange(positionStart
, positionStart
));
2638 if (wxIsWordDelimiter(text
))
2644 if (positionStart
< para
->GetRange().GetStart())
2645 positionStart
= para
->GetRange().GetStart();
2647 for (positionEnd
= position
; positionEnd
< para
->GetRange().GetEnd(); positionEnd
++)
2649 wxString text
= GetFocusObject()->GetTextForRange(wxRichTextRange(positionEnd
, positionEnd
));
2650 if (wxIsWordDelimiter(text
))
2656 if (positionEnd
>= para
->GetRange().GetEnd())
2657 positionEnd
= para
->GetRange().GetEnd();
2659 if (positionEnd
< positionStart
)
2662 SetSelection(positionStart
, positionEnd
+1);
2664 if (positionStart
>= 0)
2666 MoveCaret(positionStart
-1, true);
2667 SetDefaultStyleToCursorStyle();
2673 wxString
wxRichTextCtrl::GetStringSelection() const
2676 GetSelection(&from
, &to
);
2678 return GetRange(from
, to
);
2681 // ----------------------------------------------------------------------------
2683 // ----------------------------------------------------------------------------
2685 wxTextCtrlHitTestResult
2686 wxRichTextCtrl::HitTest(const wxPoint
& pt
, wxTextCoord
*x
, wxTextCoord
*y
) const
2688 // implement in terms of the other overload as the native ports typically
2689 // can get the position and not (x, y) pair directly (although wxUniv
2690 // directly gets x and y -- and so overrides this method as well)
2692 wxTextCtrlHitTestResult rc
= HitTest(pt
, &pos
);
2694 if ( rc
!= wxTE_HT_UNKNOWN
)
2696 PositionToXY(pos
, x
, y
);
2702 wxTextCtrlHitTestResult
2703 wxRichTextCtrl::HitTest(const wxPoint
& pt
,
2706 wxClientDC
dc((wxRichTextCtrl
*) this);
2707 ((wxRichTextCtrl
*)this)->PrepareDC(dc
);
2709 // Buffer uses logical position (relative to start of buffer)
2711 wxPoint pt2
= GetLogicalPoint(pt
);
2713 wxRichTextObject
* hitObj
= NULL
;
2714 wxRichTextObject
* contextObj
= NULL
;
2715 int hit
= ((wxRichTextCtrl
*)this)->GetFocusObject()->HitTest(dc
, pt2
, *pos
, & hitObj
, & contextObj
, wxRICHTEXT_HITTEST_NO_NESTED_OBJECTS
);
2717 if ((hit
& wxRICHTEXT_HITTEST_BEFORE
) && (hit
& wxRICHTEXT_HITTEST_OUTSIDE
))
2718 return wxTE_HT_BEFORE
;
2719 else if ((hit
& wxRICHTEXT_HITTEST_AFTER
) && (hit
& wxRICHTEXT_HITTEST_OUTSIDE
))
2720 return wxTE_HT_BEYOND
;
2721 else if (hit
& (wxRICHTEXT_HITTEST_BEFORE
|wxRICHTEXT_HITTEST_AFTER
))
2722 return wxTE_HT_ON_TEXT
;
2724 return wxTE_HT_UNKNOWN
;
2727 wxRichTextParagraphLayoutBox
*
2728 wxRichTextCtrl::FindContainerAtPoint(const wxPoint pt
, long& position
, int& hit
, wxRichTextObject
* hitObj
, int flags
/* = 0*/)
2730 wxClientDC
dc(this);
2732 dc
.SetFont(GetFont());
2734 wxPoint logicalPt
= GetLogicalPoint(pt
);
2736 wxRichTextObject
* contextObj
= NULL
;
2737 hit
= GetBuffer().HitTest(dc
, logicalPt
, position
, &hitObj
, &contextObj
, flags
);
2738 wxRichTextParagraphLayoutBox
* container
= wxDynamicCast(contextObj
, wxRichTextParagraphLayoutBox
);
2744 // ----------------------------------------------------------------------------
2745 // set/get the controls text
2746 // ----------------------------------------------------------------------------
2748 wxString
wxRichTextCtrl::DoGetValue() const
2750 return GetBuffer().GetText();
2753 wxString
wxRichTextCtrl::GetRange(long from
, long to
) const
2755 // Public API for range is different from internals
2756 return GetFocusObject()->GetTextForRange(wxRichTextRange(from
, to
-1));
2759 void wxRichTextCtrl::DoSetValue(const wxString
& value
, int flags
)
2761 // Don't call Clear here, since it always sends a text updated event
2762 m_buffer
.ResetAndClearCommands();
2763 m_buffer
.Invalidate(wxRICHTEXT_ALL
);
2764 m_caretPosition
= -1;
2765 m_caretPositionForDefaultStyle
= -2;
2766 m_caretAtLineStart
= false;
2767 m_selection
.Reset();
2768 m_selectionState
= wxRichTextCtrlSelectionState_Normal
;
2778 if (!value
.IsEmpty())
2780 // Remove empty paragraph
2781 GetBuffer().Clear();
2782 DoWriteText(value
, flags
);
2784 // for compatibility, don't move the cursor when doing SetValue()
2785 SetInsertionPoint(0);
2789 // still send an event for consistency
2790 if (flags
& SetValue_SendEvent
)
2791 wxTextCtrl::SendTextUpdatedEvent(this);
2796 void wxRichTextCtrl::WriteText(const wxString
& value
)
2801 void wxRichTextCtrl::DoWriteText(const wxString
& value
, int flags
)
2803 wxString valueUnix
= wxTextFile::Translate(value
, wxTextFileType_Unix
);
2805 GetFocusObject()->InsertTextWithUndo(m_caretPosition
+1, valueUnix
, this, & GetBuffer(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
);
2807 if ( flags
& SetValue_SendEvent
)
2808 wxTextCtrl::SendTextUpdatedEvent(this);
2811 void wxRichTextCtrl::AppendText(const wxString
& text
)
2813 SetInsertionPointEnd();
2818 /// Write an image at the current insertion point
2819 bool wxRichTextCtrl::WriteImage(const wxImage
& image
, wxBitmapType bitmapType
, const wxRichTextAttr
& textAttr
)
2821 wxRichTextImageBlock imageBlock
;
2823 wxImage image2
= image
;
2824 if (imageBlock
.MakeImageBlock(image2
, bitmapType
))
2825 return WriteImage(imageBlock
, textAttr
);
2830 bool wxRichTextCtrl::WriteImage(const wxString
& filename
, wxBitmapType bitmapType
, const wxRichTextAttr
& textAttr
)
2832 wxRichTextImageBlock imageBlock
;
2835 if (imageBlock
.MakeImageBlock(filename
, bitmapType
, image
, false))
2836 return WriteImage(imageBlock
, textAttr
);
2841 bool wxRichTextCtrl::WriteImage(const wxRichTextImageBlock
& imageBlock
, const wxRichTextAttr
& textAttr
)
2843 return GetFocusObject()->InsertImageWithUndo(m_caretPosition
+1, imageBlock
, this, & GetBuffer(), 0, textAttr
);
2846 bool wxRichTextCtrl::WriteImage(const wxBitmap
& bitmap
, wxBitmapType bitmapType
, const wxRichTextAttr
& textAttr
)
2850 wxRichTextImageBlock imageBlock
;
2852 wxImage image
= bitmap
.ConvertToImage();
2853 if (image
.IsOk() && imageBlock
.MakeImageBlock(image
, bitmapType
))
2854 return WriteImage(imageBlock
, textAttr
);
2860 // Write a text box at the current insertion point.
2861 wxRichTextBox
* wxRichTextCtrl::WriteTextBox(const wxRichTextAttr
& textAttr
)
2863 wxRichTextBox
* textBox
= new wxRichTextBox
;
2864 textBox
->SetAttributes(textAttr
);
2865 textBox
->SetParent(& GetBuffer()); // set parent temporarily for AddParagraph to use correct style
2866 textBox
->AddParagraph(wxEmptyString
);
2867 textBox
->SetParent(NULL
);
2869 // The object returned is the one actually inserted into the buffer,
2870 // while the original one is deleted.
2871 wxRichTextObject
* obj
= GetFocusObject()->InsertObjectWithUndo(m_caretPosition
+1, textBox
, this, & GetBuffer(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
);
2872 wxRichTextBox
* box
= wxDynamicCast(obj
, wxRichTextBox
);
2876 // Write a table at the current insertion point, returning the table.
2877 wxRichTextTable
* wxRichTextCtrl::WriteTable(int rows
, int cols
, const wxRichTextAttr
& tableAttr
, const wxRichTextAttr
& cellAttr
)
2879 wxASSERT(rows
> 0 && cols
> 0);
2881 if (rows
<= 0 || cols
<= 0)
2884 wxRichTextTable
* table
= new wxRichTextTable
;
2885 table
->SetAttributes(tableAttr
);
2886 table
->SetParent(& GetBuffer()); // set parent temporarily for AddParagraph to use correct style
2888 table
->CreateTable(rows
, cols
);
2890 table
->SetParent(NULL
);
2893 for (j
= 0; j
< rows
; j
++)
2895 for (i
= 0; i
< cols
; i
++)
2897 table
->GetCell(j
, i
)->GetAttributes() = cellAttr
;
2901 // The object returned is the one actually inserted into the buffer,
2902 // while the original one is deleted.
2903 wxRichTextObject
* obj
= GetFocusObject()->InsertObjectWithUndo(m_caretPosition
+1, table
, this, & GetBuffer(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
);
2904 wxRichTextTable
* tableResult
= wxDynamicCast(obj
, wxRichTextTable
);
2909 /// Insert a newline (actually paragraph) at the current insertion point.
2910 bool wxRichTextCtrl::Newline()
2912 return GetFocusObject()->InsertNewlineWithUndo(m_caretPosition
+1, this, & GetBuffer(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
);
2915 /// Insert a line break at the current insertion point.
2916 bool wxRichTextCtrl::LineBreak()
2919 text
= wxRichTextLineBreakChar
;
2920 return GetFocusObject()->InsertTextWithUndo(m_caretPosition
+1, text
, this, & GetBuffer());
2923 // ----------------------------------------------------------------------------
2924 // Clipboard operations
2925 // ----------------------------------------------------------------------------
2927 void wxRichTextCtrl::Copy()
2931 wxRichTextRange range
= GetInternalSelectionRange();
2932 GetBuffer().CopyToClipboard(range
);
2936 void wxRichTextCtrl::Cut()
2940 wxRichTextRange range
= GetInternalSelectionRange();
2941 GetBuffer().CopyToClipboard(range
);
2943 DeleteSelectedContent();
2949 void wxRichTextCtrl::Paste()
2953 BeginBatchUndo(_("Paste"));
2955 long newPos
= m_caretPosition
;
2956 DeleteSelectedContent(& newPos
);
2958 GetBuffer().PasteFromClipboard(newPos
);
2964 void wxRichTextCtrl::DeleteSelection()
2966 if (CanDeleteSelection())
2968 DeleteSelectedContent();
2972 bool wxRichTextCtrl::HasSelection() const
2974 return (m_selection
.IsValid() && m_selection
.GetContainer() == GetFocusObject());
2977 bool wxRichTextCtrl::HasUnfocusedSelection() const
2979 return m_selection
.IsValid();
2982 bool wxRichTextCtrl::CanCopy() const
2984 // Can copy if there's a selection
2985 return HasSelection();
2988 bool wxRichTextCtrl::CanCut() const
2990 return HasSelection() && IsEditable();
2993 bool wxRichTextCtrl::CanPaste() const
2995 if ( !IsEditable() )
2998 return GetBuffer().CanPasteFromClipboard();
3001 bool wxRichTextCtrl::CanDeleteSelection() const
3003 return HasSelection() && IsEditable();
3007 // ----------------------------------------------------------------------------
3009 // ----------------------------------------------------------------------------
3011 void wxRichTextCtrl::SetContextMenu(wxMenu
* menu
)
3013 if (m_contextMenu
&& m_contextMenu
!= menu
)
3014 delete m_contextMenu
;
3015 m_contextMenu
= menu
;
3018 void wxRichTextCtrl::SetEditable(bool editable
)
3020 m_editable
= editable
;
3023 void wxRichTextCtrl::SetInsertionPoint(long pos
)
3027 m_caretPosition
= pos
- 1;
3031 SetDefaultStyleToCursorStyle();
3034 void wxRichTextCtrl::SetInsertionPointEnd()
3036 long pos
= GetLastPosition();
3037 SetInsertionPoint(pos
);
3040 long wxRichTextCtrl::GetInsertionPoint() const
3042 return m_caretPosition
+1;
3045 wxTextPos
wxRichTextCtrl::GetLastPosition() const
3047 return GetFocusObject()->GetOwnRange().GetEnd();
3050 // If the return values from and to are the same, there is no
3052 void wxRichTextCtrl::GetSelection(long* from
, long* to
) const
3054 if (m_selection
.IsValid())
3056 *from
= m_selection
.GetRange().GetStart();
3057 *to
= m_selection
.GetRange().GetEnd();
3067 bool wxRichTextCtrl::IsEditable() const
3072 // ----------------------------------------------------------------------------
3074 // ----------------------------------------------------------------------------
3076 void wxRichTextCtrl::SetSelection(long from
, long to
)
3078 // if from and to are both -1, it means (in wxWidgets) that all text should
3080 if ( (from
== -1) && (to
== -1) )
3083 to
= GetLastPosition()+1;
3092 wxRichTextSelection oldSelection
= m_selection
;
3094 m_selectionAnchor
= from
-1;
3095 m_selectionAnchorObject
= NULL
;
3096 m_selection
.Set(wxRichTextRange(from
, to
-1), GetFocusObject());
3098 m_caretPosition
= wxMax(-1, to
-1);
3100 RefreshForSelectionChange(oldSelection
, m_selection
);
3105 // ----------------------------------------------------------------------------
3107 // ----------------------------------------------------------------------------
3109 void wxRichTextCtrl::Replace(long from
, long to
,
3110 const wxString
& value
)
3112 BeginBatchUndo(_("Replace"));
3114 SetSelection(from
, to
);
3116 wxRichTextAttr attr
= GetDefaultStyle();
3118 DeleteSelectedContent();
3120 SetDefaultStyle(attr
);
3122 DoWriteText(value
, SetValue_SelectionOnly
);
3127 void wxRichTextCtrl::Remove(long from
, long to
)
3131 GetFocusObject()->DeleteRangeWithUndo(wxRichTextRange(from
, to
-1), this, & GetBuffer());
3138 bool wxRichTextCtrl::IsModified() const
3140 return m_buffer
.IsModified();
3143 void wxRichTextCtrl::MarkDirty()
3145 m_buffer
.Modify(true);
3148 void wxRichTextCtrl::DiscardEdits()
3150 m_caretPositionForDefaultStyle
= -2;
3151 m_buffer
.Modify(false);
3152 m_buffer
.GetCommandProcessor()->ClearCommands();
3155 int wxRichTextCtrl::GetNumberOfLines() const
3157 return GetFocusObject()->GetParagraphCount();
3160 // ----------------------------------------------------------------------------
3161 // Positions <-> coords
3162 // ----------------------------------------------------------------------------
3164 long wxRichTextCtrl::XYToPosition(long x
, long y
) const
3166 return GetFocusObject()->XYToPosition(x
, y
);
3169 bool wxRichTextCtrl::PositionToXY(long pos
, long *x
, long *y
) const
3171 return GetFocusObject()->PositionToXY(pos
, x
, y
);
3174 // ----------------------------------------------------------------------------
3176 // ----------------------------------------------------------------------------
3178 void wxRichTextCtrl::ShowPosition(long pos
)
3180 if (!IsPositionVisible(pos
))
3181 ScrollIntoView(pos
-1, WXK_DOWN
);
3184 int wxRichTextCtrl::GetLineLength(long lineNo
) const
3186 return GetFocusObject()->GetParagraphLength(lineNo
);
3189 wxString
wxRichTextCtrl::GetLineText(long lineNo
) const
3191 return GetFocusObject()->GetParagraphText(lineNo
);
3194 // ----------------------------------------------------------------------------
3196 // ----------------------------------------------------------------------------
3198 void wxRichTextCtrl::Undo()
3202 GetCommandProcessor()->Undo();
3206 void wxRichTextCtrl::Redo()
3210 GetCommandProcessor()->Redo();
3214 bool wxRichTextCtrl::CanUndo() const
3216 return GetCommandProcessor()->CanUndo() && IsEditable();
3219 bool wxRichTextCtrl::CanRedo() const
3221 return GetCommandProcessor()->CanRedo() && IsEditable();
3224 // ----------------------------------------------------------------------------
3225 // implementation details
3226 // ----------------------------------------------------------------------------
3228 void wxRichTextCtrl::Command(wxCommandEvent
& event
)
3230 SetValue(event
.GetString());
3231 GetEventHandler()->ProcessEvent(event
);
3234 void wxRichTextCtrl::OnDropFiles(wxDropFilesEvent
& event
)
3236 // By default, load the first file into the text window.
3237 if (event
.GetNumberOfFiles() > 0)
3239 LoadFile(event
.GetFiles()[0]);
3243 wxSize
wxRichTextCtrl::DoGetBestSize() const
3245 return wxSize(10, 10);
3248 // ----------------------------------------------------------------------------
3249 // standard handlers for standard edit menu events
3250 // ----------------------------------------------------------------------------
3252 void wxRichTextCtrl::OnCut(wxCommandEvent
& WXUNUSED(event
))
3257 void wxRichTextCtrl::OnClear(wxCommandEvent
& WXUNUSED(event
))
3262 void wxRichTextCtrl::OnCopy(wxCommandEvent
& WXUNUSED(event
))
3267 void wxRichTextCtrl::OnPaste(wxCommandEvent
& WXUNUSED(event
))
3272 void wxRichTextCtrl::OnUndo(wxCommandEvent
& WXUNUSED(event
))
3277 void wxRichTextCtrl::OnRedo(wxCommandEvent
& WXUNUSED(event
))
3282 void wxRichTextCtrl::OnUpdateCut(wxUpdateUIEvent
& event
)
3284 event
.Enable( CanCut() );
3287 void wxRichTextCtrl::OnUpdateCopy(wxUpdateUIEvent
& event
)
3289 event
.Enable( CanCopy() );
3292 void wxRichTextCtrl::OnUpdateClear(wxUpdateUIEvent
& event
)
3294 event
.Enable( CanDeleteSelection() );
3297 void wxRichTextCtrl::OnUpdatePaste(wxUpdateUIEvent
& event
)
3299 event
.Enable( CanPaste() );
3302 void wxRichTextCtrl::OnUpdateUndo(wxUpdateUIEvent
& event
)
3304 event
.Enable( CanUndo() );
3305 event
.SetText( GetCommandProcessor()->GetUndoMenuLabel() );
3308 void wxRichTextCtrl::OnUpdateRedo(wxUpdateUIEvent
& event
)
3310 event
.Enable( CanRedo() );
3311 event
.SetText( GetCommandProcessor()->GetRedoMenuLabel() );
3314 void wxRichTextCtrl::OnSelectAll(wxCommandEvent
& WXUNUSED(event
))
3316 if (GetLastPosition() > 0)
3320 void wxRichTextCtrl::OnUpdateSelectAll(wxUpdateUIEvent
& event
)
3322 event
.Enable(GetLastPosition() > 0);
3325 void wxRichTextCtrl::OnProperties(wxCommandEvent
& event
)
3327 int idx
= event
.GetId() - wxID_RICHTEXT_PROPERTIES1
;
3328 if (idx
>= 0 && idx
< m_contextMenuPropertiesInfo
.GetCount())
3330 wxRichTextObject
* obj
= m_contextMenuPropertiesInfo
.GetObject(idx
);
3331 if (obj
&& obj
->CanEditProperties())
3332 obj
->EditProperties(this, & GetBuffer());
3334 m_contextMenuPropertiesInfo
.Clear();
3338 void wxRichTextCtrl::OnUpdateProperties(wxUpdateUIEvent
& event
)
3340 int idx
= event
.GetId() - wxID_RICHTEXT_PROPERTIES1
;
3341 event
.Enable(idx
>= 0 && idx
< m_contextMenuPropertiesInfo
.GetCount());
3344 void wxRichTextCtrl::OnContextMenu(wxContextMenuEvent
& event
)
3346 if (event
.GetEventObject() != this)
3352 ShowContextMenu(m_contextMenu
, event
.GetPosition());
3355 // Prepares the context menu, adding appropriate property-editing commands.
3356 // Returns the number of property commands added.
3357 int wxRichTextCtrl::PrepareContextMenu(wxMenu
* menu
, const wxPoint
& pt
, bool addPropertyCommands
)
3359 wxClientDC
dc(this);
3361 dc
.SetFont(GetFont());
3363 m_contextMenuPropertiesInfo
.Clear();
3366 wxRichTextObject
* hitObj
= NULL
;
3367 wxRichTextObject
* contextObj
= NULL
;
3368 if (pt
!= wxDefaultPosition
)
3370 wxPoint logicalPt
= GetLogicalPoint(ScreenToClient(pt
));
3371 int hit
= GetBuffer().HitTest(dc
, logicalPt
, position
, & hitObj
, & contextObj
);
3373 if (hit
== wxRICHTEXT_HITTEST_ON
|| hit
== wxRICHTEXT_HITTEST_BEFORE
|| hit
== wxRICHTEXT_HITTEST_AFTER
)
3375 wxRichTextParagraphLayoutBox
* actualContainer
= wxDynamicCast(contextObj
, wxRichTextParagraphLayoutBox
);
3376 if (hitObj
&& actualContainer
)
3378 if (actualContainer
->AcceptsFocus())
3380 SetFocusObject(actualContainer
, false /* don't set caret position yet */);
3381 SetCaretPositionAfterClick(actualContainer
, position
, hit
);
3384 if (addPropertyCommands
)
3385 m_contextMenuPropertiesInfo
.AddItems(actualContainer
, hitObj
);
3389 if (addPropertyCommands
)
3390 m_contextMenuPropertiesInfo
.AddItems(GetFocusObject(), NULL
);
3395 if (addPropertyCommands
)
3396 m_contextMenuPropertiesInfo
.AddItems(GetFocusObject(), NULL
);
3401 // Invoked from the keyboard, so don't set the caret position and don't use the event
3403 hitObj
= GetFocusObject()->GetLeafObjectAtPosition(m_caretPosition
+1);
3405 contextObj
= hitObj
->GetParentContainer();
3407 contextObj
= GetFocusObject();
3409 wxRichTextParagraphLayoutBox
* actualContainer
= wxDynamicCast(contextObj
, wxRichTextParagraphLayoutBox
);
3410 if (hitObj
&& actualContainer
)
3412 if (addPropertyCommands
)
3413 m_contextMenuPropertiesInfo
.AddItems(actualContainer
, hitObj
);
3417 if (addPropertyCommands
)
3418 m_contextMenuPropertiesInfo
.AddItems(GetFocusObject(), NULL
);
3424 if (addPropertyCommands
)
3425 m_contextMenuPropertiesInfo
.AddMenuItems(menu
);
3426 return m_contextMenuPropertiesInfo
.GetCount();
3432 // Shows the context menu, adding appropriate property-editing commands
3433 bool wxRichTextCtrl::ShowContextMenu(wxMenu
* menu
, const wxPoint
& pt
, bool addPropertyCommands
)
3437 PrepareContextMenu(menu
, pt
, addPropertyCommands
);
3445 bool wxRichTextCtrl::SetStyle(long start
, long end
, const wxTextAttr
& style
)
3447 return GetFocusObject()->SetStyle(wxRichTextRange(start
, end
-1), wxRichTextAttr(style
));
3450 bool wxRichTextCtrl::SetStyle(long start
, long end
, const wxRichTextAttr
& style
)
3452 return GetFocusObject()->SetStyle(wxRichTextRange(start
, end
-1), style
);
3455 bool wxRichTextCtrl::SetStyle(const wxRichTextRange
& range
, const wxTextAttr
& style
)
3457 return GetFocusObject()->SetStyle(range
.ToInternal(), wxRichTextAttr(style
));
3460 bool wxRichTextCtrl::SetStyle(const wxRichTextRange
& range
, const wxRichTextAttr
& style
)
3462 return GetFocusObject()->SetStyle(range
.ToInternal(), style
);
3465 void wxRichTextCtrl::SetStyle(wxRichTextObject
*obj
, const wxRichTextAttr
& textAttr
)
3467 GetFocusObject()->SetStyle(obj
, textAttr
);
3470 // extended style setting operation with flags including:
3471 // wxRICHTEXT_SETSTYLE_WITH_UNDO, wxRICHTEXT_SETSTYLE_OPTIMIZE, wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY.
3472 // see richtextbuffer.h for more details.
3474 bool wxRichTextCtrl::SetStyleEx(const wxRichTextRange
& range
, const wxRichTextAttr
& style
, int flags
)
3476 return GetFocusObject()->SetStyle(range
.ToInternal(), style
, flags
);
3479 bool wxRichTextCtrl::SetDefaultStyle(const wxTextAttr
& style
)
3481 return GetBuffer().SetDefaultStyle(style
);
3484 bool wxRichTextCtrl::SetDefaultStyle(const wxRichTextAttr
& style
)
3486 wxRichTextAttr
attr1(style
);
3487 attr1
.GetTextBoxAttr().Reset();
3488 return GetBuffer().SetDefaultStyle(attr1
);
3491 const wxRichTextAttr
& wxRichTextCtrl::GetDefaultStyleEx() const
3493 return GetBuffer().GetDefaultStyle();
3496 bool wxRichTextCtrl::GetStyle(long position
, wxTextAttr
& style
)
3498 wxRichTextAttr attr
;
3499 if (GetFocusObject()->GetStyle(position
, attr
))
3508 bool wxRichTextCtrl::GetStyle(long position
, wxRichTextAttr
& style
)
3510 return GetFocusObject()->GetStyle(position
, style
);
3513 bool wxRichTextCtrl::GetStyle(long position
, wxRichTextAttr
& style
, wxRichTextParagraphLayoutBox
* container
)
3515 wxRichTextAttr attr
;
3516 if (container
->GetStyle(position
, attr
))
3525 // get the common set of styles for the range
3526 bool wxRichTextCtrl::GetStyleForRange(const wxRichTextRange
& range
, wxTextAttr
& style
)
3528 wxRichTextAttr attr
;
3529 if (GetFocusObject()->GetStyleForRange(range
.ToInternal(), attr
))
3538 bool wxRichTextCtrl::GetStyleForRange(const wxRichTextRange
& range
, wxRichTextAttr
& style
)
3540 return GetFocusObject()->GetStyleForRange(range
.ToInternal(), style
);
3543 bool wxRichTextCtrl::GetStyleForRange(const wxRichTextRange
& range
, wxRichTextAttr
& style
, wxRichTextParagraphLayoutBox
* container
)
3545 return container
->GetStyleForRange(range
.ToInternal(), style
);
3548 /// Get the content (uncombined) attributes for this position.
3549 bool wxRichTextCtrl::GetUncombinedStyle(long position
, wxRichTextAttr
& style
)
3551 return GetFocusObject()->GetUncombinedStyle(position
, style
);
3554 /// Get the content (uncombined) attributes for this position.
3555 bool wxRichTextCtrl::GetUncombinedStyle(long position
, wxRichTextAttr
& style
, wxRichTextParagraphLayoutBox
* container
)
3557 return container
->GetUncombinedStyle(position
, style
);
3560 /// Set font, and also the buffer attributes
3561 bool wxRichTextCtrl::SetFont(const wxFont
& font
)
3563 wxControl::SetFont(font
);
3565 wxRichTextAttr attr
= GetBuffer().GetAttributes();
3567 GetBuffer().SetBasicStyle(attr
);
3569 GetBuffer().Invalidate(wxRICHTEXT_ALL
);
3575 /// Transform logical to physical
3576 wxPoint
wxRichTextCtrl::GetPhysicalPoint(const wxPoint
& ptLogical
) const
3579 CalcScrolledPosition(ptLogical
.x
, ptLogical
.y
, & pt
.x
, & pt
.y
);
3584 /// Transform physical to logical
3585 wxPoint
wxRichTextCtrl::GetLogicalPoint(const wxPoint
& ptPhysical
) const
3588 CalcUnscrolledPosition(ptPhysical
.x
, ptPhysical
.y
, & pt
.x
, & pt
.y
);
3593 /// Position the caret
3594 void wxRichTextCtrl::PositionCaret(wxRichTextParagraphLayoutBox
* container
)
3599 //wxLogDebug(wxT("PositionCaret"));
3602 if (GetCaretPositionForIndex(GetCaretPosition(), caretRect
, container
))
3604 wxPoint newPt
= caretRect
.GetPosition();
3605 wxSize newSz
= caretRect
.GetSize();
3606 wxPoint pt
= GetPhysicalPoint(newPt
);
3607 if (GetCaret()->GetPosition() != pt
|| GetCaret()->GetSize() != newSz
)
3610 if (GetCaret()->GetSize() != newSz
)
3611 GetCaret()->SetSize(newSz
);
3613 // Adjust size so the caret size and position doesn't appear in the margins
3614 if (((pt
.y
+ newSz
.y
) <= GetBuffer().GetTopMargin()) || (pt
.y
>= (GetClientSize().y
- GetBuffer().GetBottomMargin())))
3619 else if (pt
.y
< GetBuffer().GetTopMargin() && (pt
.y
+ newSz
.y
) > GetBuffer().GetTopMargin())
3621 newSz
.y
-= (GetBuffer().GetTopMargin() - pt
.y
);
3624 pt
.y
= GetBuffer().GetTopMargin();
3625 GetCaret()->SetSize(newSz
);
3628 else if (pt
.y
< (GetClientSize().y
- GetBuffer().GetBottomMargin()) && (pt
.y
+ newSz
.y
) > (GetClientSize().y
- GetBuffer().GetBottomMargin()))
3630 newSz
.y
= GetClientSize().y
- GetBuffer().GetBottomMargin() - pt
.y
;
3631 GetCaret()->SetSize(newSz
);
3634 GetCaret()->Move(pt
);
3640 /// Get the caret height and position for the given character position
3641 bool wxRichTextCtrl::GetCaretPositionForIndex(long position
, wxRect
& rect
, wxRichTextParagraphLayoutBox
* container
)
3643 wxClientDC
dc(this);
3644 dc
.SetFont(GetFont());
3652 container
= GetFocusObject();
3654 if (container
->FindPosition(dc
, position
, pt
, & height
, m_caretAtLineStart
))
3656 // Caret height can't be zero
3658 height
= dc
.GetCharHeight();
3660 rect
= wxRect(pt
, wxSize(wxRICHTEXT_DEFAULT_CARET_WIDTH
, height
));
3667 /// Gets the line for the visible caret position. If the caret is
3668 /// shown at the very end of the line, it means the next character is actually
3669 /// on the following line. So let's get the line we're expecting to find
3670 /// if this is the case.
3671 wxRichTextLine
* wxRichTextCtrl::GetVisibleLineForCaretPosition(long caretPosition
) const
3673 wxRichTextLine
* line
= GetFocusObject()->GetLineAtPosition(caretPosition
, true);
3674 wxRichTextParagraph
* para
= GetFocusObject()->GetParagraphAtPosition(caretPosition
, true);
3677 wxRichTextRange lineRange
= line
->GetAbsoluteRange();
3678 if (caretPosition
== lineRange
.GetStart()-1 &&
3679 (para
->GetRange().GetStart() != lineRange
.GetStart()))
3681 if (!m_caretAtLineStart
)
3682 line
= GetFocusObject()->GetLineAtPosition(caretPosition
-1, true);
3689 /// Move the caret to the given character position
3690 bool wxRichTextCtrl::MoveCaret(long pos
, bool showAtLineStart
, wxRichTextParagraphLayoutBox
* container
)
3692 if (GetBuffer().IsDirty())
3696 container
= GetFocusObject();
3698 if (pos
<= container
->GetOwnRange().GetEnd())
3700 SetCaretPosition(pos
, showAtLineStart
);
3702 PositionCaret(container
);
3710 /// Layout the buffer: which we must do before certain operations, such as
3711 /// setting the caret position.
3712 bool wxRichTextCtrl::LayoutContent(bool onlyVisibleRect
)
3714 if (GetBuffer().IsDirty() || onlyVisibleRect
)
3716 wxRect
availableSpace(GetClientSize());
3717 if (availableSpace
.width
== 0)
3718 availableSpace
.width
= 10;
3719 if (availableSpace
.height
== 0)
3720 availableSpace
.height
= 10;
3722 int flags
= wxRICHTEXT_FIXED_WIDTH
|wxRICHTEXT_VARIABLE_HEIGHT
;
3723 if (onlyVisibleRect
)
3725 flags
|= wxRICHTEXT_LAYOUT_SPECIFIED_RECT
;
3726 availableSpace
.SetPosition(GetLogicalPoint(wxPoint(0, 0)));
3729 wxClientDC
dc(this);
3730 dc
.SetFont(GetFont());
3734 GetBuffer().Defragment();
3735 GetBuffer().UpdateRanges(); // If items were deleted, ranges need recalculation
3736 GetBuffer().Layout(dc
, availableSpace
, flags
);
3737 GetBuffer().Invalidate(wxRICHTEXT_NONE
);
3746 /// Is all of the selection, or the current caret position, bold?
3747 bool wxRichTextCtrl::IsSelectionBold()
3751 wxRichTextAttr attr
;
3752 wxRichTextRange range
= GetSelectionRange();
3753 attr
.SetFlags(wxTEXT_ATTR_FONT_WEIGHT
);
3754 attr
.SetFontWeight(wxFONTWEIGHT_BOLD
);
3756 return HasCharacterAttributes(range
, attr
);
3760 // If no selection, then we need to combine current style with default style
3761 // to see what the effect would be if we started typing.
3762 wxRichTextAttr attr
;
3763 attr
.SetFlags(wxTEXT_ATTR_FONT_WEIGHT
);
3765 long pos
= GetAdjustedCaretPosition(GetCaretPosition());
3766 if (GetStyle(pos
, attr
))
3768 if (IsDefaultStyleShowing())
3769 wxRichTextApplyStyle(attr
, GetDefaultStyleEx());
3770 return attr
.GetFontWeight() == wxFONTWEIGHT_BOLD
;
3776 /// Is all of the selection, or the current caret position, italics?
3777 bool wxRichTextCtrl::IsSelectionItalics()
3781 wxRichTextRange range
= GetSelectionRange();
3782 wxRichTextAttr attr
;
3783 attr
.SetFlags(wxTEXT_ATTR_FONT_ITALIC
);
3784 attr
.SetFontStyle(wxFONTSTYLE_ITALIC
);
3786 return HasCharacterAttributes(range
, attr
);
3790 // If no selection, then we need to combine current style with default style
3791 // to see what the effect would be if we started typing.
3792 wxRichTextAttr attr
;
3793 attr
.SetFlags(wxTEXT_ATTR_FONT_ITALIC
);
3795 long pos
= GetAdjustedCaretPosition(GetCaretPosition());
3796 if (GetStyle(pos
, attr
))
3798 if (IsDefaultStyleShowing())
3799 wxRichTextApplyStyle(attr
, GetDefaultStyleEx());
3800 return attr
.GetFontStyle() == wxFONTSTYLE_ITALIC
;
3806 /// Is all of the selection, or the current caret position, underlined?
3807 bool wxRichTextCtrl::IsSelectionUnderlined()
3811 wxRichTextRange range
= GetSelectionRange();
3812 wxRichTextAttr attr
;
3813 attr
.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE
);
3814 attr
.SetFontUnderlined(true);
3816 return HasCharacterAttributes(range
, attr
);
3820 // If no selection, then we need to combine current style with default style
3821 // to see what the effect would be if we started typing.
3822 wxRichTextAttr attr
;
3823 attr
.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE
);
3824 long pos
= GetAdjustedCaretPosition(GetCaretPosition());
3826 if (GetStyle(pos
, attr
))
3828 if (IsDefaultStyleShowing())
3829 wxRichTextApplyStyle(attr
, GetDefaultStyleEx());
3830 return attr
.GetFontUnderlined();
3836 /// Does all of the selection, or the current caret position, have this wxTextAttrEffects flag(s)?
3837 bool wxRichTextCtrl::DoesSelectionHaveTextEffectFlag(int flag
)
3839 wxRichTextAttr attr
;
3840 attr
.SetFlags(wxTEXT_ATTR_EFFECTS
);
3841 attr
.SetTextEffectFlags(flag
);
3842 attr
.SetTextEffects(flag
);
3846 return HasCharacterAttributes(GetSelectionRange(), attr
);
3850 // If no selection, then we need to combine current style with default style
3851 // to see what the effect would be if we started typing.
3852 long pos
= GetAdjustedCaretPosition(GetCaretPosition());
3853 if (GetStyle(pos
, attr
))
3855 if (IsDefaultStyleShowing())
3856 wxRichTextApplyStyle(attr
, GetDefaultStyleEx());
3857 return (attr
.GetTextEffectFlags() & flag
) != 0;
3863 /// Apply bold to the selection
3864 bool wxRichTextCtrl::ApplyBoldToSelection()
3866 wxRichTextAttr attr
;
3867 attr
.SetFlags(wxTEXT_ATTR_FONT_WEIGHT
);
3868 attr
.SetFontWeight(IsSelectionBold() ? wxFONTWEIGHT_NORMAL
: wxFONTWEIGHT_BOLD
);
3871 return SetStyleEx(GetSelectionRange(), attr
, wxRICHTEXT_SETSTYLE_WITH_UNDO
|wxRICHTEXT_SETSTYLE_OPTIMIZE
|wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY
);
3874 wxRichTextAttr current
= GetDefaultStyleEx();
3875 current
.Apply(attr
);
3876 SetAndShowDefaultStyle(current
);
3881 /// Apply italic to the selection
3882 bool wxRichTextCtrl::ApplyItalicToSelection()
3884 wxRichTextAttr attr
;
3885 attr
.SetFlags(wxTEXT_ATTR_FONT_ITALIC
);
3886 attr
.SetFontStyle(IsSelectionItalics() ? wxFONTSTYLE_NORMAL
: wxFONTSTYLE_ITALIC
);
3889 return SetStyleEx(GetSelectionRange(), attr
, wxRICHTEXT_SETSTYLE_WITH_UNDO
|wxRICHTEXT_SETSTYLE_OPTIMIZE
|wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY
);
3892 wxRichTextAttr current
= GetDefaultStyleEx();
3893 current
.Apply(attr
);
3894 SetAndShowDefaultStyle(current
);
3899 /// Apply underline to the selection
3900 bool wxRichTextCtrl::ApplyUnderlineToSelection()
3902 wxRichTextAttr attr
;
3903 attr
.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE
);
3904 attr
.SetFontUnderlined(!IsSelectionUnderlined());
3907 return SetStyleEx(GetSelectionRange(), attr
, wxRICHTEXT_SETSTYLE_WITH_UNDO
|wxRICHTEXT_SETSTYLE_OPTIMIZE
|wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY
);
3910 wxRichTextAttr current
= GetDefaultStyleEx();
3911 current
.Apply(attr
);
3912 SetAndShowDefaultStyle(current
);
3917 /// Apply the wxTextAttrEffects flag(s) to the selection, or the current caret position if there's no selection
3918 bool wxRichTextCtrl::ApplyTextEffectToSelection(int flags
)
3920 wxRichTextAttr attr
;
3921 attr
.SetFlags(wxTEXT_ATTR_EFFECTS
);
3922 attr
.SetTextEffectFlags(flags
);
3923 if (!DoesSelectionHaveTextEffectFlag(flags
))
3924 attr
.SetTextEffects(flags
);
3926 attr
.SetTextEffects(attr
.GetTextEffectFlags() & ~flags
);
3929 return SetStyleEx(GetSelectionRange(), attr
, wxRICHTEXT_SETSTYLE_WITH_UNDO
|wxRICHTEXT_SETSTYLE_OPTIMIZE
|wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY
);
3932 wxRichTextAttr current
= GetDefaultStyleEx();
3933 current
.Apply(attr
);
3934 SetAndShowDefaultStyle(current
);
3939 /// Is all of the selection aligned according to the specified flag?
3940 bool wxRichTextCtrl::IsSelectionAligned(wxTextAttrAlignment alignment
)
3942 wxRichTextRange range
;
3944 range
= GetSelectionRange();
3946 range
= wxRichTextRange(GetCaretPosition()+1, GetCaretPosition()+2);
3948 wxRichTextAttr attr
;
3949 attr
.SetAlignment(alignment
);
3951 return HasParagraphAttributes(range
, attr
);
3954 /// Apply alignment to the selection
3955 bool wxRichTextCtrl::ApplyAlignmentToSelection(wxTextAttrAlignment alignment
)
3957 wxRichTextAttr attr
;
3958 attr
.SetAlignment(alignment
);
3960 return SetStyle(GetSelectionRange(), attr
);
3963 wxRichTextParagraph
* para
= GetFocusObject()->GetParagraphAtPosition(GetCaretPosition()+1);
3965 return SetStyleEx(para
->GetRange().FromInternal(), attr
, wxRICHTEXT_SETSTYLE_WITH_UNDO
|wxRICHTEXT_SETSTYLE_OPTIMIZE
|wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY
);
3970 /// Apply a named style to the selection
3971 bool wxRichTextCtrl::ApplyStyle(wxRichTextStyleDefinition
* def
)
3973 // Flags are defined within each definition, so only certain
3974 // attributes are applied.
3975 wxRichTextAttr
attr(GetStyleSheet() ? def
->GetStyleMergedWithBase(GetStyleSheet()) : def
->GetStyle());
3977 int flags
= wxRICHTEXT_SETSTYLE_WITH_UNDO
|wxRICHTEXT_SETSTYLE_OPTIMIZE
|wxRICHTEXT_SETSTYLE_RESET
;
3979 if (def
->IsKindOf(CLASSINFO(wxRichTextListStyleDefinition
)))
3981 flags
|= wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY
;
3983 wxRichTextRange range
;
3986 range
= GetSelectionRange();
3989 long pos
= GetAdjustedCaretPosition(GetCaretPosition());
3990 range
= wxRichTextRange(pos
, pos
+1);
3993 return SetListStyle(range
, (wxRichTextListStyleDefinition
*) def
, flags
);
3996 bool isPara
= false;
3998 // Make sure the attr has the style name
3999 if (def
->IsKindOf(CLASSINFO(wxRichTextParagraphStyleDefinition
)))
4002 attr
.SetParagraphStyleName(def
->GetName());
4004 // If applying a paragraph style, we only want the paragraph nodes to adopt these
4005 // attributes, and not the leaf nodes. This will allow the content (e.g. text)
4006 // to change its style independently.
4007 flags
|= wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY
;
4010 attr
.SetCharacterStyleName(def
->GetName());
4013 return SetStyleEx(GetSelectionRange(), attr
, flags
);
4016 wxRichTextAttr current
= GetDefaultStyleEx();
4017 wxRichTextAttr
defaultStyle(attr
);
4020 // Don't apply extra character styles since they are already implied
4021 // in the paragraph style
4022 defaultStyle
.SetFlags(defaultStyle
.GetFlags() & ~wxTEXT_ATTR_CHARACTER
);
4024 current
.Apply(defaultStyle
);
4025 SetAndShowDefaultStyle(current
);
4027 // If it's a paragraph style, we want to apply the style to the
4028 // current paragraph even if we didn't select any text.
4031 long pos
= GetAdjustedCaretPosition(GetCaretPosition());
4032 wxRichTextParagraph
* para
= GetFocusObject()->GetParagraphAtPosition(pos
);
4035 return SetStyleEx(para
->GetRange().FromInternal(), attr
, flags
);
4042 /// Apply the style sheet to the buffer, for example if the styles have changed.
4043 bool wxRichTextCtrl::ApplyStyleSheet(wxRichTextStyleSheet
* styleSheet
)
4046 styleSheet
= GetBuffer().GetStyleSheet();
4050 if (GetBuffer().ApplyStyleSheet(styleSheet
))
4052 GetBuffer().Invalidate(wxRICHTEXT_ALL
);
4060 /// Sets the default style to the style under the cursor
4061 bool wxRichTextCtrl::SetDefaultStyleToCursorStyle()
4063 wxRichTextAttr attr
;
4064 attr
.SetFlags(wxTEXT_ATTR_CHARACTER
);
4066 // If at the start of a paragraph, use the next position.
4067 long pos
= GetAdjustedCaretPosition(GetCaretPosition());
4069 if (GetUncombinedStyle(pos
, attr
))
4071 SetDefaultStyle(attr
);
4078 /// Returns the first visible position in the current view
4079 long wxRichTextCtrl::GetFirstVisiblePosition() const
4081 wxRichTextLine
* line
= GetFocusObject()->GetLineAtYPosition(GetLogicalPoint(wxPoint(0, 0)).y
);
4083 return line
->GetAbsoluteRange().GetStart();
4088 /// Get the first visible point in the window
4089 wxPoint
wxRichTextCtrl::GetFirstVisiblePoint() const
4092 int startXUnits
, startYUnits
;
4094 GetScrollPixelsPerUnit(& ppuX
, & ppuY
);
4095 GetViewStart(& startXUnits
, & startYUnits
);
4097 return wxPoint(startXUnits
* ppuX
, startYUnits
* ppuY
);
4100 /// The adjusted caret position is the character position adjusted to take
4101 /// into account whether we're at the start of a paragraph, in which case
4102 /// style information should be taken from the next position, not current one.
4103 long wxRichTextCtrl::GetAdjustedCaretPosition(long caretPos
) const
4105 wxRichTextParagraph
* para
= GetFocusObject()->GetParagraphAtPosition(caretPos
+1);
4107 if (para
&& (caretPos
+1 == para
->GetRange().GetStart()))
4112 /// Get/set the selection range in character positions. -1, -1 means no selection.
4113 /// The range is in API convention, i.e. a single character selection is denoted
4115 wxRichTextRange
wxRichTextCtrl::GetSelectionRange() const
4117 wxRichTextRange range
= GetInternalSelectionRange();
4118 if (range
!= wxRichTextRange(-2,-2) && range
!= wxRichTextRange(-1,-1))
4119 range
.SetEnd(range
.GetEnd() + 1);
4123 void wxRichTextCtrl::SetSelectionRange(const wxRichTextRange
& range
)
4125 SetSelection(range
.GetStart(), range
.GetEnd());
4129 bool wxRichTextCtrl::SetListStyle(const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
4131 return GetFocusObject()->SetListStyle(range
.ToInternal(), def
, flags
, startFrom
, specifiedLevel
);
4134 bool wxRichTextCtrl::SetListStyle(const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int startFrom
, int specifiedLevel
)
4136 return GetFocusObject()->SetListStyle(range
.ToInternal(), defName
, flags
, startFrom
, specifiedLevel
);
4139 /// Clear list for given range
4140 bool wxRichTextCtrl::ClearListStyle(const wxRichTextRange
& range
, int flags
)
4142 return GetFocusObject()->ClearListStyle(range
.ToInternal(), flags
);
4145 /// Number/renumber any list elements in the given range
4146 bool wxRichTextCtrl::NumberList(const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int startFrom
, int specifiedLevel
)
4148 return GetFocusObject()->NumberList(range
.ToInternal(), def
, flags
, startFrom
, specifiedLevel
);
4151 bool wxRichTextCtrl::NumberList(const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int startFrom
, int specifiedLevel
)
4153 return GetFocusObject()->NumberList(range
.ToInternal(), defName
, flags
, startFrom
, specifiedLevel
);
4156 /// Promote the list items within the given range. promoteBy can be a positive or negative number, e.g. 1 or -1
4157 bool wxRichTextCtrl::PromoteList(int promoteBy
, const wxRichTextRange
& range
, wxRichTextListStyleDefinition
* def
, int flags
, int specifiedLevel
)
4159 return GetFocusObject()->PromoteList(promoteBy
, range
.ToInternal(), def
, flags
, specifiedLevel
);
4162 bool wxRichTextCtrl::PromoteList(int promoteBy
, const wxRichTextRange
& range
, const wxString
& defName
, int flags
, int specifiedLevel
)
4164 return GetFocusObject()->PromoteList(promoteBy
, range
.ToInternal(), defName
, flags
, specifiedLevel
);
4167 /// Deletes the content in the given range
4168 bool wxRichTextCtrl::Delete(const wxRichTextRange
& range
)
4170 return GetFocusObject()->DeleteRangeWithUndo(range
.ToInternal(), this, & GetBuffer());
4173 const wxArrayString
& wxRichTextCtrl::GetAvailableFontNames()
4175 if (sm_availableFontNames
.GetCount() == 0)
4177 sm_availableFontNames
= wxFontEnumerator::GetFacenames();
4178 sm_availableFontNames
.Sort();
4180 return sm_availableFontNames
;
4183 void wxRichTextCtrl::ClearAvailableFontNames()
4185 sm_availableFontNames
.Clear();
4188 void wxRichTextCtrl::OnSysColourChanged(wxSysColourChangedEvent
& WXUNUSED(event
))
4190 //wxLogDebug(wxT("wxRichTextCtrl::OnSysColourChanged"));
4192 wxTextAttrEx basicStyle
= GetBasicStyle();
4193 basicStyle
.SetTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT
));
4194 SetBasicStyle(basicStyle
);
4195 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
));
4200 // Refresh the area affected by a selection change
4201 bool wxRichTextCtrl::RefreshForSelectionChange(const wxRichTextSelection
& oldSelection
, const wxRichTextSelection
& newSelection
)
4203 // If the selection is not part of the focus object, or we have multiple ranges, then the chances are that
4204 // the selection contains whole containers rather than just text, so refresh everything
4205 // for now as it would be hard to compute the rectangle bounding all selections.
4206 // TODO: improve on this.
4207 if ((oldSelection
.IsValid() && (oldSelection
.GetContainer() != GetFocusObject() || oldSelection
.GetCount() > 1)) ||
4208 (newSelection
.IsValid() && (newSelection
.GetContainer() != GetFocusObject() || newSelection
.GetCount() > 1)))
4214 wxRichTextRange oldRange
, newRange
;
4215 if (oldSelection
.IsValid())
4216 oldRange
= oldSelection
.GetRange();
4218 oldRange
= wxRICHTEXT_NO_SELECTION
;
4219 if (newSelection
.IsValid())
4220 newRange
= newSelection
.GetRange();
4222 newRange
= wxRICHTEXT_NO_SELECTION
;
4224 // Calculate the refresh rectangle - just the affected lines
4225 long firstPos
, lastPos
;
4226 if (oldRange
.GetStart() == -2 && newRange
.GetStart() != -2)
4228 firstPos
= newRange
.GetStart();
4229 lastPos
= newRange
.GetEnd();
4231 else if (oldRange
.GetStart() != -2 && newRange
.GetStart() == -2)
4233 firstPos
= oldRange
.GetStart();
4234 lastPos
= oldRange
.GetEnd();
4236 else if (oldRange
.GetStart() == -2 && newRange
.GetStart() == -2)
4242 firstPos
= wxMin(oldRange
.GetStart(), newRange
.GetStart());
4243 lastPos
= wxMax(oldRange
.GetEnd(), newRange
.GetEnd());
4246 wxRichTextLine
* firstLine
= GetFocusObject()->GetLineAtPosition(firstPos
);
4247 wxRichTextLine
* lastLine
= GetFocusObject()->GetLineAtPosition(lastPos
);
4249 if (firstLine
&& lastLine
)
4251 wxSize clientSize
= GetClientSize();
4252 wxPoint pt1
= GetPhysicalPoint(firstLine
->GetAbsolutePosition());
4253 wxPoint pt2
= GetPhysicalPoint(lastLine
->GetAbsolutePosition()) + wxPoint(0, lastLine
->GetSize().y
);
4256 pt1
.y
= wxMax(0, pt1
.y
);
4258 pt2
.y
= wxMin(clientSize
.y
, pt2
.y
);
4260 wxRect
rect(pt1
, wxSize(clientSize
.x
, pt2
.y
- pt1
.y
));
4261 RefreshRect(rect
, false);
4269 // margins functions
4270 bool wxRichTextCtrl::DoSetMargins(const wxPoint
& pt
)
4272 GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetLeft().SetValue(pt
.x
, wxTEXT_ATTR_UNITS_PIXELS
);
4273 GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetRight().SetValue(pt
.x
, wxTEXT_ATTR_UNITS_PIXELS
);
4274 GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetTop().SetValue(pt
.y
, wxTEXT_ATTR_UNITS_PIXELS
);
4275 GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetBottom().SetValue(pt
.y
, wxTEXT_ATTR_UNITS_PIXELS
);
4280 wxPoint
wxRichTextCtrl::DoGetMargins() const
4282 return wxPoint(GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetLeft().GetValue(),
4283 GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetTop().GetValue());
4286 bool wxRichTextCtrl::SetFocusObject(wxRichTextParagraphLayoutBox
* obj
, bool setCaretPosition
)
4288 if (obj
&& !obj
->AcceptsFocus())
4291 wxRichTextParagraphLayoutBox
* oldContainer
= GetFocusObject();
4292 bool changingContainer
= (m_focusObject
!= obj
);
4294 if (changingContainer
&& HasSelection())
4297 m_focusObject
= obj
;
4300 m_focusObject
= & m_buffer
;
4302 if (setCaretPosition
&& changingContainer
)
4304 m_selection
.Reset();
4305 m_selectionAnchor
= -2;
4306 m_selectionAnchorObject
= NULL
;
4307 m_selectionState
= wxRichTextCtrlSelectionState_Normal
;
4311 m_caretAtLineStart
= false;
4312 MoveCaret(pos
, m_caretAtLineStart
);
4313 SetDefaultStyleToCursorStyle();
4315 wxRichTextEvent
cmdEvent(
4316 wxEVT_COMMAND_RICHTEXT_FOCUS_OBJECT_CHANGED
,
4318 cmdEvent
.SetEventObject(this);
4319 cmdEvent
.SetPosition(m_caretPosition
+1);
4320 cmdEvent
.SetOldContainer(oldContainer
);
4321 cmdEvent
.SetContainer(m_focusObject
);
4323 GetEventHandler()->ProcessEvent(cmdEvent
);
4328 #if wxUSE_DRAG_AND_DROP
4329 void wxRichTextCtrl::OnDrop(wxCoord
WXUNUSED(x
), wxCoord
WXUNUSED(y
), wxDragResult def
, wxDataObject
* DataObj
)
4333 if ((def
!= wxDragCopy
) && (def
!= wxDragMove
))
4338 if (!GetSelection().IsValid())
4343 wxRichTextParagraphLayoutBox
* originContainer
= GetSelection().GetContainer();
4344 wxRichTextParagraphLayoutBox
* destContainer
= GetFocusObject(); // This will be the drop container, not necessarily the same as the origin one
4347 wxRichTextBuffer
* richTextBuffer
= ((wxRichTextBufferDataObject
*)DataObj
)->GetRichTextBuffer();
4350 long position
= GetCaretPosition();
4351 wxRichTextRange selectionrange
= GetInternalSelectionRange();
4352 if (selectionrange
.Contains(position
) && (def
== wxDragMove
))
4354 // It doesn't make sense to move onto itself
4358 // If we're moving, and the data is being moved forward, we need to drop first, then delete the selection
4359 // If moving backwards, we need to delete then drop. If we're copying (or doing nothing) we don't delete anyway
4360 bool DeleteAfter
= (def
== wxDragMove
) && (position
> selectionrange
.GetEnd());
4361 if ((def
== wxDragMove
) && !DeleteAfter
)
4363 // We can't use e.g. DeleteSelectedContent() as it uses the focus container
4364 originContainer
->DeleteRangeWithUndo(selectionrange
, this, &GetBuffer());
4367 destContainer
->InsertParagraphsWithUndo(position
+1, *richTextBuffer
, this, &GetBuffer(), 0);
4368 ShowPosition(position
+ richTextBuffer
->GetOwnRange().GetEnd());
4370 delete richTextBuffer
;
4374 // We can't use e.g. DeleteSelectedContent() as it uses the focus container
4375 originContainer
->DeleteRangeWithUndo(selectionrange
, this, &GetBuffer());
4383 #endif // wxUSE_DRAG_AND_DROP
4386 #if wxUSE_DRAG_AND_DROP
4387 bool wxRichTextDropSource::GiveFeedback(wxDragResult
WXUNUSED(effect
))
4389 wxCHECK_MSG(m_rtc
, false, wxT("NULL m_rtc"));
4393 wxRichTextObject
* hitObj
= NULL
;
4394 wxRichTextParagraphLayoutBox
* container
= m_rtc
->FindContainerAtPoint(m_rtc
->ScreenToClient(wxGetMousePosition()), position
, hit
, hitObj
);
4396 if (!(hit
& wxRICHTEXT_HITTEST_NONE
) && container
&& container
->AcceptsFocus())
4398 m_rtc
->StoreFocusObject(container
);
4399 m_rtc
->SetCaretPositionAfterClick(container
, position
, hit
);
4402 return false; // so that the base-class sets a cursor
4404 #endif // wxUSE_DRAG_AND_DROP
4407 #if wxRICHTEXT_USE_OWN_CARET
4409 // ----------------------------------------------------------------------------
4410 // initialization and destruction
4411 // ----------------------------------------------------------------------------
4413 void wxRichTextCaret::Init()
4419 m_richTextCtrl
= NULL
;
4420 m_needsUpdate
= false;
4424 wxRichTextCaret::~wxRichTextCaret()
4426 if (m_timer
.IsRunning())
4430 // ----------------------------------------------------------------------------
4431 // showing/hiding/moving the caret (base class interface)
4432 // ----------------------------------------------------------------------------
4434 void wxRichTextCaret::DoShow()
4438 if (!m_timer
.IsRunning())
4439 m_timer
.Start(GetBlinkTime());
4444 void wxRichTextCaret::DoHide()
4446 if (m_timer
.IsRunning())
4452 void wxRichTextCaret::DoMove()
4458 if (m_xOld
!= -1 && m_yOld
!= -1)
4462 wxRect
rect(GetPosition(), GetSize());
4463 m_richTextCtrl
->RefreshRect(rect
, false);
4472 void wxRichTextCaret::DoSize()
4474 int countVisible
= m_countVisible
;
4475 if (countVisible
> 0)
4481 if (countVisible
> 0)
4483 m_countVisible
= countVisible
;
4488 // ----------------------------------------------------------------------------
4489 // handling the focus
4490 // ----------------------------------------------------------------------------
4492 void wxRichTextCaret::OnSetFocus()
4500 void wxRichTextCaret::OnKillFocus()
4505 // ----------------------------------------------------------------------------
4506 // drawing the caret
4507 // ----------------------------------------------------------------------------
4509 void wxRichTextCaret::Refresh()
4513 wxRect
rect(GetPosition(), GetSize());
4514 m_richTextCtrl
->RefreshRect(rect
, false);
4518 void wxRichTextCaret::DoDraw(wxDC
*dc
)
4520 dc
->SetPen( *wxBLACK_PEN
);
4522 dc
->SetBrush(*(m_hasFocus
? wxBLACK_BRUSH
: wxTRANSPARENT_BRUSH
));
4523 dc
->SetPen(*wxBLACK_PEN
);
4525 wxPoint
pt(m_x
, m_y
);
4529 pt
= m_richTextCtrl
->GetLogicalPoint(pt
);
4531 if (IsVisible() && m_flashOn
)
4532 dc
->DrawRectangle(pt
.x
, pt
.y
, m_width
, m_height
);
4535 void wxRichTextCaret::Notify()
4537 m_flashOn
= !m_flashOn
;
4541 void wxRichTextCaretTimer::Notify()
4546 // wxRICHTEXT_USE_OWN_CARET
4549 bool wxRichTextContextMenuPropertiesInfo::AddItem(const wxString
& label
, wxRichTextObject
* obj
)
4553 m_labels
.Add(label
);
4561 // Returns number of menu items were added.
4562 int wxRichTextContextMenuPropertiesInfo::AddMenuItems(wxMenu
* menu
, int startCmd
) const
4564 wxMenuItem
* item
= menu
->FindItem(startCmd
);
4565 // If none of the standard properties identifiers are in the menu, add them if necessary.
4566 // If no items to add, just set the text to something generic
4567 if (GetCount() == 0)
4571 menu
->SetLabel(startCmd
, _("&Properties"));
4573 // Delete the others if necessary
4575 for (i
= startCmd
+1; i
< startCmd
+3; i
++)
4577 if (menu
->FindItem(i
))
4588 // Find the position of the first properties item
4589 for (i
= 0; i
< (int) menu
->GetMenuItemCount(); i
++)
4591 wxMenuItem
* item
= menu
->FindItemByPosition(i
);
4592 if (item
&& item
->GetId() == startCmd
)
4601 int insertBefore
= pos
+1;
4602 for (i
= startCmd
; i
< startCmd
+GetCount(); i
++)
4604 if (menu
->FindItem(i
))
4606 menu
->SetLabel(i
, m_labels
[i
- startCmd
]);
4610 if (insertBefore
>= (int) menu
->GetMenuItemCount())
4611 menu
->Append(i
, m_labels
[i
- startCmd
]);
4613 menu
->Insert(insertBefore
, i
, m_labels
[i
- startCmd
]);
4618 // Delete any old items still left on the menu
4619 for (i
= startCmd
+ GetCount(); i
< startCmd
+3; i
++)
4621 if (menu
->FindItem(i
))
4629 // No existing property identifiers were found, so append to the end of the menu.
4630 menu
->AppendSeparator();
4631 for (i
= startCmd
; i
< startCmd
+GetCount(); i
++)
4633 menu
->Append(i
, m_labels
[i
- startCmd
]);
4641 // Add appropriate menu items for the current container and clicked on object
4642 // (and container's parent, if appropriate).
4643 int wxRichTextContextMenuPropertiesInfo::AddItems(wxRichTextObject
* container
, wxRichTextObject
* obj
)
4646 if (obj
&& obj
->CanEditProperties())
4647 AddItem(obj
->GetPropertiesMenuLabel(), obj
);
4649 if (container
&& container
!= obj
&& container
->CanEditProperties() && m_labels
.Index(container
->GetPropertiesMenuLabel()) == wxNOT_FOUND
)
4650 AddItem(container
->GetPropertiesMenuLabel(), container
);
4652 if (container
&& container
->GetParent() && container
->GetParent()->CanEditProperties() && m_labels
.Index(container
->GetParent()->GetPropertiesMenuLabel()) == wxNOT_FOUND
)
4653 AddItem(container
->GetParent()->GetPropertiesMenuLabel(), container
->GetParent());